babylon.max.js 5.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318
  1. (function universalModuleDefinition(root, factory) {
  2. var amdDependencies = [];
  3. var CANNON = root.CANNON || this.CANNON;
  4. var OIMO = root.OIMO || this.OIMO;
  5. var earcut = root.earcut || this.earcut;
  6. if(typeof exports === 'object' && typeof module === 'object') {
  7. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  8. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  9. try { earcut = earcut || require("earcut"); } catch(e) {}
  10. module.exports = factory(CANNON,OIMO,earcut);
  11. } else if(typeof define === 'function' && define.amd) {
  12. if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
  13. if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
  14. if(require.specified && require.specified("earcut")) amdDependencies.push("earcut");
  15. define("babylonjs", amdDependencies, factory);
  16. } else if(typeof exports === 'object') {
  17. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  18. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  19. try { earcut = earcut || require("earcut"); } catch(e) {}
  20. exports["babylonjs"] = factory(CANNON,OIMO,earcut);
  21. } else {
  22. root["BABYLON"] = factory(CANNON,OIMO,earcut);
  23. }
  24. })(this, function(CANNON,OIMO,earcut) {
  25. CANNON = CANNON || this.CANNON;
  26. OIMO = OIMO || this.OIMO;
  27. earcut = earcut || this.earcut;
  28. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  29. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  30. var BABYLON;
  31. (function (BABYLON) {
  32. /**
  33. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  34. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  35. */
  36. var EffectFallbacks = /** @class */ (function () {
  37. function EffectFallbacks() {
  38. this._defines = {};
  39. this._currentRank = 32;
  40. this._maxRank = -1;
  41. }
  42. /**
  43. * Removes the fallback from the bound mesh.
  44. */
  45. EffectFallbacks.prototype.unBindMesh = function () {
  46. this._mesh = null;
  47. };
  48. /**
  49. * Adds a fallback on the specified property.
  50. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  51. * @param define The name of the define in the shader
  52. */
  53. EffectFallbacks.prototype.addFallback = function (rank, define) {
  54. if (!this._defines[rank]) {
  55. if (rank < this._currentRank) {
  56. this._currentRank = rank;
  57. }
  58. if (rank > this._maxRank) {
  59. this._maxRank = rank;
  60. }
  61. this._defines[rank] = new Array();
  62. }
  63. this._defines[rank].push(define);
  64. };
  65. /**
  66. * Sets the mesh to use CPU skinning when needing to fallback.
  67. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  68. * @param mesh The mesh to use the fallbacks.
  69. */
  70. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  71. this._mesh = mesh;
  72. if (rank < this._currentRank) {
  73. this._currentRank = rank;
  74. }
  75. if (rank > this._maxRank) {
  76. this._maxRank = rank;
  77. }
  78. };
  79. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  80. /**
  81. * Checks to see if more fallbacks are still availible.
  82. */
  83. get: function () {
  84. return this._currentRank <= this._maxRank;
  85. },
  86. enumerable: true,
  87. configurable: true
  88. });
  89. /**
  90. * Removes the defines that shoould be removed when falling back.
  91. * @param currentDefines defines the current define statements for the shader.
  92. * @param effect defines the current effect we try to compile
  93. * @returns The resulting defines with defines of the current rank removed.
  94. */
  95. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  96. // First we try to switch to CPU skinning
  97. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  98. this._mesh.computeBonesUsingShaders = false;
  99. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  100. effect._bonesComputationForcedToCPU = true;
  101. var scene = this._mesh.getScene();
  102. for (var index = 0; index < scene.meshes.length; index++) {
  103. var otherMesh = scene.meshes[index];
  104. if (!otherMesh.material) {
  105. continue;
  106. }
  107. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  108. continue;
  109. }
  110. if (otherMesh.material.getEffect() === effect) {
  111. otherMesh.computeBonesUsingShaders = false;
  112. }
  113. else if (otherMesh.subMeshes) {
  114. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  115. var subMesh = _a[_i];
  116. var subMeshEffect = subMesh.effect;
  117. if (subMeshEffect === effect) {
  118. otherMesh.computeBonesUsingShaders = false;
  119. break;
  120. }
  121. }
  122. }
  123. }
  124. }
  125. else {
  126. var currentFallbacks = this._defines[this._currentRank];
  127. if (currentFallbacks) {
  128. for (var index = 0; index < currentFallbacks.length; index++) {
  129. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  130. }
  131. }
  132. this._currentRank++;
  133. }
  134. return currentDefines;
  135. };
  136. return EffectFallbacks;
  137. }());
  138. BABYLON.EffectFallbacks = EffectFallbacks;
  139. /**
  140. * Options to be used when creating an effect.
  141. */
  142. var EffectCreationOptions = /** @class */ (function () {
  143. function EffectCreationOptions() {
  144. }
  145. return EffectCreationOptions;
  146. }());
  147. BABYLON.EffectCreationOptions = EffectCreationOptions;
  148. /**
  149. * Effect containing vertex and fragment shader that can be executed on an object.
  150. */
  151. var Effect = /** @class */ (function () {
  152. /**
  153. * Instantiates an effect.
  154. * An effect can be used to create/manage/execute vertex and fragment shaders.
  155. * @param baseName Name of the effect.
  156. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  157. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  158. * @param samplers List of sampler variables that will be passed to the shader.
  159. * @param engine Engine to be used to render the effect
  160. * @param defines Define statements to be added to the shader.
  161. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  162. * @param onCompiled Callback that will be called when the shader is compiled.
  163. * @param onError Callback that will be called if an error occurs during shader compilation.
  164. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  165. */
  166. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  167. if (samplers === void 0) { samplers = null; }
  168. if (defines === void 0) { defines = null; }
  169. if (fallbacks === void 0) { fallbacks = null; }
  170. if (onCompiled === void 0) { onCompiled = null; }
  171. if (onError === void 0) { onError = null; }
  172. var _this = this;
  173. /**
  174. * Unique ID of the effect.
  175. */
  176. this.uniqueId = 0;
  177. /**
  178. * Observable that will be called when the shader is compiled.
  179. */
  180. this.onCompileObservable = new BABYLON.Observable();
  181. /**
  182. * Observable that will be called if an error occurs during shader compilation.
  183. */
  184. this.onErrorObservable = new BABYLON.Observable();
  185. /** @hidden */
  186. this._bonesComputationForcedToCPU = false;
  187. this._uniformBuffersNames = {};
  188. this._isReady = false;
  189. this._compilationError = "";
  190. this.name = baseName;
  191. if (attributesNamesOrOptions.attributes) {
  192. var options = attributesNamesOrOptions;
  193. this._engine = uniformsNamesOrEngine;
  194. this._attributesNames = options.attributes;
  195. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  196. this._samplers = options.samplers.slice();
  197. this.defines = options.defines;
  198. this.onError = options.onError;
  199. this.onCompiled = options.onCompiled;
  200. this._fallbacks = options.fallbacks;
  201. this._indexParameters = options.indexParameters;
  202. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  203. if (options.uniformBuffersNames) {
  204. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  205. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  206. }
  207. }
  208. }
  209. else {
  210. this._engine = engine;
  211. this.defines = defines;
  212. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  213. this._samplers = samplers ? samplers.slice() : [];
  214. this._attributesNames = attributesNamesOrOptions;
  215. this.onError = onError;
  216. this.onCompiled = onCompiled;
  217. this._indexParameters = indexParameters;
  218. this._fallbacks = fallbacks;
  219. }
  220. this.uniqueId = Effect._uniqueIdSeed++;
  221. var vertexSource;
  222. var fragmentSource;
  223. if (baseName.vertexElement) {
  224. vertexSource = document.getElementById(baseName.vertexElement);
  225. if (!vertexSource) {
  226. vertexSource = baseName.vertexElement;
  227. }
  228. }
  229. else {
  230. vertexSource = baseName.vertex || baseName;
  231. }
  232. if (baseName.fragmentElement) {
  233. fragmentSource = document.getElementById(baseName.fragmentElement);
  234. if (!fragmentSource) {
  235. fragmentSource = baseName.fragmentElement;
  236. }
  237. }
  238. else {
  239. fragmentSource = baseName.fragment || baseName;
  240. }
  241. this._loadVertexShader(vertexSource, function (vertexCode) {
  242. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  243. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  244. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  245. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  246. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  247. if (baseName) {
  248. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  249. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  250. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  251. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  252. }
  253. else {
  254. _this._vertexSourceCode = migratedVertexCode;
  255. _this._fragmentSourceCode = migratedFragmentCode;
  256. }
  257. _this._prepareEffect();
  258. });
  259. });
  260. });
  261. });
  262. });
  263. });
  264. }
  265. Object.defineProperty(Effect.prototype, "onBindObservable", {
  266. /**
  267. * Observable that will be called when effect is bound.
  268. */
  269. get: function () {
  270. if (!this._onBindObservable) {
  271. this._onBindObservable = new BABYLON.Observable();
  272. }
  273. return this._onBindObservable;
  274. },
  275. enumerable: true,
  276. configurable: true
  277. });
  278. Object.defineProperty(Effect.prototype, "key", {
  279. /**
  280. * Unique key for this effect
  281. */
  282. get: function () {
  283. return this._key;
  284. },
  285. enumerable: true,
  286. configurable: true
  287. });
  288. /**
  289. * If the effect has been compiled and prepared.
  290. * @returns if the effect is compiled and prepared.
  291. */
  292. Effect.prototype.isReady = function () {
  293. return this._isReady;
  294. };
  295. /**
  296. * The engine the effect was initialized with.
  297. * @returns the engine.
  298. */
  299. Effect.prototype.getEngine = function () {
  300. return this._engine;
  301. };
  302. /**
  303. * The compiled webGL program for the effect
  304. * @returns the webGL program.
  305. */
  306. Effect.prototype.getProgram = function () {
  307. return this._program;
  308. };
  309. /**
  310. * The set of names of attribute variables for the shader.
  311. * @returns An array of attribute names.
  312. */
  313. Effect.prototype.getAttributesNames = function () {
  314. return this._attributesNames;
  315. };
  316. /**
  317. * Returns the attribute at the given index.
  318. * @param index The index of the attribute.
  319. * @returns The location of the attribute.
  320. */
  321. Effect.prototype.getAttributeLocation = function (index) {
  322. return this._attributes[index];
  323. };
  324. /**
  325. * Returns the attribute based on the name of the variable.
  326. * @param name of the attribute to look up.
  327. * @returns the attribute location.
  328. */
  329. Effect.prototype.getAttributeLocationByName = function (name) {
  330. var index = this._attributesNames.indexOf(name);
  331. return this._attributes[index];
  332. };
  333. /**
  334. * The number of attributes.
  335. * @returns the numnber of attributes.
  336. */
  337. Effect.prototype.getAttributesCount = function () {
  338. return this._attributes.length;
  339. };
  340. /**
  341. * Gets the index of a uniform variable.
  342. * @param uniformName of the uniform to look up.
  343. * @returns the index.
  344. */
  345. Effect.prototype.getUniformIndex = function (uniformName) {
  346. return this._uniformsNames.indexOf(uniformName);
  347. };
  348. /**
  349. * Returns the attribute based on the name of the variable.
  350. * @param uniformName of the uniform to look up.
  351. * @returns the location of the uniform.
  352. */
  353. Effect.prototype.getUniform = function (uniformName) {
  354. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  355. };
  356. /**
  357. * Returns an array of sampler variable names
  358. * @returns The array of sampler variable neames.
  359. */
  360. Effect.prototype.getSamplers = function () {
  361. return this._samplers;
  362. };
  363. /**
  364. * The error from the last compilation.
  365. * @returns the error string.
  366. */
  367. Effect.prototype.getCompilationError = function () {
  368. return this._compilationError;
  369. };
  370. /**
  371. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  372. * @param func The callback to be used.
  373. */
  374. Effect.prototype.executeWhenCompiled = function (func) {
  375. if (this.isReady()) {
  376. func(this);
  377. return;
  378. }
  379. this.onCompileObservable.add(function (effect) {
  380. func(effect);
  381. });
  382. };
  383. /** @hidden */
  384. Effect.prototype._loadVertexShader = function (vertex, callback) {
  385. if (BABYLON.Tools.IsWindowObjectExist()) {
  386. // DOM element ?
  387. if (vertex instanceof HTMLElement) {
  388. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  389. callback(vertexCode);
  390. return;
  391. }
  392. }
  393. // Base64 encoded ?
  394. if (vertex.substr(0, 7) === "base64:") {
  395. var vertexBinary = window.atob(vertex.substr(7));
  396. callback(vertexBinary);
  397. return;
  398. }
  399. // Is in local store ?
  400. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  401. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  402. return;
  403. }
  404. var vertexShaderUrl;
  405. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  406. vertexShaderUrl = vertex;
  407. }
  408. else {
  409. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  410. }
  411. // Vertex shader
  412. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  413. };
  414. /** @hidden */
  415. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  416. if (BABYLON.Tools.IsWindowObjectExist()) {
  417. // DOM element ?
  418. if (fragment instanceof HTMLElement) {
  419. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  420. callback(fragmentCode);
  421. return;
  422. }
  423. }
  424. // Base64 encoded ?
  425. if (fragment.substr(0, 7) === "base64:") {
  426. var fragmentBinary = window.atob(fragment.substr(7));
  427. callback(fragmentBinary);
  428. return;
  429. }
  430. // Is in local store ?
  431. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  432. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  433. return;
  434. }
  435. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  436. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  437. return;
  438. }
  439. var fragmentShaderUrl;
  440. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  441. fragmentShaderUrl = fragment;
  442. }
  443. else {
  444. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  445. }
  446. // Fragment shader
  447. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  448. };
  449. /** @hidden */
  450. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  451. // Rebuild shaders source code
  452. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  453. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  454. vertexCode = prefix + vertexCode;
  455. fragmentCode = prefix + fragmentCode;
  456. // Number lines of shaders source code
  457. var i = 2;
  458. var regex = /\n/gm;
  459. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  460. i = 2;
  461. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  462. // Dump shaders name and formatted source code
  463. if (this.name.vertexElement) {
  464. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  465. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  466. }
  467. else if (this.name.vertex) {
  468. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  469. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  470. }
  471. else {
  472. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  473. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  474. }
  475. };
  476. ;
  477. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  478. var preparedSourceCode = this._processPrecision(sourceCode);
  479. if (this._engine.webGLVersion == 1) {
  480. callback(preparedSourceCode);
  481. return;
  482. }
  483. // Already converted
  484. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  485. callback(preparedSourceCode.replace("#version 300 es", ""));
  486. return;
  487. }
  488. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  489. // Remove extensions
  490. // #extension GL_OES_standard_derivatives : enable
  491. // #extension GL_EXT_shader_texture_lod : enable
  492. // #extension GL_EXT_frag_depth : enable
  493. // #extension GL_EXT_draw_buffers : require
  494. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  495. var result = preparedSourceCode.replace(regex, "");
  496. // Migrate to GLSL v300
  497. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  498. result = result.replace(/attribute[ \t]/g, "in ");
  499. result = result.replace(/[ \t]attribute/g, " in");
  500. if (isFragment) {
  501. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  502. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  503. result = result.replace(/texture2D\s*\(/g, "texture(");
  504. result = result.replace(/textureCube\s*\(/g, "texture(");
  505. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  506. result = result.replace(/gl_FragColor/g, "glFragColor");
  507. result = result.replace(/gl_FragData/g, "glFragData");
  508. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  509. }
  510. callback(result);
  511. };
  512. Effect.prototype._processIncludes = function (sourceCode, callback) {
  513. var _this = this;
  514. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  515. var match = regex.exec(sourceCode);
  516. var returnValue = new String(sourceCode);
  517. while (match != null) {
  518. var includeFile = match[1];
  519. // Uniform declaration
  520. if (includeFile.indexOf("__decl__") !== -1) {
  521. includeFile = includeFile.replace(/__decl__/, "");
  522. if (this._engine.supportsUniformBuffers) {
  523. includeFile = includeFile.replace(/Vertex/, "Ubo");
  524. includeFile = includeFile.replace(/Fragment/, "Ubo");
  525. }
  526. includeFile = includeFile + "Declaration";
  527. }
  528. if (Effect.IncludesShadersStore[includeFile]) {
  529. // Substitution
  530. var includeContent = Effect.IncludesShadersStore[includeFile];
  531. if (match[2]) {
  532. var splits = match[3].split(",");
  533. for (var index = 0; index < splits.length; index += 2) {
  534. var source = new RegExp(splits[index], "g");
  535. var dest = splits[index + 1];
  536. includeContent = includeContent.replace(source, dest);
  537. }
  538. }
  539. if (match[4]) {
  540. var indexString = match[5];
  541. if (indexString.indexOf("..") !== -1) {
  542. var indexSplits = indexString.split("..");
  543. var minIndex = parseInt(indexSplits[0]);
  544. var maxIndex = parseInt(indexSplits[1]);
  545. var sourceIncludeContent = includeContent.slice(0);
  546. includeContent = "";
  547. if (isNaN(maxIndex)) {
  548. maxIndex = this._indexParameters[indexSplits[1]];
  549. }
  550. for (var i = minIndex; i < maxIndex; i++) {
  551. if (!this._engine.supportsUniformBuffers) {
  552. // Ubo replacement
  553. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  554. return p1 + "{X}";
  555. });
  556. }
  557. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  558. }
  559. }
  560. else {
  561. if (!this._engine.supportsUniformBuffers) {
  562. // Ubo replacement
  563. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  564. return p1 + "{X}";
  565. });
  566. }
  567. includeContent = includeContent.replace(/\{X\}/g, indexString);
  568. }
  569. }
  570. // Replace
  571. returnValue = returnValue.replace(match[0], includeContent);
  572. }
  573. else {
  574. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  575. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  576. Effect.IncludesShadersStore[includeFile] = fileContent;
  577. _this._processIncludes(returnValue, callback);
  578. });
  579. return;
  580. }
  581. match = regex.exec(sourceCode);
  582. }
  583. callback(returnValue);
  584. };
  585. Effect.prototype._processPrecision = function (source) {
  586. if (source.indexOf("precision highp float") === -1) {
  587. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  588. source = "precision mediump float;\n" + source;
  589. }
  590. else {
  591. source = "precision highp float;\n" + source;
  592. }
  593. }
  594. else {
  595. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  596. source = source.replace("precision highp float", "precision mediump float");
  597. }
  598. }
  599. return source;
  600. };
  601. /**
  602. * Recompiles the webGL program
  603. * @param vertexSourceCode The source code for the vertex shader.
  604. * @param fragmentSourceCode The source code for the fragment shader.
  605. * @param onCompiled Callback called when completed.
  606. * @param onError Callback called on error.
  607. * @hidden
  608. */
  609. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  610. var _this = this;
  611. this._isReady = false;
  612. this._vertexSourceCodeOverride = vertexSourceCode;
  613. this._fragmentSourceCodeOverride = fragmentSourceCode;
  614. this.onError = function (effect, error) {
  615. if (onError) {
  616. onError(error);
  617. }
  618. };
  619. this.onCompiled = function () {
  620. var scenes = _this.getEngine().scenes;
  621. for (var i = 0; i < scenes.length; i++) {
  622. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  623. }
  624. if (onCompiled) {
  625. onCompiled(_this._program);
  626. }
  627. };
  628. this._fallbacks = null;
  629. this._prepareEffect();
  630. };
  631. /**
  632. * Gets the uniform locations of the the specified variable names
  633. * @param names THe names of the variables to lookup.
  634. * @returns Array of locations in the same order as variable names.
  635. */
  636. Effect.prototype.getSpecificUniformLocations = function (names) {
  637. var engine = this._engine;
  638. return engine.getUniforms(this._program, names);
  639. };
  640. /**
  641. * Prepares the effect
  642. * @hidden
  643. */
  644. Effect.prototype._prepareEffect = function () {
  645. var attributesNames = this._attributesNames;
  646. var defines = this.defines;
  647. var fallbacks = this._fallbacks;
  648. this._valueCache = {};
  649. var previousProgram = this._program;
  650. try {
  651. var engine = this._engine;
  652. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  653. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  654. }
  655. else {
  656. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  657. }
  658. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  659. if (engine.supportsUniformBuffers) {
  660. for (var name in this._uniformBuffersNames) {
  661. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  662. }
  663. }
  664. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  665. this._attributes = engine.getAttributes(this._program, attributesNames);
  666. var index;
  667. for (index = 0; index < this._samplers.length; index++) {
  668. var sampler = this.getUniform(this._samplers[index]);
  669. if (sampler == null) {
  670. this._samplers.splice(index, 1);
  671. index--;
  672. }
  673. }
  674. engine.bindSamplers(this);
  675. this._compilationError = "";
  676. this._isReady = true;
  677. if (this.onCompiled) {
  678. this.onCompiled(this);
  679. }
  680. this.onCompileObservable.notifyObservers(this);
  681. this.onCompileObservable.clear();
  682. // Unbind mesh reference in fallbacks
  683. if (this._fallbacks) {
  684. this._fallbacks.unBindMesh();
  685. }
  686. if (previousProgram) {
  687. this.getEngine()._deleteProgram(previousProgram);
  688. }
  689. }
  690. catch (e) {
  691. this._compilationError = e.message;
  692. // Let's go through fallbacks then
  693. BABYLON.Tools.Error("Unable to compile effect:");
  694. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  695. return " " + uniform;
  696. }));
  697. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  698. return " " + attribute;
  699. }));
  700. BABYLON.Tools.Error("Error: " + this._compilationError);
  701. if (previousProgram) {
  702. this._program = previousProgram;
  703. this._isReady = true;
  704. if (this.onError) {
  705. this.onError(this, this._compilationError);
  706. }
  707. this.onErrorObservable.notifyObservers(this);
  708. }
  709. if (fallbacks && fallbacks.isMoreFallbacks) {
  710. BABYLON.Tools.Error("Trying next fallback.");
  711. this.defines = fallbacks.reduce(this.defines, this);
  712. this._prepareEffect();
  713. }
  714. else { // Sorry we did everything we can
  715. if (this.onError) {
  716. this.onError(this, this._compilationError);
  717. }
  718. this.onErrorObservable.notifyObservers(this);
  719. this.onErrorObservable.clear();
  720. // Unbind mesh reference in fallbacks
  721. if (this._fallbacks) {
  722. this._fallbacks.unBindMesh();
  723. }
  724. }
  725. }
  726. };
  727. Object.defineProperty(Effect.prototype, "isSupported", {
  728. /**
  729. * Checks if the effect is supported. (Must be called after compilation)
  730. */
  731. get: function () {
  732. return this._compilationError === "";
  733. },
  734. enumerable: true,
  735. configurable: true
  736. });
  737. /**
  738. * Binds a texture to the engine to be used as output of the shader.
  739. * @param channel Name of the output variable.
  740. * @param texture Texture to bind.
  741. * @hidden
  742. */
  743. Effect.prototype._bindTexture = function (channel, texture) {
  744. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  745. };
  746. /**
  747. * Sets a texture on the engine to be used in the shader.
  748. * @param channel Name of the sampler variable.
  749. * @param texture Texture to set.
  750. */
  751. Effect.prototype.setTexture = function (channel, texture) {
  752. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  753. };
  754. /**
  755. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  756. * @param channel Name of the sampler variable.
  757. * @param texture Texture to set.
  758. */
  759. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  760. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  761. };
  762. /**
  763. * Sets an array of textures on the engine to be used in the shader.
  764. * @param channel Name of the variable.
  765. * @param textures Textures to set.
  766. */
  767. Effect.prototype.setTextureArray = function (channel, textures) {
  768. if (this._samplers.indexOf(channel + "Ex") === -1) {
  769. var initialPos = this._samplers.indexOf(channel);
  770. for (var index = 1; index < textures.length; index++) {
  771. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  772. }
  773. }
  774. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  775. };
  776. /**
  777. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  778. * @param channel Name of the sampler variable.
  779. * @param postProcess Post process to get the input texture from.
  780. */
  781. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  782. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  783. };
  784. /**
  785. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  786. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  787. * @param channel Name of the sampler variable.
  788. * @param postProcess Post process to get the output texture from.
  789. */
  790. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  791. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  792. };
  793. /** @hidden */
  794. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  795. var cache = this._valueCache[uniformName];
  796. var flag = matrix.updateFlag;
  797. if (cache !== undefined && cache === flag) {
  798. return false;
  799. }
  800. this._valueCache[uniformName] = flag;
  801. return true;
  802. };
  803. /** @hidden */
  804. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  805. var cache = this._valueCache[uniformName];
  806. if (!cache) {
  807. cache = [x, y];
  808. this._valueCache[uniformName] = cache;
  809. return true;
  810. }
  811. var changed = false;
  812. if (cache[0] !== x) {
  813. cache[0] = x;
  814. changed = true;
  815. }
  816. if (cache[1] !== y) {
  817. cache[1] = y;
  818. changed = true;
  819. }
  820. return changed;
  821. };
  822. /** @hidden */
  823. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  824. var cache = this._valueCache[uniformName];
  825. if (!cache) {
  826. cache = [x, y, z];
  827. this._valueCache[uniformName] = cache;
  828. return true;
  829. }
  830. var changed = false;
  831. if (cache[0] !== x) {
  832. cache[0] = x;
  833. changed = true;
  834. }
  835. if (cache[1] !== y) {
  836. cache[1] = y;
  837. changed = true;
  838. }
  839. if (cache[2] !== z) {
  840. cache[2] = z;
  841. changed = true;
  842. }
  843. return changed;
  844. };
  845. /** @hidden */
  846. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  847. var cache = this._valueCache[uniformName];
  848. if (!cache) {
  849. cache = [x, y, z, w];
  850. this._valueCache[uniformName] = cache;
  851. return true;
  852. }
  853. var changed = false;
  854. if (cache[0] !== x) {
  855. cache[0] = x;
  856. changed = true;
  857. }
  858. if (cache[1] !== y) {
  859. cache[1] = y;
  860. changed = true;
  861. }
  862. if (cache[2] !== z) {
  863. cache[2] = z;
  864. changed = true;
  865. }
  866. if (cache[3] !== w) {
  867. cache[3] = w;
  868. changed = true;
  869. }
  870. return changed;
  871. };
  872. /**
  873. * Binds a buffer to a uniform.
  874. * @param buffer Buffer to bind.
  875. * @param name Name of the uniform variable to bind to.
  876. */
  877. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  878. var bufferName = this._uniformBuffersNames[name];
  879. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  880. return;
  881. }
  882. Effect._baseCache[bufferName] = buffer;
  883. this._engine.bindUniformBufferBase(buffer, bufferName);
  884. };
  885. /**
  886. * Binds block to a uniform.
  887. * @param blockName Name of the block to bind.
  888. * @param index Index to bind.
  889. */
  890. Effect.prototype.bindUniformBlock = function (blockName, index) {
  891. this._engine.bindUniformBlock(this._program, blockName, index);
  892. };
  893. /**
  894. * Sets an interger value on a uniform variable.
  895. * @param uniformName Name of the variable.
  896. * @param value Value to be set.
  897. * @returns this effect.
  898. */
  899. Effect.prototype.setInt = function (uniformName, value) {
  900. var cache = this._valueCache[uniformName];
  901. if (cache !== undefined && cache === value)
  902. return this;
  903. this._valueCache[uniformName] = value;
  904. this._engine.setInt(this.getUniform(uniformName), value);
  905. return this;
  906. };
  907. /**
  908. * Sets an int array on a uniform variable.
  909. * @param uniformName Name of the variable.
  910. * @param array array to be set.
  911. * @returns this effect.
  912. */
  913. Effect.prototype.setIntArray = function (uniformName, array) {
  914. this._valueCache[uniformName] = null;
  915. this._engine.setIntArray(this.getUniform(uniformName), array);
  916. return this;
  917. };
  918. /**
  919. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  920. * @param uniformName Name of the variable.
  921. * @param array array to be set.
  922. * @returns this effect.
  923. */
  924. Effect.prototype.setIntArray2 = function (uniformName, array) {
  925. this._valueCache[uniformName] = null;
  926. this._engine.setIntArray2(this.getUniform(uniformName), array);
  927. return this;
  928. };
  929. /**
  930. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  931. * @param uniformName Name of the variable.
  932. * @param array array to be set.
  933. * @returns this effect.
  934. */
  935. Effect.prototype.setIntArray3 = function (uniformName, array) {
  936. this._valueCache[uniformName] = null;
  937. this._engine.setIntArray3(this.getUniform(uniformName), array);
  938. return this;
  939. };
  940. /**
  941. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  942. * @param uniformName Name of the variable.
  943. * @param array array to be set.
  944. * @returns this effect.
  945. */
  946. Effect.prototype.setIntArray4 = function (uniformName, array) {
  947. this._valueCache[uniformName] = null;
  948. this._engine.setIntArray4(this.getUniform(uniformName), array);
  949. return this;
  950. };
  951. /**
  952. * Sets an float array on a uniform variable.
  953. * @param uniformName Name of the variable.
  954. * @param array array to be set.
  955. * @returns this effect.
  956. */
  957. Effect.prototype.setFloatArray = function (uniformName, array) {
  958. this._valueCache[uniformName] = null;
  959. this._engine.setFloatArray(this.getUniform(uniformName), array);
  960. return this;
  961. };
  962. /**
  963. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  964. * @param uniformName Name of the variable.
  965. * @param array array to be set.
  966. * @returns this effect.
  967. */
  968. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  969. this._valueCache[uniformName] = null;
  970. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  971. return this;
  972. };
  973. /**
  974. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  975. * @param uniformName Name of the variable.
  976. * @param array array to be set.
  977. * @returns this effect.
  978. */
  979. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  980. this._valueCache[uniformName] = null;
  981. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  982. return this;
  983. };
  984. /**
  985. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  986. * @param uniformName Name of the variable.
  987. * @param array array to be set.
  988. * @returns this effect.
  989. */
  990. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  991. this._valueCache[uniformName] = null;
  992. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  993. return this;
  994. };
  995. /**
  996. * Sets an array on a uniform variable.
  997. * @param uniformName Name of the variable.
  998. * @param array array to be set.
  999. * @returns this effect.
  1000. */
  1001. Effect.prototype.setArray = function (uniformName, array) {
  1002. this._valueCache[uniformName] = null;
  1003. this._engine.setArray(this.getUniform(uniformName), array);
  1004. return this;
  1005. };
  1006. /**
  1007. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1008. * @param uniformName Name of the variable.
  1009. * @param array array to be set.
  1010. * @returns this effect.
  1011. */
  1012. Effect.prototype.setArray2 = function (uniformName, array) {
  1013. this._valueCache[uniformName] = null;
  1014. this._engine.setArray2(this.getUniform(uniformName), array);
  1015. return this;
  1016. };
  1017. /**
  1018. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1019. * @param uniformName Name of the variable.
  1020. * @param array array to be set.
  1021. * @returns this effect.
  1022. */
  1023. Effect.prototype.setArray3 = function (uniformName, array) {
  1024. this._valueCache[uniformName] = null;
  1025. this._engine.setArray3(this.getUniform(uniformName), array);
  1026. return this;
  1027. };
  1028. /**
  1029. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1030. * @param uniformName Name of the variable.
  1031. * @param array array to be set.
  1032. * @returns this effect.
  1033. */
  1034. Effect.prototype.setArray4 = function (uniformName, array) {
  1035. this._valueCache[uniformName] = null;
  1036. this._engine.setArray4(this.getUniform(uniformName), array);
  1037. return this;
  1038. };
  1039. /**
  1040. * Sets matrices on a uniform variable.
  1041. * @param uniformName Name of the variable.
  1042. * @param matrices matrices to be set.
  1043. * @returns this effect.
  1044. */
  1045. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1046. if (!matrices) {
  1047. return this;
  1048. }
  1049. this._valueCache[uniformName] = null;
  1050. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1051. return this;
  1052. };
  1053. /**
  1054. * Sets matrix on a uniform variable.
  1055. * @param uniformName Name of the variable.
  1056. * @param matrix matrix to be set.
  1057. * @returns this effect.
  1058. */
  1059. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1060. if (this._cacheMatrix(uniformName, matrix)) {
  1061. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1062. }
  1063. return this;
  1064. };
  1065. /**
  1066. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1067. * @param uniformName Name of the variable.
  1068. * @param matrix matrix to be set.
  1069. * @returns this effect.
  1070. */
  1071. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1072. this._valueCache[uniformName] = null;
  1073. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1074. return this;
  1075. };
  1076. /**
  1077. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1078. * @param uniformName Name of the variable.
  1079. * @param matrix matrix to be set.
  1080. * @returns this effect.
  1081. */
  1082. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1083. this._valueCache[uniformName] = null;
  1084. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1085. return this;
  1086. };
  1087. /**
  1088. * Sets a float on a uniform variable.
  1089. * @param uniformName Name of the variable.
  1090. * @param value value to be set.
  1091. * @returns this effect.
  1092. */
  1093. Effect.prototype.setFloat = function (uniformName, value) {
  1094. var cache = this._valueCache[uniformName];
  1095. if (cache !== undefined && cache === value)
  1096. return this;
  1097. this._valueCache[uniformName] = value;
  1098. this._engine.setFloat(this.getUniform(uniformName), value);
  1099. return this;
  1100. };
  1101. /**
  1102. * Sets a boolean on a uniform variable.
  1103. * @param uniformName Name of the variable.
  1104. * @param bool value to be set.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setBool = function (uniformName, bool) {
  1108. var cache = this._valueCache[uniformName];
  1109. if (cache !== undefined && cache === bool)
  1110. return this;
  1111. this._valueCache[uniformName] = bool;
  1112. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1113. return this;
  1114. };
  1115. /**
  1116. * Sets a Vector2 on a uniform variable.
  1117. * @param uniformName Name of the variable.
  1118. * @param vector2 vector2 to be set.
  1119. * @returns this effect.
  1120. */
  1121. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1122. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1123. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1124. }
  1125. return this;
  1126. };
  1127. /**
  1128. * Sets a float2 on a uniform variable.
  1129. * @param uniformName Name of the variable.
  1130. * @param x First float in float2.
  1131. * @param y Second float in float2.
  1132. * @returns this effect.
  1133. */
  1134. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1135. if (this._cacheFloat2(uniformName, x, y)) {
  1136. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1137. }
  1138. return this;
  1139. };
  1140. /**
  1141. * Sets a Vector3 on a uniform variable.
  1142. * @param uniformName Name of the variable.
  1143. * @param vector3 Value to be set.
  1144. * @returns this effect.
  1145. */
  1146. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1147. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1148. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1149. }
  1150. return this;
  1151. };
  1152. /**
  1153. * Sets a float3 on a uniform variable.
  1154. * @param uniformName Name of the variable.
  1155. * @param x First float in float3.
  1156. * @param y Second float in float3.
  1157. * @param z Third float in float3.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1161. if (this._cacheFloat3(uniformName, x, y, z)) {
  1162. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Vector4 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param vector4 Value to be set.
  1170. * @returns this effect.
  1171. */
  1172. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1173. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1174. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1175. }
  1176. return this;
  1177. };
  1178. /**
  1179. * Sets a float4 on a uniform variable.
  1180. * @param uniformName Name of the variable.
  1181. * @param x First float in float4.
  1182. * @param y Second float in float4.
  1183. * @param z Third float in float4.
  1184. * @param w Fourth float in float4.
  1185. * @returns this effect.
  1186. */
  1187. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1188. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1189. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1190. }
  1191. return this;
  1192. };
  1193. /**
  1194. * Sets a Color3 on a uniform variable.
  1195. * @param uniformName Name of the variable.
  1196. * @param color3 Value to be set.
  1197. * @returns this effect.
  1198. */
  1199. Effect.prototype.setColor3 = function (uniformName, color3) {
  1200. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1201. this._engine.setColor3(this.getUniform(uniformName), color3);
  1202. }
  1203. return this;
  1204. };
  1205. /**
  1206. * Sets a Color4 on a uniform variable.
  1207. * @param uniformName Name of the variable.
  1208. * @param color3 Value to be set.
  1209. * @param alpha Alpha value to be set.
  1210. * @returns this effect.
  1211. */
  1212. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1213. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1214. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1215. }
  1216. return this;
  1217. };
  1218. /**
  1219. * Sets a Color4 on a uniform variable
  1220. * @param uniformName defines the name of the variable
  1221. * @param color4 defines the value to be set
  1222. * @returns this effect.
  1223. */
  1224. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1225. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1226. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1227. }
  1228. return this;
  1229. };
  1230. /**
  1231. * This function will add a new shader to the shader store
  1232. * @param name the name of the shader
  1233. * @param pixelShader optional pixel shader content
  1234. * @param vertexShader optional vertex shader content
  1235. */
  1236. Effect.RegisterShader = function (name, pixelShader, vertexShader) {
  1237. if (pixelShader) {
  1238. Effect.ShadersStore[name + "PixelShader"] = pixelShader;
  1239. }
  1240. if (vertexShader) {
  1241. Effect.ShadersStore[name + "VertexShader"] = vertexShader;
  1242. }
  1243. };
  1244. /**
  1245. * Resets the cache of effects.
  1246. */
  1247. Effect.ResetCache = function () {
  1248. Effect._baseCache = {};
  1249. };
  1250. Effect._uniqueIdSeed = 0;
  1251. Effect._baseCache = {};
  1252. /**
  1253. * Store of each shader (The can be looked up using effect.key)
  1254. */
  1255. Effect.ShadersStore = {};
  1256. /**
  1257. * Store of each included file for a shader (The can be looked up using effect.key)
  1258. */
  1259. Effect.IncludesShadersStore = {};
  1260. return Effect;
  1261. }());
  1262. BABYLON.Effect = Effect;
  1263. })(BABYLON || (BABYLON = {}));
  1264. //# sourceMappingURL=babylon.effect.js.map
  1265. //# sourceMappingURL=babylon.types.js.map
  1266. var BABYLON;
  1267. (function (BABYLON) {
  1268. var KeyboardEventTypes = /** @class */ (function () {
  1269. function KeyboardEventTypes() {
  1270. }
  1271. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1272. get: function () {
  1273. return KeyboardEventTypes._KEYDOWN;
  1274. },
  1275. enumerable: true,
  1276. configurable: true
  1277. });
  1278. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1279. get: function () {
  1280. return KeyboardEventTypes._KEYUP;
  1281. },
  1282. enumerable: true,
  1283. configurable: true
  1284. });
  1285. KeyboardEventTypes._KEYDOWN = 0x01;
  1286. KeyboardEventTypes._KEYUP = 0x02;
  1287. return KeyboardEventTypes;
  1288. }());
  1289. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1290. var KeyboardInfo = /** @class */ (function () {
  1291. function KeyboardInfo(type, event) {
  1292. this.type = type;
  1293. this.event = event;
  1294. }
  1295. return KeyboardInfo;
  1296. }());
  1297. BABYLON.KeyboardInfo = KeyboardInfo;
  1298. /**
  1299. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1300. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1301. */
  1302. var KeyboardInfoPre = /** @class */ (function (_super) {
  1303. __extends(KeyboardInfoPre, _super);
  1304. function KeyboardInfoPre(type, event) {
  1305. var _this = _super.call(this, type, event) || this;
  1306. _this.skipOnPointerObservable = false;
  1307. return _this;
  1308. }
  1309. return KeyboardInfoPre;
  1310. }(KeyboardInfo));
  1311. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1312. })(BABYLON || (BABYLON = {}));
  1313. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1314. var BABYLON;
  1315. (function (BABYLON) {
  1316. var PointerEventTypes = /** @class */ (function () {
  1317. function PointerEventTypes() {
  1318. }
  1319. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1320. get: function () {
  1321. return PointerEventTypes._POINTERDOWN;
  1322. },
  1323. enumerable: true,
  1324. configurable: true
  1325. });
  1326. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1327. get: function () {
  1328. return PointerEventTypes._POINTERUP;
  1329. },
  1330. enumerable: true,
  1331. configurable: true
  1332. });
  1333. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1334. get: function () {
  1335. return PointerEventTypes._POINTERMOVE;
  1336. },
  1337. enumerable: true,
  1338. configurable: true
  1339. });
  1340. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1341. get: function () {
  1342. return PointerEventTypes._POINTERWHEEL;
  1343. },
  1344. enumerable: true,
  1345. configurable: true
  1346. });
  1347. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1348. get: function () {
  1349. return PointerEventTypes._POINTERPICK;
  1350. },
  1351. enumerable: true,
  1352. configurable: true
  1353. });
  1354. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1355. get: function () {
  1356. return PointerEventTypes._POINTERTAP;
  1357. },
  1358. enumerable: true,
  1359. configurable: true
  1360. });
  1361. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1362. get: function () {
  1363. return PointerEventTypes._POINTERDOUBLETAP;
  1364. },
  1365. enumerable: true,
  1366. configurable: true
  1367. });
  1368. PointerEventTypes._POINTERDOWN = 0x01;
  1369. PointerEventTypes._POINTERUP = 0x02;
  1370. PointerEventTypes._POINTERMOVE = 0x04;
  1371. PointerEventTypes._POINTERWHEEL = 0x08;
  1372. PointerEventTypes._POINTERPICK = 0x10;
  1373. PointerEventTypes._POINTERTAP = 0x20;
  1374. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1375. return PointerEventTypes;
  1376. }());
  1377. BABYLON.PointerEventTypes = PointerEventTypes;
  1378. var PointerInfoBase = /** @class */ (function () {
  1379. function PointerInfoBase(type, event) {
  1380. this.type = type;
  1381. this.event = event;
  1382. }
  1383. return PointerInfoBase;
  1384. }());
  1385. BABYLON.PointerInfoBase = PointerInfoBase;
  1386. /**
  1387. * This class is used to store pointer related info for the onPrePointerObservable event.
  1388. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1389. */
  1390. var PointerInfoPre = /** @class */ (function (_super) {
  1391. __extends(PointerInfoPre, _super);
  1392. function PointerInfoPre(type, event, localX, localY) {
  1393. var _this = _super.call(this, type, event) || this;
  1394. /**
  1395. * Ray from a pointer if availible (eg. 6dof controller)
  1396. */
  1397. _this.ray = null;
  1398. _this.skipOnPointerObservable = false;
  1399. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1400. return _this;
  1401. }
  1402. return PointerInfoPre;
  1403. }(PointerInfoBase));
  1404. BABYLON.PointerInfoPre = PointerInfoPre;
  1405. /**
  1406. * This type contains all the data related to a pointer event in Babylon.js.
  1407. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1408. */
  1409. var PointerInfo = /** @class */ (function (_super) {
  1410. __extends(PointerInfo, _super);
  1411. function PointerInfo(type, event, pickInfo) {
  1412. var _this = _super.call(this, type, event) || this;
  1413. _this.pickInfo = pickInfo;
  1414. return _this;
  1415. }
  1416. return PointerInfo;
  1417. }(PointerInfoBase));
  1418. BABYLON.PointerInfo = PointerInfo;
  1419. })(BABYLON || (BABYLON = {}));
  1420. //# sourceMappingURL=babylon.pointerEvents.js.map
  1421. var BABYLON;
  1422. (function (BABYLON) {
  1423. BABYLON.ToGammaSpace = 1 / 2.2;
  1424. BABYLON.ToLinearSpace = 2.2;
  1425. BABYLON.Epsilon = 0.001;
  1426. /**
  1427. * Class used to hold a RBG color
  1428. */
  1429. var Color3 = /** @class */ (function () {
  1430. /**
  1431. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1432. * @param r defines the red component (between 0 and 1, default is 0)
  1433. * @param g defines the green component (between 0 and 1, default is 0)
  1434. * @param b defines the blue component (between 0 and 1, default is 0)
  1435. */
  1436. function Color3(
  1437. /**
  1438. * Defines the red component (between 0 and 1, default is 0)
  1439. */
  1440. r,
  1441. /**
  1442. * Defines the green component (between 0 and 1, default is 0)
  1443. */
  1444. g,
  1445. /**
  1446. * Defines the blue component (between 0 and 1, default is 0)
  1447. */
  1448. b) {
  1449. if (r === void 0) { r = 0; }
  1450. if (g === void 0) { g = 0; }
  1451. if (b === void 0) { b = 0; }
  1452. this.r = r;
  1453. this.g = g;
  1454. this.b = b;
  1455. }
  1456. /**
  1457. * Creates a string with the Color3 current values
  1458. * @returns the string representation of the Color3 object
  1459. */
  1460. Color3.prototype.toString = function () {
  1461. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1462. };
  1463. /**
  1464. * Returns the string "Color3"
  1465. * @returns "Color3"
  1466. */
  1467. Color3.prototype.getClassName = function () {
  1468. return "Color3";
  1469. };
  1470. /**
  1471. * Compute the Color3 hash code
  1472. * @returns an unique number that can be used to hash Color3 objects
  1473. */
  1474. Color3.prototype.getHashCode = function () {
  1475. var hash = this.r || 0;
  1476. hash = (hash * 397) ^ (this.g || 0);
  1477. hash = (hash * 397) ^ (this.b || 0);
  1478. return hash;
  1479. };
  1480. // Operators
  1481. /**
  1482. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1483. * @param array defines the array where to store the r,g,b components
  1484. * @param index defines an optional index in the target array to define where to start storing values
  1485. * @returns the current Color3 object
  1486. */
  1487. Color3.prototype.toArray = function (array, index) {
  1488. if (index === undefined) {
  1489. index = 0;
  1490. }
  1491. array[index] = this.r;
  1492. array[index + 1] = this.g;
  1493. array[index + 2] = this.b;
  1494. return this;
  1495. };
  1496. /**
  1497. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1498. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1499. * @returns a new {BABYLON.Color4} object
  1500. */
  1501. Color3.prototype.toColor4 = function (alpha) {
  1502. if (alpha === void 0) { alpha = 1; }
  1503. return new Color4(this.r, this.g, this.b, alpha);
  1504. };
  1505. /**
  1506. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1507. * @returns the new array
  1508. */
  1509. Color3.prototype.asArray = function () {
  1510. var result = new Array();
  1511. this.toArray(result, 0);
  1512. return result;
  1513. };
  1514. /**
  1515. * Returns the luminance value
  1516. * @returns a float value
  1517. */
  1518. Color3.prototype.toLuminance = function () {
  1519. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1520. };
  1521. /**
  1522. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1523. * @param otherColor defines the second operand
  1524. * @returns the new Color3 object
  1525. */
  1526. Color3.prototype.multiply = function (otherColor) {
  1527. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1528. };
  1529. /**
  1530. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1531. * @param otherColor defines the second operand
  1532. * @param result defines the Color3 object where to store the result
  1533. * @returns the current Color3
  1534. */
  1535. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1536. result.r = this.r * otherColor.r;
  1537. result.g = this.g * otherColor.g;
  1538. result.b = this.b * otherColor.b;
  1539. return this;
  1540. };
  1541. /**
  1542. * Determines equality between Color3 objects
  1543. * @param otherColor defines the second operand
  1544. * @returns true if the rgb values are equal to the given ones
  1545. */
  1546. Color3.prototype.equals = function (otherColor) {
  1547. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1548. };
  1549. /**
  1550. * Determines equality between the current Color3 object and a set of r,b,g values
  1551. * @param r defines the red component to check
  1552. * @param g defines the green component to check
  1553. * @param b defines the blue component to check
  1554. * @returns true if the rgb values are equal to the given ones
  1555. */
  1556. Color3.prototype.equalsFloats = function (r, g, b) {
  1557. return this.r === r && this.g === g && this.b === b;
  1558. };
  1559. /**
  1560. * Multiplies in place each rgb value by scale
  1561. * @param scale defines the scaling factor
  1562. * @returns the updated Color3
  1563. */
  1564. Color3.prototype.scale = function (scale) {
  1565. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1566. };
  1567. /**
  1568. * Multiplies the rgb values by scale and stores the result into "result"
  1569. * @param scale defines the scaling factor
  1570. * @param result defines the Color3 object where to store the result
  1571. * @returns the unmodified current Color3
  1572. */
  1573. Color3.prototype.scaleToRef = function (scale, result) {
  1574. result.r = this.r * scale;
  1575. result.g = this.g * scale;
  1576. result.b = this.b * scale;
  1577. return this;
  1578. };
  1579. /**
  1580. * Scale the current Color3 values by a factor and add the result to a given Color3
  1581. * @param scale defines the scale factor
  1582. * @param result defines color to store the result into
  1583. * @returns the unmodified current Color3
  1584. */
  1585. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1586. result.r += this.r * scale;
  1587. result.g += this.g * scale;
  1588. result.b += this.b * scale;
  1589. return this;
  1590. };
  1591. /**
  1592. * Clamps the rgb values by the min and max values and stores the result into "result"
  1593. * @param min defines minimum clamping value (default is 0)
  1594. * @param max defines maximum clamping value (default is 1)
  1595. * @param result defines color to store the result into
  1596. * @returns the original Color3
  1597. */
  1598. Color3.prototype.clampToRef = function (min, max, result) {
  1599. if (min === void 0) { min = 0; }
  1600. if (max === void 0) { max = 1; }
  1601. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1602. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1603. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1604. return this;
  1605. };
  1606. /**
  1607. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1608. * @param otherColor defines the second operand
  1609. * @returns the new Color3
  1610. */
  1611. Color3.prototype.add = function (otherColor) {
  1612. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1613. };
  1614. /**
  1615. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1616. * @param otherColor defines the second operand
  1617. * @param result defines Color3 object to store the result into
  1618. * @returns the unmodified current Color3
  1619. */
  1620. Color3.prototype.addToRef = function (otherColor, result) {
  1621. result.r = this.r + otherColor.r;
  1622. result.g = this.g + otherColor.g;
  1623. result.b = this.b + otherColor.b;
  1624. return this;
  1625. };
  1626. /**
  1627. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1628. * @param otherColor defines the second operand
  1629. * @returns the new Color3
  1630. */
  1631. Color3.prototype.subtract = function (otherColor) {
  1632. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1633. };
  1634. /**
  1635. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1636. * @param otherColor defines the second operand
  1637. * @param result defines Color3 object to store the result into
  1638. * @returns the unmodified current Color3
  1639. */
  1640. Color3.prototype.subtractToRef = function (otherColor, result) {
  1641. result.r = this.r - otherColor.r;
  1642. result.g = this.g - otherColor.g;
  1643. result.b = this.b - otherColor.b;
  1644. return this;
  1645. };
  1646. /**
  1647. * Copy the current object
  1648. * @returns a new Color3 copied the current one
  1649. */
  1650. Color3.prototype.clone = function () {
  1651. return new Color3(this.r, this.g, this.b);
  1652. };
  1653. /**
  1654. * Copies the rgb values from the source in the current Color3
  1655. * @param source defines the source Color3 object
  1656. * @returns the updated Color3 object
  1657. */
  1658. Color3.prototype.copyFrom = function (source) {
  1659. this.r = source.r;
  1660. this.g = source.g;
  1661. this.b = source.b;
  1662. return this;
  1663. };
  1664. /**
  1665. * Updates the Color3 rgb values from the given floats
  1666. * @param r defines the red component to read from
  1667. * @param g defines the green component to read from
  1668. * @param b defines the blue component to read from
  1669. * @returns the current Color3 object
  1670. */
  1671. Color3.prototype.copyFromFloats = function (r, g, b) {
  1672. this.r = r;
  1673. this.g = g;
  1674. this.b = b;
  1675. return this;
  1676. };
  1677. /**
  1678. * Updates the Color3 rgb values from the given floats
  1679. * @param r defines the red component to read from
  1680. * @param g defines the green component to read from
  1681. * @param b defines the blue component to read from
  1682. * @returns the current Color3 object
  1683. */
  1684. Color3.prototype.set = function (r, g, b) {
  1685. return this.copyFromFloats(r, g, b);
  1686. };
  1687. /**
  1688. * Compute the Color3 hexadecimal code as a string
  1689. * @returns a string containing the hexadecimal representation of the Color3 object
  1690. */
  1691. Color3.prototype.toHexString = function () {
  1692. var intR = (this.r * 255) | 0;
  1693. var intG = (this.g * 255) | 0;
  1694. var intB = (this.b * 255) | 0;
  1695. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1696. };
  1697. /**
  1698. * Computes a new Color3 converted from the current one to linear space
  1699. * @returns a new Color3 object
  1700. */
  1701. Color3.prototype.toLinearSpace = function () {
  1702. var convertedColor = new Color3();
  1703. this.toLinearSpaceToRef(convertedColor);
  1704. return convertedColor;
  1705. };
  1706. /**
  1707. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1708. * @param convertedColor defines the Color3 object where to store the linear space version
  1709. * @returns the unmodified Color3
  1710. */
  1711. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1712. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1713. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1714. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1715. return this;
  1716. };
  1717. /**
  1718. * Computes a new Color3 converted from the current one to gamma space
  1719. * @returns a new Color3 object
  1720. */
  1721. Color3.prototype.toGammaSpace = function () {
  1722. var convertedColor = new Color3();
  1723. this.toGammaSpaceToRef(convertedColor);
  1724. return convertedColor;
  1725. };
  1726. /**
  1727. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1728. * @param convertedColor defines the Color3 object where to store the gamma space version
  1729. * @returns the unmodified Color3
  1730. */
  1731. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1732. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1733. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1734. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1735. return this;
  1736. };
  1737. // Statics
  1738. /**
  1739. * Creates a new Color3 from the string containing valid hexadecimal values
  1740. * @param hex defines a string containing valid hexadecimal values
  1741. * @returns a new Color3 object
  1742. */
  1743. Color3.FromHexString = function (hex) {
  1744. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1745. return new Color3(0, 0, 0);
  1746. }
  1747. var r = parseInt(hex.substring(1, 3), 16);
  1748. var g = parseInt(hex.substring(3, 5), 16);
  1749. var b = parseInt(hex.substring(5, 7), 16);
  1750. return Color3.FromInts(r, g, b);
  1751. };
  1752. /**
  1753. * Creates a new Vector3 from the starting index of the given array
  1754. * @param array defines the source array
  1755. * @param offset defines an offset in the source array
  1756. * @returns a new Color3 object
  1757. */
  1758. Color3.FromArray = function (array, offset) {
  1759. if (offset === void 0) { offset = 0; }
  1760. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1761. };
  1762. /**
  1763. * Creates a new Color3 from integer values (< 256)
  1764. * @param r defines the red component to read from (value between 0 and 255)
  1765. * @param g defines the green component to read from (value between 0 and 255)
  1766. * @param b defines the blue component to read from (value between 0 and 255)
  1767. * @returns a new Color3 object
  1768. */
  1769. Color3.FromInts = function (r, g, b) {
  1770. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1771. };
  1772. /**
  1773. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1774. * @param start defines the start Color3 value
  1775. * @param end defines the end Color3 value
  1776. * @param amount defines the gradient value between start and end
  1777. * @returns a new Color3 object
  1778. */
  1779. Color3.Lerp = function (start, end, amount) {
  1780. var r = start.r + ((end.r - start.r) * amount);
  1781. var g = start.g + ((end.g - start.g) * amount);
  1782. var b = start.b + ((end.b - start.b) * amount);
  1783. return new Color3(r, g, b);
  1784. };
  1785. /**
  1786. * Returns a Color3 value containing a red color
  1787. * @returns a new Color3 object
  1788. */
  1789. Color3.Red = function () { return new Color3(1, 0, 0); };
  1790. /**
  1791. * Returns a Color3 value containing a green color
  1792. * @returns a new Color3 object
  1793. */
  1794. Color3.Green = function () { return new Color3(0, 1, 0); };
  1795. /**
  1796. * Returns a Color3 value containing a blue color
  1797. * @returns a new Color3 object
  1798. */
  1799. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1800. /**
  1801. * Returns a Color3 value containing a black color
  1802. * @returns a new Color3 object
  1803. */
  1804. Color3.Black = function () { return new Color3(0, 0, 0); };
  1805. /**
  1806. * Returns a Color3 value containing a white color
  1807. * @returns a new Color3 object
  1808. */
  1809. Color3.White = function () { return new Color3(1, 1, 1); };
  1810. /**
  1811. * Returns a Color3 value containing a purple color
  1812. * @returns a new Color3 object
  1813. */
  1814. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1815. /**
  1816. * Returns a Color3 value containing a magenta color
  1817. * @returns a new Color3 object
  1818. */
  1819. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1820. /**
  1821. * Returns a Color3 value containing a yellow color
  1822. * @returns a new Color3 object
  1823. */
  1824. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1825. /**
  1826. * Returns a Color3 value containing a gray color
  1827. * @returns a new Color3 object
  1828. */
  1829. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1830. /**
  1831. * Returns a Color3 value containing a teal color
  1832. * @returns a new Color3 object
  1833. */
  1834. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1835. /**
  1836. * Returns a Color3 value containing a random color
  1837. * @returns a new Color3 object
  1838. */
  1839. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1840. return Color3;
  1841. }());
  1842. BABYLON.Color3 = Color3;
  1843. /**
  1844. * Class used to hold a RBGA color
  1845. */
  1846. var Color4 = /** @class */ (function () {
  1847. /**
  1848. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1849. * @param r defines the red component (between 0 and 1, default is 0)
  1850. * @param g defines the green component (between 0 and 1, default is 0)
  1851. * @param b defines the blue component (between 0 and 1, default is 0)
  1852. * @param a defines the alpha component (between 0 and 1, default is 1)
  1853. */
  1854. function Color4(
  1855. /**
  1856. * Defines the red component (between 0 and 1, default is 0)
  1857. */
  1858. r,
  1859. /**
  1860. * Defines the green component (between 0 and 1, default is 0)
  1861. */
  1862. g,
  1863. /**
  1864. * Defines the blue component (between 0 and 1, default is 0)
  1865. */
  1866. b,
  1867. /**
  1868. * Defines the alpha component (between 0 and 1, default is 1)
  1869. */
  1870. a) {
  1871. if (r === void 0) { r = 0; }
  1872. if (g === void 0) { g = 0; }
  1873. if (b === void 0) { b = 0; }
  1874. if (a === void 0) { a = 1; }
  1875. this.r = r;
  1876. this.g = g;
  1877. this.b = b;
  1878. this.a = a;
  1879. }
  1880. // Operators
  1881. /**
  1882. * Adds in place the given Color4 values to the current Color4 object
  1883. * @param right defines the second operand
  1884. * @returns the current updated Color4 object
  1885. */
  1886. Color4.prototype.addInPlace = function (right) {
  1887. this.r += right.r;
  1888. this.g += right.g;
  1889. this.b += right.b;
  1890. this.a += right.a;
  1891. return this;
  1892. };
  1893. /**
  1894. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1895. * @returns the new array
  1896. */
  1897. Color4.prototype.asArray = function () {
  1898. var result = new Array();
  1899. this.toArray(result, 0);
  1900. return result;
  1901. };
  1902. /**
  1903. * Stores from the starting index in the given array the Color4 successive values
  1904. * @param array defines the array where to store the r,g,b components
  1905. * @param index defines an optional index in the target array to define where to start storing values
  1906. * @returns the current Color4 object
  1907. */
  1908. Color4.prototype.toArray = function (array, index) {
  1909. if (index === undefined) {
  1910. index = 0;
  1911. }
  1912. array[index] = this.r;
  1913. array[index + 1] = this.g;
  1914. array[index + 2] = this.b;
  1915. array[index + 3] = this.a;
  1916. return this;
  1917. };
  1918. /**
  1919. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1920. * @param right defines the second operand
  1921. * @returns a new Color4 object
  1922. */
  1923. Color4.prototype.add = function (right) {
  1924. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1925. };
  1926. /**
  1927. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1928. * @param right defines the second operand
  1929. * @returns a new Color4 object
  1930. */
  1931. Color4.prototype.subtract = function (right) {
  1932. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1933. };
  1934. /**
  1935. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1936. * @param right defines the second operand
  1937. * @param result defines the Color4 object where to store the result
  1938. * @returns the current Color4 object
  1939. */
  1940. Color4.prototype.subtractToRef = function (right, result) {
  1941. result.r = this.r - right.r;
  1942. result.g = this.g - right.g;
  1943. result.b = this.b - right.b;
  1944. result.a = this.a - right.a;
  1945. return this;
  1946. };
  1947. /**
  1948. * Creates a new Color4 with the current Color4 values multiplied by scale
  1949. * @param scale defines the scaling factor to apply
  1950. * @returns a new Color4 object
  1951. */
  1952. Color4.prototype.scale = function (scale) {
  1953. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1954. };
  1955. /**
  1956. * Multiplies the current Color4 values by scale and stores the result in "result"
  1957. * @param scale defines the scaling factor to apply
  1958. * @param result defines the Color4 object where to store the result
  1959. * @returns the current unmodified Color4
  1960. */
  1961. Color4.prototype.scaleToRef = function (scale, result) {
  1962. result.r = this.r * scale;
  1963. result.g = this.g * scale;
  1964. result.b = this.b * scale;
  1965. result.a = this.a * scale;
  1966. return this;
  1967. };
  1968. /**
  1969. * Scale the current Color4 values by a factor and add the result to a given Color4
  1970. * @param scale defines the scale factor
  1971. * @param result defines the Color4 object where to store the result
  1972. * @returns the unmodified current Color4
  1973. */
  1974. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1975. result.r += this.r * scale;
  1976. result.g += this.g * scale;
  1977. result.b += this.b * scale;
  1978. result.a += this.a * scale;
  1979. return this;
  1980. };
  1981. /**
  1982. * Clamps the rgb values by the min and max values and stores the result into "result"
  1983. * @param min defines minimum clamping value (default is 0)
  1984. * @param max defines maximum clamping value (default is 1)
  1985. * @param result defines color to store the result into.
  1986. * @returns the cuurent Color4
  1987. */
  1988. Color4.prototype.clampToRef = function (min, max, result) {
  1989. if (min === void 0) { min = 0; }
  1990. if (max === void 0) { max = 1; }
  1991. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1992. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1993. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1994. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1995. return this;
  1996. };
  1997. /**
  1998. * Multipy an Color4 value by another and return a new Color4 object
  1999. * @param color defines the Color4 value to multiply by
  2000. * @returns a new Color4 object
  2001. */
  2002. Color4.prototype.multiply = function (color) {
  2003. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2004. };
  2005. /**
  2006. * Multipy a Color4 value by another and push the result in a reference value
  2007. * @param color defines the Color4 value to multiply by
  2008. * @param result defines the Color4 to fill the result in
  2009. * @returns the result Color4
  2010. */
  2011. Color4.prototype.multiplyToRef = function (color, result) {
  2012. result.r = this.r * color.r;
  2013. result.g = this.g * color.g;
  2014. result.b = this.b * color.b;
  2015. result.a = this.a * color.a;
  2016. return result;
  2017. };
  2018. /**
  2019. * Creates a string with the Color4 current values
  2020. * @returns the string representation of the Color4 object
  2021. */
  2022. Color4.prototype.toString = function () {
  2023. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2024. };
  2025. /**
  2026. * Returns the string "Color4"
  2027. * @returns "Color4"
  2028. */
  2029. Color4.prototype.getClassName = function () {
  2030. return "Color4";
  2031. };
  2032. /**
  2033. * Compute the Color4 hash code
  2034. * @returns an unique number that can be used to hash Color4 objects
  2035. */
  2036. Color4.prototype.getHashCode = function () {
  2037. var hash = this.r || 0;
  2038. hash = (hash * 397) ^ (this.g || 0);
  2039. hash = (hash * 397) ^ (this.b || 0);
  2040. hash = (hash * 397) ^ (this.a || 0);
  2041. return hash;
  2042. };
  2043. /**
  2044. * Creates a new Color4 copied from the current one
  2045. * @returns a new Color4 object
  2046. */
  2047. Color4.prototype.clone = function () {
  2048. return new Color4(this.r, this.g, this.b, this.a);
  2049. };
  2050. /**
  2051. * Copies the given Color4 values into the current one
  2052. * @param source defines the source Color4 object
  2053. * @returns the current updated Color4 object
  2054. */
  2055. Color4.prototype.copyFrom = function (source) {
  2056. this.r = source.r;
  2057. this.g = source.g;
  2058. this.b = source.b;
  2059. this.a = source.a;
  2060. return this;
  2061. };
  2062. /**
  2063. * Copies the given float values into the current one
  2064. * @param r defines the red component to read from
  2065. * @param g defines the green component to read from
  2066. * @param b defines the blue component to read from
  2067. * @param a defines the alpha component to read from
  2068. * @returns the current updated Color4 object
  2069. */
  2070. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2071. this.r = r;
  2072. this.g = g;
  2073. this.b = b;
  2074. this.a = a;
  2075. return this;
  2076. };
  2077. /**
  2078. * Copies the given float values into the current one
  2079. * @param r defines the red component to read from
  2080. * @param g defines the green component to read from
  2081. * @param b defines the blue component to read from
  2082. * @param a defines the alpha component to read from
  2083. * @returns the current updated Color4 object
  2084. */
  2085. Color4.prototype.set = function (r, g, b, a) {
  2086. return this.copyFromFloats(r, g, b, a);
  2087. };
  2088. /**
  2089. * Compute the Color4 hexadecimal code as a string
  2090. * @returns a string containing the hexadecimal representation of the Color4 object
  2091. */
  2092. Color4.prototype.toHexString = function () {
  2093. var intR = (this.r * 255) | 0;
  2094. var intG = (this.g * 255) | 0;
  2095. var intB = (this.b * 255) | 0;
  2096. var intA = (this.a * 255) | 0;
  2097. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2098. };
  2099. /**
  2100. * Computes a new Color4 converted from the current one to linear space
  2101. * @returns a new Color4 object
  2102. */
  2103. Color4.prototype.toLinearSpace = function () {
  2104. var convertedColor = new Color4();
  2105. this.toLinearSpaceToRef(convertedColor);
  2106. return convertedColor;
  2107. };
  2108. /**
  2109. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2110. * @param convertedColor defines the Color4 object where to store the linear space version
  2111. * @returns the unmodified Color4
  2112. */
  2113. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2114. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2115. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2116. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2117. convertedColor.a = this.a;
  2118. return this;
  2119. };
  2120. /**
  2121. * Computes a new Color4 converted from the current one to gamma space
  2122. * @returns a new Color4 object
  2123. */
  2124. Color4.prototype.toGammaSpace = function () {
  2125. var convertedColor = new Color4();
  2126. this.toGammaSpaceToRef(convertedColor);
  2127. return convertedColor;
  2128. };
  2129. /**
  2130. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2131. * @param convertedColor defines the Color4 object where to store the gamma space version
  2132. * @returns the unmodified Color4
  2133. */
  2134. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2135. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2136. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2137. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2138. convertedColor.a = this.a;
  2139. return this;
  2140. };
  2141. // Statics
  2142. /**
  2143. * Creates a new Color4 from the string containing valid hexadecimal values
  2144. * @param hex defines a string containing valid hexadecimal values
  2145. * @returns a new Color4 object
  2146. */
  2147. Color4.FromHexString = function (hex) {
  2148. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2149. return new Color4(0.0, 0.0, 0.0, 0.0);
  2150. }
  2151. var r = parseInt(hex.substring(1, 3), 16);
  2152. var g = parseInt(hex.substring(3, 5), 16);
  2153. var b = parseInt(hex.substring(5, 7), 16);
  2154. var a = parseInt(hex.substring(7, 9), 16);
  2155. return Color4.FromInts(r, g, b, a);
  2156. };
  2157. /**
  2158. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2159. * @param left defines the start value
  2160. * @param right defines the end value
  2161. * @param amount defines the gradient factor
  2162. * @returns a new Color4 object
  2163. */
  2164. Color4.Lerp = function (left, right, amount) {
  2165. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2166. Color4.LerpToRef(left, right, amount, result);
  2167. return result;
  2168. };
  2169. /**
  2170. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2171. * @param left defines the start value
  2172. * @param right defines the end value
  2173. * @param amount defines the gradient factor
  2174. * @param result defines the Color4 object where to store data
  2175. */
  2176. Color4.LerpToRef = function (left, right, amount, result) {
  2177. result.r = left.r + (right.r - left.r) * amount;
  2178. result.g = left.g + (right.g - left.g) * amount;
  2179. result.b = left.b + (right.b - left.b) * amount;
  2180. result.a = left.a + (right.a - left.a) * amount;
  2181. };
  2182. /**
  2183. * Creates a new Color4 from the starting index element of the given array
  2184. * @param array defines the source array to read from
  2185. * @param offset defines the offset in the source array
  2186. * @returns a new Color4 object
  2187. */
  2188. Color4.FromArray = function (array, offset) {
  2189. if (offset === void 0) { offset = 0; }
  2190. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2191. };
  2192. /**
  2193. * Creates a new Color3 from integer values (< 256)
  2194. * @param r defines the red component to read from (value between 0 and 255)
  2195. * @param g defines the green component to read from (value between 0 and 255)
  2196. * @param b defines the blue component to read from (value between 0 and 255)
  2197. * @param a defines the alpha component to read from (value between 0 and 255)
  2198. * @returns a new Color3 object
  2199. */
  2200. Color4.FromInts = function (r, g, b, a) {
  2201. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2202. };
  2203. /**
  2204. * Check the content of a given array and convert it to an array containing RGBA data
  2205. * If the original array was already containing count * 4 values then it is returned directly
  2206. * @param colors defines the array to check
  2207. * @param count defines the number of RGBA data to expect
  2208. * @returns an array containing count * 4 values (RGBA)
  2209. */
  2210. Color4.CheckColors4 = function (colors, count) {
  2211. // Check if color3 was used
  2212. if (colors.length === count * 3) {
  2213. var colors4 = [];
  2214. for (var index = 0; index < colors.length; index += 3) {
  2215. var newIndex = (index / 3) * 4;
  2216. colors4[newIndex] = colors[index];
  2217. colors4[newIndex + 1] = colors[index + 1];
  2218. colors4[newIndex + 2] = colors[index + 2];
  2219. colors4[newIndex + 3] = 1.0;
  2220. }
  2221. return colors4;
  2222. }
  2223. return colors;
  2224. };
  2225. return Color4;
  2226. }());
  2227. BABYLON.Color4 = Color4;
  2228. /**
  2229. * Class representing a vector containing 2 coordinates
  2230. */
  2231. var Vector2 = /** @class */ (function () {
  2232. /**
  2233. * Creates a new Vector2 from the given x and y coordinates
  2234. * @param x defines the first coordinate
  2235. * @param y defines the second coordinate
  2236. */
  2237. function Vector2(
  2238. /** defines the first coordinate */
  2239. x,
  2240. /** defines the second coordinate */
  2241. y) {
  2242. if (x === void 0) { x = 0; }
  2243. if (y === void 0) { y = 0; }
  2244. this.x = x;
  2245. this.y = y;
  2246. }
  2247. /**
  2248. * Gets a string with the Vector2 coordinates
  2249. * @returns a string with the Vector2 coordinates
  2250. */
  2251. Vector2.prototype.toString = function () {
  2252. return "{X: " + this.x + " Y:" + this.y + "}";
  2253. };
  2254. /**
  2255. * Gets class name
  2256. * @returns the string "Vector2"
  2257. */
  2258. Vector2.prototype.getClassName = function () {
  2259. return "Vector2";
  2260. };
  2261. /**
  2262. * Gets current vector hash code
  2263. * @returns the Vector2 hash code as a number
  2264. */
  2265. Vector2.prototype.getHashCode = function () {
  2266. var hash = this.x || 0;
  2267. hash = (hash * 397) ^ (this.y || 0);
  2268. return hash;
  2269. };
  2270. // Operators
  2271. /**
  2272. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2273. * @param array defines the source array
  2274. * @param index defines the offset in source array
  2275. * @returns the current Vector2
  2276. */
  2277. Vector2.prototype.toArray = function (array, index) {
  2278. if (index === void 0) { index = 0; }
  2279. array[index] = this.x;
  2280. array[index + 1] = this.y;
  2281. return this;
  2282. };
  2283. /**
  2284. * Copy the current vector to an array
  2285. * @returns a new array with 2 elements: the Vector2 coordinates.
  2286. */
  2287. Vector2.prototype.asArray = function () {
  2288. var result = new Array();
  2289. this.toArray(result, 0);
  2290. return result;
  2291. };
  2292. /**
  2293. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2294. * @param source defines the source Vector2
  2295. * @returns the current updated Vector2
  2296. */
  2297. Vector2.prototype.copyFrom = function (source) {
  2298. this.x = source.x;
  2299. this.y = source.y;
  2300. return this;
  2301. };
  2302. /**
  2303. * Sets the Vector2 coordinates with the given floats
  2304. * @param x defines the first coordinate
  2305. * @param y defines the second coordinate
  2306. * @returns the current updated Vector2
  2307. */
  2308. Vector2.prototype.copyFromFloats = function (x, y) {
  2309. this.x = x;
  2310. this.y = y;
  2311. return this;
  2312. };
  2313. /**
  2314. * Sets the Vector2 coordinates with the given floats
  2315. * @param x defines the first coordinate
  2316. * @param y defines the second coordinate
  2317. * @returns the current updated Vector2
  2318. */
  2319. Vector2.prototype.set = function (x, y) {
  2320. return this.copyFromFloats(x, y);
  2321. };
  2322. /**
  2323. * Add another vector with the current one
  2324. * @param otherVector defines the other vector
  2325. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2326. */
  2327. Vector2.prototype.add = function (otherVector) {
  2328. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2329. };
  2330. /**
  2331. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2332. * @param otherVector defines the other vector
  2333. * @param result defines the target vector
  2334. * @returns the unmodified current Vector2
  2335. */
  2336. Vector2.prototype.addToRef = function (otherVector, result) {
  2337. result.x = this.x + otherVector.x;
  2338. result.y = this.y + otherVector.y;
  2339. return this;
  2340. };
  2341. /**
  2342. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2343. * @param otherVector defines the other vector
  2344. * @returns the current updated Vector2
  2345. */
  2346. Vector2.prototype.addInPlace = function (otherVector) {
  2347. this.x += otherVector.x;
  2348. this.y += otherVector.y;
  2349. return this;
  2350. };
  2351. /**
  2352. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2353. * @param otherVector defines the other vector
  2354. * @returns a new Vector2
  2355. */
  2356. Vector2.prototype.addVector3 = function (otherVector) {
  2357. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2358. };
  2359. /**
  2360. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2361. * @param otherVector defines the other vector
  2362. * @returns a new Vector2
  2363. */
  2364. Vector2.prototype.subtract = function (otherVector) {
  2365. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2366. };
  2367. /**
  2368. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2369. * @param otherVector defines the other vector
  2370. * @param result defines the target vector
  2371. * @returns the unmodified current Vector2
  2372. */
  2373. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2374. result.x = this.x - otherVector.x;
  2375. result.y = this.y - otherVector.y;
  2376. return this;
  2377. };
  2378. /**
  2379. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2380. * @param otherVector defines the other vector
  2381. * @returns the current updated Vector2
  2382. */
  2383. Vector2.prototype.subtractInPlace = function (otherVector) {
  2384. this.x -= otherVector.x;
  2385. this.y -= otherVector.y;
  2386. return this;
  2387. };
  2388. /**
  2389. * Multiplies in place the current Vector2 coordinates by the given ones
  2390. * @param otherVector defines the other vector
  2391. * @returns the current updated Vector2
  2392. */
  2393. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2394. this.x *= otherVector.x;
  2395. this.y *= otherVector.y;
  2396. return this;
  2397. };
  2398. /**
  2399. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2400. * @param otherVector defines the other vector
  2401. * @returns a new Vector2
  2402. */
  2403. Vector2.prototype.multiply = function (otherVector) {
  2404. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2405. };
  2406. /**
  2407. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2408. * @param otherVector defines the other vector
  2409. * @param result defines the target vector
  2410. * @returns the unmodified current Vector2
  2411. */
  2412. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2413. result.x = this.x * otherVector.x;
  2414. result.y = this.y * otherVector.y;
  2415. return this;
  2416. };
  2417. /**
  2418. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2419. * @param x defines the first coordinate
  2420. * @param y defines the second coordinate
  2421. * @returns a new Vector2
  2422. */
  2423. Vector2.prototype.multiplyByFloats = function (x, y) {
  2424. return new Vector2(this.x * x, this.y * y);
  2425. };
  2426. /**
  2427. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2428. * @param otherVector defines the other vector
  2429. * @returns a new Vector2
  2430. */
  2431. Vector2.prototype.divide = function (otherVector) {
  2432. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2433. };
  2434. /**
  2435. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2436. * @param otherVector defines the other vector
  2437. * @param result defines the target vector
  2438. * @returns the unmodified current Vector2
  2439. */
  2440. Vector2.prototype.divideToRef = function (otherVector, result) {
  2441. result.x = this.x / otherVector.x;
  2442. result.y = this.y / otherVector.y;
  2443. return this;
  2444. };
  2445. /**
  2446. * Divides the current Vector2 coordinates by the given ones
  2447. * @param otherVector defines the other vector
  2448. * @returns the current updated Vector2
  2449. */
  2450. Vector2.prototype.divideInPlace = function (otherVector) {
  2451. return this.divideToRef(otherVector, this);
  2452. };
  2453. /**
  2454. * Gets a new Vector2 with current Vector2 negated coordinates
  2455. * @returns a new Vector2
  2456. */
  2457. Vector2.prototype.negate = function () {
  2458. return new Vector2(-this.x, -this.y);
  2459. };
  2460. /**
  2461. * Multiply the Vector2 coordinates by scale
  2462. * @param scale defines the scaling factor
  2463. * @returns the current updated Vector2
  2464. */
  2465. Vector2.prototype.scaleInPlace = function (scale) {
  2466. this.x *= scale;
  2467. this.y *= scale;
  2468. return this;
  2469. };
  2470. /**
  2471. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2472. * @param scale defines the scaling factor
  2473. * @returns a new Vector2
  2474. */
  2475. Vector2.prototype.scale = function (scale) {
  2476. var result = new Vector2(0, 0);
  2477. this.scaleToRef(scale, result);
  2478. return result;
  2479. };
  2480. /**
  2481. * Scale the current Vector2 values by a factor to a given Vector2
  2482. * @param scale defines the scale factor
  2483. * @param result defines the Vector2 object where to store the result
  2484. * @returns the unmodified current Vector2
  2485. */
  2486. Vector2.prototype.scaleToRef = function (scale, result) {
  2487. result.x = this.x * scale;
  2488. result.y = this.y * scale;
  2489. return this;
  2490. };
  2491. /**
  2492. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2493. * @param scale defines the scale factor
  2494. * @param result defines the Vector2 object where to store the result
  2495. * @returns the unmodified current Vector2
  2496. */
  2497. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2498. result.x += this.x * scale;
  2499. result.y += this.y * scale;
  2500. return this;
  2501. };
  2502. /**
  2503. * Gets a boolean if two vectors are equals
  2504. * @param otherVector defines the other vector
  2505. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2506. */
  2507. Vector2.prototype.equals = function (otherVector) {
  2508. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2509. };
  2510. /**
  2511. * Gets a boolean if two vectors are equals (using an epsilon value)
  2512. * @param otherVector defines the other vector
  2513. * @param epsilon defines the minimal distance to consider equality
  2514. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2515. */
  2516. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2517. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2518. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2519. };
  2520. /**
  2521. * Gets a new Vector2 from current Vector2 floored values
  2522. * @returns a new Vector2
  2523. */
  2524. Vector2.prototype.floor = function () {
  2525. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  2526. };
  2527. /**
  2528. * Gets a new Vector2 from current Vector2 floored values
  2529. * @returns a new Vector2
  2530. */
  2531. Vector2.prototype.fract = function () {
  2532. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  2533. };
  2534. // Properties
  2535. /**
  2536. * Gets the length of the vector
  2537. * @returns the vector length (float)
  2538. */
  2539. Vector2.prototype.length = function () {
  2540. return Math.sqrt(this.x * this.x + this.y * this.y);
  2541. };
  2542. /**
  2543. * Gets the vector squared length
  2544. * @returns the vector squared length (float)
  2545. */
  2546. Vector2.prototype.lengthSquared = function () {
  2547. return (this.x * this.x + this.y * this.y);
  2548. };
  2549. // Methods
  2550. /**
  2551. * Normalize the vector
  2552. * @returns the current updated Vector2
  2553. */
  2554. Vector2.prototype.normalize = function () {
  2555. var len = this.length();
  2556. if (len === 0)
  2557. return this;
  2558. var num = 1.0 / len;
  2559. this.x *= num;
  2560. this.y *= num;
  2561. return this;
  2562. };
  2563. /**
  2564. * Gets a new Vector2 copied from the Vector2
  2565. * @returns a new Vector2
  2566. */
  2567. Vector2.prototype.clone = function () {
  2568. return new Vector2(this.x, this.y);
  2569. };
  2570. // Statics
  2571. /**
  2572. * Gets a new Vector2(0, 0)
  2573. * @returns a new Vector2
  2574. */
  2575. Vector2.Zero = function () {
  2576. return new Vector2(0, 0);
  2577. };
  2578. /**
  2579. * Gets a new Vector2(1, 1)
  2580. * @returns a new Vector2
  2581. */
  2582. Vector2.One = function () {
  2583. return new Vector2(1, 1);
  2584. };
  2585. /**
  2586. * Gets a new Vector2 set from the given index element of the given array
  2587. * @param array defines the data source
  2588. * @param offset defines the offset in the data source
  2589. * @returns a new Vector2
  2590. */
  2591. Vector2.FromArray = function (array, offset) {
  2592. if (offset === void 0) { offset = 0; }
  2593. return new Vector2(array[offset], array[offset + 1]);
  2594. };
  2595. /**
  2596. * Sets "result" from the given index element of the given array
  2597. * @param array defines the data source
  2598. * @param offset defines the offset in the data source
  2599. * @param result defines the target vector
  2600. */
  2601. Vector2.FromArrayToRef = function (array, offset, result) {
  2602. result.x = array[offset];
  2603. result.y = array[offset + 1];
  2604. };
  2605. /**
  2606. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2607. * @param value1 defines 1st point of control
  2608. * @param value2 defines 2nd point of control
  2609. * @param value3 defines 3rd point of control
  2610. * @param value4 defines 4th point of control
  2611. * @param amount defines the interpolation factor
  2612. * @returns a new Vector2
  2613. */
  2614. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2615. var squared = amount * amount;
  2616. var cubed = amount * squared;
  2617. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2618. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2619. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2620. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2621. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2622. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2623. return new Vector2(x, y);
  2624. };
  2625. /**
  2626. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  2627. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2628. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2629. * @param value defines the value to clamp
  2630. * @param min defines the lower limit
  2631. * @param max defines the upper limit
  2632. * @returns a new Vector2
  2633. */
  2634. Vector2.Clamp = function (value, min, max) {
  2635. var x = value.x;
  2636. x = (x > max.x) ? max.x : x;
  2637. x = (x < min.x) ? min.x : x;
  2638. var y = value.y;
  2639. y = (y > max.y) ? max.y : y;
  2640. y = (y < min.y) ? min.y : y;
  2641. return new Vector2(x, y);
  2642. };
  2643. /**
  2644. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2645. * @param value1 defines the 1st control point
  2646. * @param tangent1 defines the outgoing tangent
  2647. * @param value2 defines the 2nd control point
  2648. * @param tangent2 defines the incoming tangent
  2649. * @param amount defines the interpolation factor
  2650. * @returns a new Vector2
  2651. */
  2652. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2653. var squared = amount * amount;
  2654. var cubed = amount * squared;
  2655. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2656. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2657. var part3 = (cubed - (2.0 * squared)) + amount;
  2658. var part4 = cubed - squared;
  2659. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2660. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2661. return new Vector2(x, y);
  2662. };
  2663. /**
  2664. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2665. * @param start defines the start vector
  2666. * @param end defines the end vector
  2667. * @param amount defines the interpolation factor
  2668. * @returns a new Vector2
  2669. */
  2670. Vector2.Lerp = function (start, end, amount) {
  2671. var x = start.x + ((end.x - start.x) * amount);
  2672. var y = start.y + ((end.y - start.y) * amount);
  2673. return new Vector2(x, y);
  2674. };
  2675. /**
  2676. * Gets the dot product of the vector "left" and the vector "right"
  2677. * @param left defines first vector
  2678. * @param right defines second vector
  2679. * @returns the dot product (float)
  2680. */
  2681. Vector2.Dot = function (left, right) {
  2682. return left.x * right.x + left.y * right.y;
  2683. };
  2684. /**
  2685. * Returns a new Vector2 equal to the normalized given vector
  2686. * @param vector defines the vector to normalize
  2687. * @returns a new Vector2
  2688. */
  2689. Vector2.Normalize = function (vector) {
  2690. var newVector = vector.clone();
  2691. newVector.normalize();
  2692. return newVector;
  2693. };
  2694. /**
  2695. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2696. * @param left defines 1st vector
  2697. * @param right defines 2nd vector
  2698. * @returns a new Vector2
  2699. */
  2700. Vector2.Minimize = function (left, right) {
  2701. var x = (left.x < right.x) ? left.x : right.x;
  2702. var y = (left.y < right.y) ? left.y : right.y;
  2703. return new Vector2(x, y);
  2704. };
  2705. /**
  2706. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2707. * @param left defines 1st vector
  2708. * @param right defines 2nd vector
  2709. * @returns a new Vector2
  2710. */
  2711. Vector2.Maximize = function (left, right) {
  2712. var x = (left.x > right.x) ? left.x : right.x;
  2713. var y = (left.y > right.y) ? left.y : right.y;
  2714. return new Vector2(x, y);
  2715. };
  2716. /**
  2717. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2718. * @param vector defines the vector to transform
  2719. * @param transformation defines the matrix to apply
  2720. * @returns a new Vector2
  2721. */
  2722. Vector2.Transform = function (vector, transformation) {
  2723. var r = Vector2.Zero();
  2724. Vector2.TransformToRef(vector, transformation, r);
  2725. return r;
  2726. };
  2727. /**
  2728. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2729. * @param vector defines the vector to transform
  2730. * @param transformation defines the matrix to apply
  2731. * @param result defines the target vector
  2732. */
  2733. Vector2.TransformToRef = function (vector, transformation, result) {
  2734. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2735. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2736. result.x = x;
  2737. result.y = y;
  2738. };
  2739. /**
  2740. * Determines if a given vector is included in a triangle
  2741. * @param p defines the vector to test
  2742. * @param p0 defines 1st triangle point
  2743. * @param p1 defines 2nd triangle point
  2744. * @param p2 defines 3rd triangle point
  2745. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2746. */
  2747. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2748. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2749. var sign = a < 0 ? -1 : 1;
  2750. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2751. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2752. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2753. };
  2754. /**
  2755. * Gets the distance between the vectors "value1" and "value2"
  2756. * @param value1 defines first vector
  2757. * @param value2 defines second vector
  2758. * @returns the distance between vectors
  2759. */
  2760. Vector2.Distance = function (value1, value2) {
  2761. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2762. };
  2763. /**
  2764. * Returns the squared distance between the vectors "value1" and "value2"
  2765. * @param value1 defines first vector
  2766. * @param value2 defines second vector
  2767. * @returns the squared distance between vectors
  2768. */
  2769. Vector2.DistanceSquared = function (value1, value2) {
  2770. var x = value1.x - value2.x;
  2771. var y = value1.y - value2.y;
  2772. return (x * x) + (y * y);
  2773. };
  2774. /**
  2775. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2776. * @param value1 defines first vector
  2777. * @param value2 defines second vector
  2778. * @returns a new Vector2
  2779. */
  2780. Vector2.Center = function (value1, value2) {
  2781. var center = value1.add(value2);
  2782. center.scaleInPlace(0.5);
  2783. return center;
  2784. };
  2785. /**
  2786. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2787. * @param p defines the middle point
  2788. * @param segA defines one point of the segment
  2789. * @param segB defines the other point of the segment
  2790. * @returns the shortest distance
  2791. */
  2792. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2793. var l2 = Vector2.DistanceSquared(segA, segB);
  2794. if (l2 === 0.0) {
  2795. return Vector2.Distance(p, segA);
  2796. }
  2797. var v = segB.subtract(segA);
  2798. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2799. var proj = segA.add(v.multiplyByFloats(t, t));
  2800. return Vector2.Distance(p, proj);
  2801. };
  2802. return Vector2;
  2803. }());
  2804. BABYLON.Vector2 = Vector2;
  2805. /**
  2806. * Classed used to store (x,y,z) vector representation
  2807. * A Vector3 is the main object used in 3D geometry
  2808. * It can represent etiher the coordinates of a point the space, either a direction
  2809. * Reminder: Babylon.js uses a left handed forward facing system
  2810. */
  2811. var Vector3 = /** @class */ (function () {
  2812. /**
  2813. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2814. * @param x defines the first coordinates (on X axis)
  2815. * @param y defines the second coordinates (on Y axis)
  2816. * @param z defines the third coordinates (on Z axis)
  2817. */
  2818. function Vector3(
  2819. /**
  2820. * Defines the first coordinates (on X axis)
  2821. */
  2822. x,
  2823. /**
  2824. * Defines the second coordinates (on Y axis)
  2825. */
  2826. y,
  2827. /**
  2828. * Defines the third coordinates (on Z axis)
  2829. */
  2830. z) {
  2831. if (x === void 0) { x = 0; }
  2832. if (y === void 0) { y = 0; }
  2833. if (z === void 0) { z = 0; }
  2834. this.x = x;
  2835. this.y = y;
  2836. this.z = z;
  2837. }
  2838. /**
  2839. * Creates a string representation of the Vector3
  2840. * @returns a string with the Vector3 coordinates.
  2841. */
  2842. Vector3.prototype.toString = function () {
  2843. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2844. };
  2845. /**
  2846. * Gets the class name
  2847. * @returns the string "Vector3"
  2848. */
  2849. Vector3.prototype.getClassName = function () {
  2850. return "Vector3";
  2851. };
  2852. /**
  2853. * Creates the Vector3 hash code
  2854. * @returns a number which tends to be unique between Vector3 instances
  2855. */
  2856. Vector3.prototype.getHashCode = function () {
  2857. var hash = this.x || 0;
  2858. hash = (hash * 397) ^ (this.y || 0);
  2859. hash = (hash * 397) ^ (this.z || 0);
  2860. return hash;
  2861. };
  2862. // Operators
  2863. /**
  2864. * Creates an array containing three elements : the coordinates of the Vector3
  2865. * @returns a new array of numbers
  2866. */
  2867. Vector3.prototype.asArray = function () {
  2868. var result = [];
  2869. this.toArray(result, 0);
  2870. return result;
  2871. };
  2872. /**
  2873. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2874. * @param array defines the destination array
  2875. * @param index defines the offset in the destination array
  2876. * @returns the current Vector3
  2877. */
  2878. Vector3.prototype.toArray = function (array, index) {
  2879. if (index === void 0) { index = 0; }
  2880. array[index] = this.x;
  2881. array[index + 1] = this.y;
  2882. array[index + 2] = this.z;
  2883. return this;
  2884. };
  2885. /**
  2886. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2887. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2888. */
  2889. Vector3.prototype.toQuaternion = function () {
  2890. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2891. };
  2892. /**
  2893. * Adds the given vector to the current Vector3
  2894. * @param otherVector defines the second operand
  2895. * @returns the current updated Vector3
  2896. */
  2897. Vector3.prototype.addInPlace = function (otherVector) {
  2898. this.x += otherVector.x;
  2899. this.y += otherVector.y;
  2900. this.z += otherVector.z;
  2901. return this;
  2902. };
  2903. /**
  2904. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2905. * @param otherVector defines the second operand
  2906. * @returns the resulting Vector3
  2907. */
  2908. Vector3.prototype.add = function (otherVector) {
  2909. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2910. };
  2911. /**
  2912. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2913. * @param otherVector defines the second operand
  2914. * @param result defines the Vector3 object where to store the result
  2915. * @returns the current Vector3
  2916. */
  2917. Vector3.prototype.addToRef = function (otherVector, result) {
  2918. result.x = this.x + otherVector.x;
  2919. result.y = this.y + otherVector.y;
  2920. result.z = this.z + otherVector.z;
  2921. return this;
  2922. };
  2923. /**
  2924. * Subtract the given vector from the current Vector3
  2925. * @param otherVector defines the second operand
  2926. * @returns the current updated Vector3
  2927. */
  2928. Vector3.prototype.subtractInPlace = function (otherVector) {
  2929. this.x -= otherVector.x;
  2930. this.y -= otherVector.y;
  2931. this.z -= otherVector.z;
  2932. return this;
  2933. };
  2934. /**
  2935. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2936. * @param otherVector defines the second operand
  2937. * @returns the resulting Vector3
  2938. */
  2939. Vector3.prototype.subtract = function (otherVector) {
  2940. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2941. };
  2942. /**
  2943. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2944. * @param otherVector defines the second operand
  2945. * @param result defines the Vector3 object where to store the result
  2946. * @returns the current Vector3
  2947. */
  2948. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2949. result.x = this.x - otherVector.x;
  2950. result.y = this.y - otherVector.y;
  2951. result.z = this.z - otherVector.z;
  2952. return this;
  2953. };
  2954. /**
  2955. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2956. * @param x defines the x coordinate of the operand
  2957. * @param y defines the y coordinate of the operand
  2958. * @param z defines the z coordinate of the operand
  2959. * @returns the resulting Vector3
  2960. */
  2961. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2962. return new Vector3(this.x - x, this.y - y, this.z - z);
  2963. };
  2964. /**
  2965. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2966. * @param x defines the x coordinate of the operand
  2967. * @param y defines the y coordinate of the operand
  2968. * @param z defines the z coordinate of the operand
  2969. * @param result defines the Vector3 object where to store the result
  2970. * @returns the current Vector3
  2971. */
  2972. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2973. result.x = this.x - x;
  2974. result.y = this.y - y;
  2975. result.z = this.z - z;
  2976. return this;
  2977. };
  2978. /**
  2979. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2980. * @returns a new Vector3
  2981. */
  2982. Vector3.prototype.negate = function () {
  2983. return new Vector3(-this.x, -this.y, -this.z);
  2984. };
  2985. /**
  2986. * Multiplies the Vector3 coordinates by the float "scale"
  2987. * @param scale defines the multiplier factor
  2988. * @returns the current updated Vector3
  2989. */
  2990. Vector3.prototype.scaleInPlace = function (scale) {
  2991. this.x *= scale;
  2992. this.y *= scale;
  2993. this.z *= scale;
  2994. return this;
  2995. };
  2996. /**
  2997. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2998. * @param scale defines the multiplier factor
  2999. * @returns a new Vector3
  3000. */
  3001. Vector3.prototype.scale = function (scale) {
  3002. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  3003. };
  3004. /**
  3005. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3006. * @param scale defines the multiplier factor
  3007. * @param result defines the Vector3 object where to store the result
  3008. * @returns the current Vector3
  3009. */
  3010. Vector3.prototype.scaleToRef = function (scale, result) {
  3011. result.x = this.x * scale;
  3012. result.y = this.y * scale;
  3013. result.z = this.z * scale;
  3014. return this;
  3015. };
  3016. /**
  3017. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3018. * @param scale defines the scale factor
  3019. * @param result defines the Vector3 object where to store the result
  3020. * @returns the unmodified current Vector3
  3021. */
  3022. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3023. result.x += this.x * scale;
  3024. result.y += this.y * scale;
  3025. result.z += this.z * scale;
  3026. return this;
  3027. };
  3028. /**
  3029. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3030. * @param otherVector defines the second operand
  3031. * @returns true if both vectors are equals
  3032. */
  3033. Vector3.prototype.equals = function (otherVector) {
  3034. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3035. };
  3036. /**
  3037. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3038. * @param otherVector defines the second operand
  3039. * @param epsilon defines the minimal distance to define values as equals
  3040. * @returns true if both vectors are distant less than epsilon
  3041. */
  3042. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3043. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3044. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  3045. };
  3046. /**
  3047. * Returns true if the current Vector3 coordinates equals the given floats
  3048. * @param x defines the x coordinate of the operand
  3049. * @param y defines the y coordinate of the operand
  3050. * @param z defines the z coordinate of the operand
  3051. * @returns true if both vectors are equals
  3052. */
  3053. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3054. return this.x === x && this.y === y && this.z === z;
  3055. };
  3056. /**
  3057. * Multiplies the current Vector3 coordinates by the given ones
  3058. * @param otherVector defines the second operand
  3059. * @returns the current updated Vector3
  3060. */
  3061. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3062. this.x *= otherVector.x;
  3063. this.y *= otherVector.y;
  3064. this.z *= otherVector.z;
  3065. return this;
  3066. };
  3067. /**
  3068. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3069. * @param otherVector defines the second operand
  3070. * @returns the new Vector3
  3071. */
  3072. Vector3.prototype.multiply = function (otherVector) {
  3073. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3074. };
  3075. /**
  3076. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3077. * @param otherVector defines the second operand
  3078. * @param result defines the Vector3 object where to store the result
  3079. * @returns the current Vector3
  3080. */
  3081. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3082. result.x = this.x * otherVector.x;
  3083. result.y = this.y * otherVector.y;
  3084. result.z = this.z * otherVector.z;
  3085. return this;
  3086. };
  3087. /**
  3088. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3089. * @param x defines the x coordinate of the operand
  3090. * @param y defines the y coordinate of the operand
  3091. * @param z defines the z coordinate of the operand
  3092. * @returns the new Vector3
  3093. */
  3094. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3095. return new Vector3(this.x * x, this.y * y, this.z * z);
  3096. };
  3097. /**
  3098. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3099. * @param otherVector defines the second operand
  3100. * @returns the new Vector3
  3101. */
  3102. Vector3.prototype.divide = function (otherVector) {
  3103. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3104. };
  3105. /**
  3106. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3107. * @param otherVector defines the second operand
  3108. * @param result defines the Vector3 object where to store the result
  3109. * @returns the current Vector3
  3110. */
  3111. Vector3.prototype.divideToRef = function (otherVector, result) {
  3112. result.x = this.x / otherVector.x;
  3113. result.y = this.y / otherVector.y;
  3114. result.z = this.z / otherVector.z;
  3115. return this;
  3116. };
  3117. /**
  3118. * Divides the current Vector3 coordinates by the given ones.
  3119. * @param otherVector defines the second operand
  3120. * @returns the current updated Vector3
  3121. */
  3122. Vector3.prototype.divideInPlace = function (otherVector) {
  3123. return this.divideToRef(otherVector, this);
  3124. };
  3125. /**
  3126. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3127. * @param other defines the second operand
  3128. * @returns the current updated Vector3
  3129. */
  3130. Vector3.prototype.minimizeInPlace = function (other) {
  3131. if (other.x < this.x)
  3132. this.x = other.x;
  3133. if (other.y < this.y)
  3134. this.y = other.y;
  3135. if (other.z < this.z)
  3136. this.z = other.z;
  3137. return this;
  3138. };
  3139. /**
  3140. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3141. * @param other defines the second operand
  3142. * @returns the current updated Vector3
  3143. */
  3144. Vector3.prototype.maximizeInPlace = function (other) {
  3145. if (other.x > this.x)
  3146. this.x = other.x;
  3147. if (other.y > this.y)
  3148. this.y = other.y;
  3149. if (other.z > this.z)
  3150. this.z = other.z;
  3151. return this;
  3152. };
  3153. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3154. /**
  3155. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3156. */
  3157. get: function () {
  3158. var absX = Math.abs(this.x);
  3159. var absY = Math.abs(this.y);
  3160. if (absX !== absY) {
  3161. return true;
  3162. }
  3163. var absZ = Math.abs(this.z);
  3164. if (absX !== absZ) {
  3165. return true;
  3166. }
  3167. if (absY !== absZ) {
  3168. return true;
  3169. }
  3170. return false;
  3171. },
  3172. enumerable: true,
  3173. configurable: true
  3174. });
  3175. /**
  3176. * Gets a new Vector3 from current Vector3 floored values
  3177. * @returns a new Vector3
  3178. */
  3179. Vector3.prototype.floor = function () {
  3180. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  3181. };
  3182. /**
  3183. * Gets a new Vector3 from current Vector3 floored values
  3184. * @returns a new Vector3
  3185. */
  3186. Vector3.prototype.fract = function () {
  3187. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  3188. };
  3189. // Properties
  3190. /**
  3191. * Gets the length of the Vector3
  3192. * @returns the length of the Vecto3
  3193. */
  3194. Vector3.prototype.length = function () {
  3195. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3196. };
  3197. /**
  3198. * Gets the squared length of the Vector3
  3199. * @returns squared length of the Vector3
  3200. */
  3201. Vector3.prototype.lengthSquared = function () {
  3202. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3203. };
  3204. /**
  3205. * Normalize the current Vector3.
  3206. * Please note that this is an in place operation.
  3207. * @returns the current updated Vector3
  3208. */
  3209. Vector3.prototype.normalize = function () {
  3210. var len = this.length();
  3211. if (len === 0 || len === 1.0)
  3212. return this;
  3213. var num = 1.0 / len;
  3214. this.x *= num;
  3215. this.y *= num;
  3216. this.z *= num;
  3217. return this;
  3218. };
  3219. /**
  3220. * Normalize the current Vector3 to a new vector
  3221. * @returns the new Vector3
  3222. */
  3223. Vector3.prototype.normalizeToNew = function () {
  3224. var normalized = new Vector3(0, 0, 0);
  3225. this.normalizeToRef(normalized);
  3226. return normalized;
  3227. };
  3228. /**
  3229. * Normalize the current Vector3 to the reference
  3230. * @param reference define the Vector3 to update
  3231. * @returns the updated Vector3
  3232. */
  3233. Vector3.prototype.normalizeToRef = function (reference) {
  3234. var len = this.length();
  3235. if (len === 0 || len === 1.0) {
  3236. reference.set(this.x, this.y, this.z);
  3237. return reference;
  3238. }
  3239. var scale = 1.0 / len;
  3240. this.scaleToRef(scale, reference);
  3241. return reference;
  3242. };
  3243. /**
  3244. * Creates a new Vector3 copied from the current Vector3
  3245. * @returns the new Vector3
  3246. */
  3247. Vector3.prototype.clone = function () {
  3248. return new Vector3(this.x, this.y, this.z);
  3249. };
  3250. /**
  3251. * Copies the given vector coordinates to the current Vector3 ones
  3252. * @param source defines the source Vector3
  3253. * @returns the current updated Vector3
  3254. */
  3255. Vector3.prototype.copyFrom = function (source) {
  3256. this.x = source.x;
  3257. this.y = source.y;
  3258. this.z = source.z;
  3259. return this;
  3260. };
  3261. /**
  3262. * Copies the given floats to the current Vector3 coordinates
  3263. * @param x defines the x coordinate of the operand
  3264. * @param y defines the y coordinate of the operand
  3265. * @param z defines the z coordinate of the operand
  3266. * @returns the current updated Vector3
  3267. */
  3268. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3269. this.x = x;
  3270. this.y = y;
  3271. this.z = z;
  3272. return this;
  3273. };
  3274. /**
  3275. * Copies the given floats to the current Vector3 coordinates
  3276. * @param x defines the x coordinate of the operand
  3277. * @param y defines the y coordinate of the operand
  3278. * @param z defines the z coordinate of the operand
  3279. * @returns the current updated Vector3
  3280. */
  3281. Vector3.prototype.set = function (x, y, z) {
  3282. return this.copyFromFloats(x, y, z);
  3283. };
  3284. // Statics
  3285. /**
  3286. * Get the clip factor between two vectors
  3287. * @param vector0 defines the first operand
  3288. * @param vector1 defines the second operand
  3289. * @param axis defines the axis to use
  3290. * @param size defines the size along the axis
  3291. * @returns the clip factor
  3292. */
  3293. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3294. var d0 = Vector3.Dot(vector0, axis) - size;
  3295. var d1 = Vector3.Dot(vector1, axis) - size;
  3296. var s = d0 / (d0 - d1);
  3297. return s;
  3298. };
  3299. /**
  3300. * Get angle between two vectors
  3301. * @param vector0 angle between vector0 and vector1
  3302. * @param vector1 angle between vector0 and vector1
  3303. * @param normal direction of the normal
  3304. * @return the angle between vector0 and vector1
  3305. */
  3306. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3307. var v0 = vector0.clone().normalize();
  3308. var v1 = vector1.clone().normalize();
  3309. var dot = Vector3.Dot(v0, v1);
  3310. var n = Vector3.Cross(v0, v1);
  3311. if (Vector3.Dot(n, normal) > 0) {
  3312. return Math.acos(dot);
  3313. }
  3314. return -Math.acos(dot);
  3315. };
  3316. /**
  3317. * Returns a new Vector3 set from the index "offset" of the given array
  3318. * @param array defines the source array
  3319. * @param offset defines the offset in the source array
  3320. * @returns the new Vector3
  3321. */
  3322. Vector3.FromArray = function (array, offset) {
  3323. if (!offset) {
  3324. offset = 0;
  3325. }
  3326. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3327. };
  3328. /**
  3329. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3330. * This function is deprecated. Use FromArray instead
  3331. * @param array defines the source array
  3332. * @param offset defines the offset in the source array
  3333. * @returns the new Vector3
  3334. */
  3335. Vector3.FromFloatArray = function (array, offset) {
  3336. return Vector3.FromArray(array, offset);
  3337. };
  3338. /**
  3339. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3340. * @param array defines the source array
  3341. * @param offset defines the offset in the source array
  3342. * @param result defines the Vector3 where to store the result
  3343. */
  3344. Vector3.FromArrayToRef = function (array, offset, result) {
  3345. result.x = array[offset];
  3346. result.y = array[offset + 1];
  3347. result.z = array[offset + 2];
  3348. };
  3349. /**
  3350. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3351. * This function is deprecated. Use FromArrayToRef instead.
  3352. * @param array defines the source array
  3353. * @param offset defines the offset in the source array
  3354. * @param result defines the Vector3 where to store the result
  3355. */
  3356. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3357. return Vector3.FromArrayToRef(array, offset, result);
  3358. };
  3359. /**
  3360. * Sets the given vector "result" with the given floats.
  3361. * @param x defines the x coordinate of the source
  3362. * @param y defines the y coordinate of the source
  3363. * @param z defines the z coordinate of the source
  3364. * @param result defines the Vector3 where to store the result
  3365. */
  3366. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3367. result.x = x;
  3368. result.y = y;
  3369. result.z = z;
  3370. };
  3371. /**
  3372. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3373. * @returns a new empty Vector3
  3374. */
  3375. Vector3.Zero = function () {
  3376. return new Vector3(0.0, 0.0, 0.0);
  3377. };
  3378. /**
  3379. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3380. * @returns a new unit Vector3
  3381. */
  3382. Vector3.One = function () {
  3383. return new Vector3(1.0, 1.0, 1.0);
  3384. };
  3385. /**
  3386. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3387. * @returns a new up Vector3
  3388. */
  3389. Vector3.Up = function () {
  3390. return new Vector3(0.0, 1.0, 0.0);
  3391. };
  3392. /**
  3393. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3394. * @returns a new down Vector3
  3395. */
  3396. Vector3.Down = function () {
  3397. return new Vector3(0.0, -1.0, 0.0);
  3398. };
  3399. /**
  3400. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3401. * @returns a new forward Vector3
  3402. */
  3403. Vector3.Forward = function () {
  3404. return new Vector3(0.0, 0.0, 1.0);
  3405. };
  3406. /**
  3407. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3408. * @returns a new right Vector3
  3409. */
  3410. Vector3.Right = function () {
  3411. return new Vector3(1.0, 0.0, 0.0);
  3412. };
  3413. /**
  3414. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3415. * @returns a new left Vector3
  3416. */
  3417. Vector3.Left = function () {
  3418. return new Vector3(-1.0, 0.0, 0.0);
  3419. };
  3420. /**
  3421. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3422. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3423. * @param vector defines the Vector3 to transform
  3424. * @param transformation defines the transformation matrix
  3425. * @returns the transformed Vector3
  3426. */
  3427. Vector3.TransformCoordinates = function (vector, transformation) {
  3428. var result = Vector3.Zero();
  3429. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3430. return result;
  3431. };
  3432. /**
  3433. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3434. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3435. * @param vector defines the Vector3 to transform
  3436. * @param transformation defines the transformation matrix
  3437. * @param result defines the Vector3 where to store the result
  3438. */
  3439. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3440. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3441. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3442. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3443. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3444. result.x = x / w;
  3445. result.y = y / w;
  3446. result.z = z / w;
  3447. };
  3448. /**
  3449. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3450. * This method computes tranformed coordinates only, not transformed direction vectors
  3451. * @param x define the x coordinate of the source vector
  3452. * @param y define the y coordinate of the source vector
  3453. * @param z define the z coordinate of the source vector
  3454. * @param transformation defines the transformation matrix
  3455. * @param result defines the Vector3 where to store the result
  3456. */
  3457. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3458. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3459. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3460. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3461. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3462. result.x = rx / rw;
  3463. result.y = ry / rw;
  3464. result.z = rz / rw;
  3465. };
  3466. /**
  3467. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3468. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3469. * @param vector defines the Vector3 to transform
  3470. * @param transformation defines the transformation matrix
  3471. * @returns the new Vector3
  3472. */
  3473. Vector3.TransformNormal = function (vector, transformation) {
  3474. var result = Vector3.Zero();
  3475. Vector3.TransformNormalToRef(vector, transformation, result);
  3476. return result;
  3477. };
  3478. /**
  3479. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3480. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3481. * @param vector defines the Vector3 to transform
  3482. * @param transformation defines the transformation matrix
  3483. * @param result defines the Vector3 where to store the result
  3484. */
  3485. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3486. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3487. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3488. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3489. result.x = x;
  3490. result.y = y;
  3491. result.z = z;
  3492. };
  3493. /**
  3494. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3495. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3496. * @param x define the x coordinate of the source vector
  3497. * @param y define the y coordinate of the source vector
  3498. * @param z define the z coordinate of the source vector
  3499. * @param transformation defines the transformation matrix
  3500. * @param result defines the Vector3 where to store the result
  3501. */
  3502. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3503. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3504. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3505. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3506. };
  3507. /**
  3508. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3509. * @param value1 defines the first control point
  3510. * @param value2 defines the second control point
  3511. * @param value3 defines the third control point
  3512. * @param value4 defines the fourth control point
  3513. * @param amount defines the amount on the spline to use
  3514. * @returns the new Vector3
  3515. */
  3516. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3517. var squared = amount * amount;
  3518. var cubed = amount * squared;
  3519. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3520. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3521. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3522. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3523. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3524. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3525. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3526. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3527. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3528. return new Vector3(x, y, z);
  3529. };
  3530. /**
  3531. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
  3532. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3533. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3534. * @param value defines the current value
  3535. * @param min defines the lower range value
  3536. * @param max defines the upper range value
  3537. * @returns the new Vector3
  3538. */
  3539. Vector3.Clamp = function (value, min, max) {
  3540. var x = value.x;
  3541. x = (x > max.x) ? max.x : x;
  3542. x = (x < min.x) ? min.x : x;
  3543. var y = value.y;
  3544. y = (y > max.y) ? max.y : y;
  3545. y = (y < min.y) ? min.y : y;
  3546. var z = value.z;
  3547. z = (z > max.z) ? max.z : z;
  3548. z = (z < min.z) ? min.z : z;
  3549. return new Vector3(x, y, z);
  3550. };
  3551. /**
  3552. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3553. * @param value1 defines the first control point
  3554. * @param tangent1 defines the first tangent vector
  3555. * @param value2 defines the second control point
  3556. * @param tangent2 defines the second tangent vector
  3557. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3558. * @returns the new Vector3
  3559. */
  3560. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3561. var squared = amount * amount;
  3562. var cubed = amount * squared;
  3563. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3564. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3565. var part3 = (cubed - (2.0 * squared)) + amount;
  3566. var part4 = cubed - squared;
  3567. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3568. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3569. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3570. return new Vector3(x, y, z);
  3571. };
  3572. /**
  3573. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3574. * @param start defines the start value
  3575. * @param end defines the end value
  3576. * @param amount max defines amount between both (between 0 and 1)
  3577. * @returns the new Vector3
  3578. */
  3579. Vector3.Lerp = function (start, end, amount) {
  3580. var result = new Vector3(0, 0, 0);
  3581. Vector3.LerpToRef(start, end, amount, result);
  3582. return result;
  3583. };
  3584. /**
  3585. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3586. * @param start defines the start value
  3587. * @param end defines the end value
  3588. * @param amount max defines amount between both (between 0 and 1)
  3589. * @param result defines the Vector3 where to store the result
  3590. */
  3591. Vector3.LerpToRef = function (start, end, amount, result) {
  3592. result.x = start.x + ((end.x - start.x) * amount);
  3593. result.y = start.y + ((end.y - start.y) * amount);
  3594. result.z = start.z + ((end.z - start.z) * amount);
  3595. };
  3596. /**
  3597. * Returns the dot product (float) between the vectors "left" and "right"
  3598. * @param left defines the left operand
  3599. * @param right defines the right operand
  3600. * @returns the dot product
  3601. */
  3602. Vector3.Dot = function (left, right) {
  3603. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3604. };
  3605. /**
  3606. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3607. * The cross product is then orthogonal to both "left" and "right"
  3608. * @param left defines the left operand
  3609. * @param right defines the right operand
  3610. * @returns the cross product
  3611. */
  3612. Vector3.Cross = function (left, right) {
  3613. var result = Vector3.Zero();
  3614. Vector3.CrossToRef(left, right, result);
  3615. return result;
  3616. };
  3617. /**
  3618. * Sets the given vector "result" with the cross product of "left" and "right"
  3619. * The cross product is then orthogonal to both "left" and "right"
  3620. * @param left defines the left operand
  3621. * @param right defines the right operand
  3622. * @param result defines the Vector3 where to store the result
  3623. */
  3624. Vector3.CrossToRef = function (left, right, result) {
  3625. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3626. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3627. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3628. result.copyFrom(MathTmp.Vector3[0]);
  3629. };
  3630. /**
  3631. * Returns a new Vector3 as the normalization of the given vector
  3632. * @param vector defines the Vector3 to normalize
  3633. * @returns the new Vector3
  3634. */
  3635. Vector3.Normalize = function (vector) {
  3636. var result = Vector3.Zero();
  3637. Vector3.NormalizeToRef(vector, result);
  3638. return result;
  3639. };
  3640. /**
  3641. * Sets the given vector "result" with the normalization of the given first vector
  3642. * @param vector defines the Vector3 to normalize
  3643. * @param result defines the Vector3 where to store the result
  3644. */
  3645. Vector3.NormalizeToRef = function (vector, result) {
  3646. result.copyFrom(vector);
  3647. result.normalize();
  3648. };
  3649. /**
  3650. * Project a Vector3 onto screen space
  3651. * @param vector defines the Vector3 to project
  3652. * @param world defines the world matrix to use
  3653. * @param transform defines the transform (view x projection) matrix to use
  3654. * @param viewport defines the screen viewport to use
  3655. * @returns the new Vector3
  3656. */
  3657. Vector3.Project = function (vector, world, transform, viewport) {
  3658. var cw = viewport.width;
  3659. var ch = viewport.height;
  3660. var cx = viewport.x;
  3661. var cy = viewport.y;
  3662. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3663. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  3664. var matrix = MathTmp.Matrix[0];
  3665. world.multiplyToRef(transform, matrix);
  3666. matrix.multiplyToRef(viewportMatrix, matrix);
  3667. return Vector3.TransformCoordinates(vector, matrix);
  3668. };
  3669. /**
  3670. * Unproject from screen space to object space
  3671. * @param source defines the screen space Vector3 to use
  3672. * @param viewportWidth defines the current width of the viewport
  3673. * @param viewportHeight defines the current height of the viewport
  3674. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3675. * @param transform defines the transform (view x projection) matrix to use
  3676. * @returns the new Vector3
  3677. */
  3678. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3679. var matrix = MathTmp.Matrix[0];
  3680. world.multiplyToRef(transform, matrix);
  3681. matrix.invert();
  3682. source.x = source.x / viewportWidth * 2 - 1;
  3683. source.y = -(source.y / viewportHeight * 2 - 1);
  3684. var vector = Vector3.TransformCoordinates(source, matrix);
  3685. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3686. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3687. vector = vector.scale(1.0 / num);
  3688. }
  3689. return vector;
  3690. };
  3691. /**
  3692. * Unproject from screen space to object space
  3693. * @param source defines the screen space Vector3 to use
  3694. * @param viewportWidth defines the current width of the viewport
  3695. * @param viewportHeight defines the current height of the viewport
  3696. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3697. * @param view defines the view matrix to use
  3698. * @param projection defines the projection matrix to use
  3699. * @returns the new Vector3
  3700. */
  3701. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3702. var result = Vector3.Zero();
  3703. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3704. return result;
  3705. };
  3706. /**
  3707. * Unproject from screen space to object space
  3708. * @param source defines the screen space Vector3 to use
  3709. * @param viewportWidth defines the current width of the viewport
  3710. * @param viewportHeight defines the current height of the viewport
  3711. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3712. * @param view defines the view matrix to use
  3713. * @param projection defines the projection matrix to use
  3714. * @param result defines the Vector3 where to store the result
  3715. */
  3716. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3717. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3718. };
  3719. /**
  3720. * Unproject from screen space to object space
  3721. * @param sourceX defines the screen space x coordinate to use
  3722. * @param sourceY defines the screen space y coordinate to use
  3723. * @param sourceZ defines the screen space z coordinate to use
  3724. * @param viewportWidth defines the current width of the viewport
  3725. * @param viewportHeight defines the current height of the viewport
  3726. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3727. * @param view defines the view matrix to use
  3728. * @param projection defines the projection matrix to use
  3729. * @param result defines the Vector3 where to store the result
  3730. */
  3731. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3732. var matrix = MathTmp.Matrix[0];
  3733. world.multiplyToRef(view, matrix);
  3734. matrix.multiplyToRef(projection, matrix);
  3735. matrix.invert();
  3736. var screenSource = MathTmp.Vector3[0];
  3737. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3738. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3739. screenSource.z = 2 * sourceZ - 1.0;
  3740. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3741. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3742. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3743. result.scaleInPlace(1.0 / num);
  3744. }
  3745. };
  3746. /**
  3747. * Gets the minimal coordinate values between two Vector3
  3748. * @param left defines the first operand
  3749. * @param right defines the second operand
  3750. * @returns the new Vector3
  3751. */
  3752. Vector3.Minimize = function (left, right) {
  3753. var min = left.clone();
  3754. min.minimizeInPlace(right);
  3755. return min;
  3756. };
  3757. /**
  3758. * Gets the maximal coordinate values between two Vector3
  3759. * @param left defines the first operand
  3760. * @param right defines the second operand
  3761. * @returns the new Vector3
  3762. */
  3763. Vector3.Maximize = function (left, right) {
  3764. var max = left.clone();
  3765. max.maximizeInPlace(right);
  3766. return max;
  3767. };
  3768. /**
  3769. * Returns the distance between the vectors "value1" and "value2"
  3770. * @param value1 defines the first operand
  3771. * @param value2 defines the second operand
  3772. * @returns the distance
  3773. */
  3774. Vector3.Distance = function (value1, value2) {
  3775. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3776. };
  3777. /**
  3778. * Returns the squared distance between the vectors "value1" and "value2"
  3779. * @param value1 defines the first operand
  3780. * @param value2 defines the second operand
  3781. * @returns the squared distance
  3782. */
  3783. Vector3.DistanceSquared = function (value1, value2) {
  3784. var x = value1.x - value2.x;
  3785. var y = value1.y - value2.y;
  3786. var z = value1.z - value2.z;
  3787. return (x * x) + (y * y) + (z * z);
  3788. };
  3789. /**
  3790. * Returns a new Vector3 located at the center between "value1" and "value2"
  3791. * @param value1 defines the first operand
  3792. * @param value2 defines the second operand
  3793. * @returns the new Vector3
  3794. */
  3795. Vector3.Center = function (value1, value2) {
  3796. var center = value1.add(value2);
  3797. center.scaleInPlace(0.5);
  3798. return center;
  3799. };
  3800. /**
  3801. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3802. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3803. * to something in order to rotate it from its local system to the given target system
  3804. * Note: axis1, axis2 and axis3 are normalized during this operation
  3805. * @param axis1 defines the first axis
  3806. * @param axis2 defines the second axis
  3807. * @param axis3 defines the third axis
  3808. * @returns a new Vector3
  3809. */
  3810. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3811. var rotation = Vector3.Zero();
  3812. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3813. return rotation;
  3814. };
  3815. /**
  3816. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3817. * @param axis1 defines the first axis
  3818. * @param axis2 defines the second axis
  3819. * @param axis3 defines the third axis
  3820. * @param ref defines the Vector3 where to store the result
  3821. */
  3822. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3823. var quat = MathTmp.Quaternion[0];
  3824. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3825. quat.toEulerAnglesToRef(ref);
  3826. };
  3827. return Vector3;
  3828. }());
  3829. BABYLON.Vector3 = Vector3;
  3830. //Vector4 class created for EulerAngle class conversion to Quaternion
  3831. var Vector4 = /** @class */ (function () {
  3832. /**
  3833. * Creates a Vector4 object from the given floats.
  3834. */
  3835. function Vector4(x, y, z, w) {
  3836. this.x = x;
  3837. this.y = y;
  3838. this.z = z;
  3839. this.w = w;
  3840. }
  3841. /**
  3842. * Returns the string with the Vector4 coordinates.
  3843. */
  3844. Vector4.prototype.toString = function () {
  3845. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3846. };
  3847. /**
  3848. * Returns the string "Vector4".
  3849. */
  3850. Vector4.prototype.getClassName = function () {
  3851. return "Vector4";
  3852. };
  3853. /**
  3854. * Returns the Vector4 hash code.
  3855. */
  3856. Vector4.prototype.getHashCode = function () {
  3857. var hash = this.x || 0;
  3858. hash = (hash * 397) ^ (this.y || 0);
  3859. hash = (hash * 397) ^ (this.z || 0);
  3860. hash = (hash * 397) ^ (this.w || 0);
  3861. return hash;
  3862. };
  3863. // Operators
  3864. /**
  3865. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3866. */
  3867. Vector4.prototype.asArray = function () {
  3868. var result = new Array();
  3869. this.toArray(result, 0);
  3870. return result;
  3871. };
  3872. /**
  3873. * Populates the given array from the given index with the Vector4 coordinates.
  3874. * Returns the Vector4.
  3875. */
  3876. Vector4.prototype.toArray = function (array, index) {
  3877. if (index === undefined) {
  3878. index = 0;
  3879. }
  3880. array[index] = this.x;
  3881. array[index + 1] = this.y;
  3882. array[index + 2] = this.z;
  3883. array[index + 3] = this.w;
  3884. return this;
  3885. };
  3886. /**
  3887. * Adds the given vector to the current Vector4.
  3888. * Returns the updated Vector4.
  3889. */
  3890. Vector4.prototype.addInPlace = function (otherVector) {
  3891. this.x += otherVector.x;
  3892. this.y += otherVector.y;
  3893. this.z += otherVector.z;
  3894. this.w += otherVector.w;
  3895. return this;
  3896. };
  3897. /**
  3898. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3899. */
  3900. Vector4.prototype.add = function (otherVector) {
  3901. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3902. };
  3903. /**
  3904. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3905. * Returns the current Vector4.
  3906. */
  3907. Vector4.prototype.addToRef = function (otherVector, result) {
  3908. result.x = this.x + otherVector.x;
  3909. result.y = this.y + otherVector.y;
  3910. result.z = this.z + otherVector.z;
  3911. result.w = this.w + otherVector.w;
  3912. return this;
  3913. };
  3914. /**
  3915. * Subtract in place the given vector from the current Vector4.
  3916. * Returns the updated Vector4.
  3917. */
  3918. Vector4.prototype.subtractInPlace = function (otherVector) {
  3919. this.x -= otherVector.x;
  3920. this.y -= otherVector.y;
  3921. this.z -= otherVector.z;
  3922. this.w -= otherVector.w;
  3923. return this;
  3924. };
  3925. /**
  3926. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3927. */
  3928. Vector4.prototype.subtract = function (otherVector) {
  3929. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3930. };
  3931. /**
  3932. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3933. * Returns the current Vector4.
  3934. */
  3935. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3936. result.x = this.x - otherVector.x;
  3937. result.y = this.y - otherVector.y;
  3938. result.z = this.z - otherVector.z;
  3939. result.w = this.w - otherVector.w;
  3940. return this;
  3941. };
  3942. /**
  3943. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3944. */
  3945. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3946. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3947. };
  3948. /**
  3949. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3950. * Returns the current Vector4.
  3951. */
  3952. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3953. result.x = this.x - x;
  3954. result.y = this.y - y;
  3955. result.z = this.z - z;
  3956. result.w = this.w - w;
  3957. return this;
  3958. };
  3959. /**
  3960. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3961. */
  3962. Vector4.prototype.negate = function () {
  3963. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3964. };
  3965. /**
  3966. * Multiplies the current Vector4 coordinates by scale (float).
  3967. * Returns the updated Vector4.
  3968. */
  3969. Vector4.prototype.scaleInPlace = function (scale) {
  3970. this.x *= scale;
  3971. this.y *= scale;
  3972. this.z *= scale;
  3973. this.w *= scale;
  3974. return this;
  3975. };
  3976. /**
  3977. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3978. */
  3979. Vector4.prototype.scale = function (scale) {
  3980. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3981. };
  3982. /**
  3983. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3984. * Returns the current Vector4.
  3985. */
  3986. Vector4.prototype.scaleToRef = function (scale, result) {
  3987. result.x = this.x * scale;
  3988. result.y = this.y * scale;
  3989. result.z = this.z * scale;
  3990. result.w = this.w * scale;
  3991. return this;
  3992. };
  3993. /**
  3994. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3995. * @param scale defines the scale factor
  3996. * @param result defines the Vector4 object where to store the result
  3997. * @returns the unmodified current Vector4
  3998. */
  3999. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4000. result.x += this.x * scale;
  4001. result.y += this.y * scale;
  4002. result.z += this.z * scale;
  4003. result.w += this.w * scale;
  4004. return this;
  4005. };
  4006. /**
  4007. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4008. */
  4009. Vector4.prototype.equals = function (otherVector) {
  4010. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4011. };
  4012. /**
  4013. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4014. */
  4015. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4016. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4017. return otherVector
  4018. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4019. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4020. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4021. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4022. };
  4023. /**
  4024. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4025. */
  4026. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4027. return this.x === x && this.y === y && this.z === z && this.w === w;
  4028. };
  4029. /**
  4030. * Multiplies in place the current Vector4 by the given one.
  4031. * Returns the updated Vector4.
  4032. */
  4033. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4034. this.x *= otherVector.x;
  4035. this.y *= otherVector.y;
  4036. this.z *= otherVector.z;
  4037. this.w *= otherVector.w;
  4038. return this;
  4039. };
  4040. /**
  4041. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4042. */
  4043. Vector4.prototype.multiply = function (otherVector) {
  4044. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4045. };
  4046. /**
  4047. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4048. * Returns the current Vector4.
  4049. */
  4050. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4051. result.x = this.x * otherVector.x;
  4052. result.y = this.y * otherVector.y;
  4053. result.z = this.z * otherVector.z;
  4054. result.w = this.w * otherVector.w;
  4055. return this;
  4056. };
  4057. /**
  4058. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4059. */
  4060. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4061. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4062. };
  4063. /**
  4064. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4065. */
  4066. Vector4.prototype.divide = function (otherVector) {
  4067. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4068. };
  4069. /**
  4070. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4071. * Returns the current Vector4.
  4072. */
  4073. Vector4.prototype.divideToRef = function (otherVector, result) {
  4074. result.x = this.x / otherVector.x;
  4075. result.y = this.y / otherVector.y;
  4076. result.z = this.z / otherVector.z;
  4077. result.w = this.w / otherVector.w;
  4078. return this;
  4079. };
  4080. /**
  4081. * Divides the current Vector3 coordinates by the given ones.
  4082. * @returns the updated Vector3.
  4083. */
  4084. Vector4.prototype.divideInPlace = function (otherVector) {
  4085. return this.divideToRef(otherVector, this);
  4086. };
  4087. /**
  4088. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4089. * @param other defines the second operand
  4090. * @returns the current updated Vector4
  4091. */
  4092. Vector4.prototype.minimizeInPlace = function (other) {
  4093. if (other.x < this.x)
  4094. this.x = other.x;
  4095. if (other.y < this.y)
  4096. this.y = other.y;
  4097. if (other.z < this.z)
  4098. this.z = other.z;
  4099. if (other.w < this.w)
  4100. this.w = other.w;
  4101. return this;
  4102. };
  4103. /**
  4104. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4105. * @param other defines the second operand
  4106. * @returns the current updated Vector4
  4107. */
  4108. Vector4.prototype.maximizeInPlace = function (other) {
  4109. if (other.x > this.x)
  4110. this.x = other.x;
  4111. if (other.y > this.y)
  4112. this.y = other.y;
  4113. if (other.z > this.z)
  4114. this.z = other.z;
  4115. if (other.w > this.w)
  4116. this.w = other.w;
  4117. return this;
  4118. };
  4119. /**
  4120. * Gets a new Vector4 from current Vector4 floored values
  4121. * @returns a new Vector4
  4122. */
  4123. Vector4.prototype.floor = function () {
  4124. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  4125. };
  4126. /**
  4127. * Gets a new Vector4 from current Vector3 floored values
  4128. * @returns a new Vector4
  4129. */
  4130. Vector4.prototype.fract = function () {
  4131. return new Vector4(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z), this.w - Math.floor(this.w));
  4132. };
  4133. // Properties
  4134. /**
  4135. * Returns the Vector4 length (float).
  4136. */
  4137. Vector4.prototype.length = function () {
  4138. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4139. };
  4140. /**
  4141. * Returns the Vector4 squared length (float).
  4142. */
  4143. Vector4.prototype.lengthSquared = function () {
  4144. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4145. };
  4146. // Methods
  4147. /**
  4148. * Normalizes in place the Vector4.
  4149. * Returns the updated Vector4.
  4150. */
  4151. Vector4.prototype.normalize = function () {
  4152. var len = this.length();
  4153. if (len === 0)
  4154. return this;
  4155. var num = 1.0 / len;
  4156. this.x *= num;
  4157. this.y *= num;
  4158. this.z *= num;
  4159. this.w *= num;
  4160. return this;
  4161. };
  4162. /**
  4163. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4164. */
  4165. Vector4.prototype.toVector3 = function () {
  4166. return new Vector3(this.x, this.y, this.z);
  4167. };
  4168. /**
  4169. * Returns a new Vector4 copied from the current one.
  4170. */
  4171. Vector4.prototype.clone = function () {
  4172. return new Vector4(this.x, this.y, this.z, this.w);
  4173. };
  4174. /**
  4175. * Updates the current Vector4 with the given one coordinates.
  4176. * Returns the updated Vector4.
  4177. */
  4178. Vector4.prototype.copyFrom = function (source) {
  4179. this.x = source.x;
  4180. this.y = source.y;
  4181. this.z = source.z;
  4182. this.w = source.w;
  4183. return this;
  4184. };
  4185. /**
  4186. * Updates the current Vector4 coordinates with the given floats.
  4187. * Returns the updated Vector4.
  4188. */
  4189. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4190. this.x = x;
  4191. this.y = y;
  4192. this.z = z;
  4193. this.w = w;
  4194. return this;
  4195. };
  4196. /**
  4197. * Updates the current Vector4 coordinates with the given floats.
  4198. * Returns the updated Vector4.
  4199. */
  4200. Vector4.prototype.set = function (x, y, z, w) {
  4201. return this.copyFromFloats(x, y, z, w);
  4202. };
  4203. // Statics
  4204. /**
  4205. * Returns a new Vector4 set from the starting index of the given array.
  4206. */
  4207. Vector4.FromArray = function (array, offset) {
  4208. if (!offset) {
  4209. offset = 0;
  4210. }
  4211. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4212. };
  4213. /**
  4214. * Updates the given vector "result" from the starting index of the given array.
  4215. */
  4216. Vector4.FromArrayToRef = function (array, offset, result) {
  4217. result.x = array[offset];
  4218. result.y = array[offset + 1];
  4219. result.z = array[offset + 2];
  4220. result.w = array[offset + 3];
  4221. };
  4222. /**
  4223. * Updates the given vector "result" from the starting index of the given Float32Array.
  4224. */
  4225. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4226. Vector4.FromArrayToRef(array, offset, result);
  4227. };
  4228. /**
  4229. * Updates the given vector "result" coordinates from the given floats.
  4230. */
  4231. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4232. result.x = x;
  4233. result.y = y;
  4234. result.z = z;
  4235. result.w = w;
  4236. };
  4237. /**
  4238. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4239. */
  4240. Vector4.Zero = function () {
  4241. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4242. };
  4243. /**
  4244. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4245. */
  4246. Vector4.One = function () {
  4247. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4248. };
  4249. /**
  4250. * Returns a new normalized Vector4 from the given one.
  4251. */
  4252. Vector4.Normalize = function (vector) {
  4253. var result = Vector4.Zero();
  4254. Vector4.NormalizeToRef(vector, result);
  4255. return result;
  4256. };
  4257. /**
  4258. * Updates the given vector "result" from the normalization of the given one.
  4259. */
  4260. Vector4.NormalizeToRef = function (vector, result) {
  4261. result.copyFrom(vector);
  4262. result.normalize();
  4263. };
  4264. Vector4.Minimize = function (left, right) {
  4265. var min = left.clone();
  4266. min.minimizeInPlace(right);
  4267. return min;
  4268. };
  4269. Vector4.Maximize = function (left, right) {
  4270. var max = left.clone();
  4271. max.maximizeInPlace(right);
  4272. return max;
  4273. };
  4274. /**
  4275. * Returns the distance (float) between the vectors "value1" and "value2".
  4276. */
  4277. Vector4.Distance = function (value1, value2) {
  4278. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4279. };
  4280. /**
  4281. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4282. */
  4283. Vector4.DistanceSquared = function (value1, value2) {
  4284. var x = value1.x - value2.x;
  4285. var y = value1.y - value2.y;
  4286. var z = value1.z - value2.z;
  4287. var w = value1.w - value2.w;
  4288. return (x * x) + (y * y) + (z * z) + (w * w);
  4289. };
  4290. /**
  4291. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4292. */
  4293. Vector4.Center = function (value1, value2) {
  4294. var center = value1.add(value2);
  4295. center.scaleInPlace(0.5);
  4296. return center;
  4297. };
  4298. /**
  4299. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4300. * This methods computes transformed normalized direction vectors only.
  4301. */
  4302. Vector4.TransformNormal = function (vector, transformation) {
  4303. var result = Vector4.Zero();
  4304. Vector4.TransformNormalToRef(vector, transformation, result);
  4305. return result;
  4306. };
  4307. /**
  4308. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4309. * This methods computes transformed normalized direction vectors only.
  4310. */
  4311. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4312. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4313. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4314. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4315. result.x = x;
  4316. result.y = y;
  4317. result.z = z;
  4318. result.w = vector.w;
  4319. };
  4320. /**
  4321. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4322. * This methods computes transformed normalized direction vectors only.
  4323. */
  4324. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4325. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4326. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4327. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4328. result.w = w;
  4329. };
  4330. return Vector4;
  4331. }());
  4332. BABYLON.Vector4 = Vector4;
  4333. var Size = /** @class */ (function () {
  4334. /**
  4335. * Creates a Size object from the given width and height (floats).
  4336. */
  4337. function Size(width, height) {
  4338. this.width = width;
  4339. this.height = height;
  4340. }
  4341. // Returns a string with the Size width and height.
  4342. Size.prototype.toString = function () {
  4343. return "{W: " + this.width + ", H: " + this.height + "}";
  4344. };
  4345. /**
  4346. * Returns the string "Size"
  4347. */
  4348. Size.prototype.getClassName = function () {
  4349. return "Size";
  4350. };
  4351. /**
  4352. * Returns the Size hash code.
  4353. */
  4354. Size.prototype.getHashCode = function () {
  4355. var hash = this.width || 0;
  4356. hash = (hash * 397) ^ (this.height || 0);
  4357. return hash;
  4358. };
  4359. /**
  4360. * Updates the current size from the given one.
  4361. * Returns the updated Size.
  4362. */
  4363. Size.prototype.copyFrom = function (src) {
  4364. this.width = src.width;
  4365. this.height = src.height;
  4366. };
  4367. /**
  4368. * Updates in place the current Size from the given floats.
  4369. * Returns the updated Size.
  4370. */
  4371. Size.prototype.copyFromFloats = function (width, height) {
  4372. this.width = width;
  4373. this.height = height;
  4374. return this;
  4375. };
  4376. /**
  4377. * Updates in place the current Size from the given floats.
  4378. * Returns the updated Size.
  4379. */
  4380. Size.prototype.set = function (width, height) {
  4381. return this.copyFromFloats(width, height);
  4382. };
  4383. /**
  4384. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4385. */
  4386. Size.prototype.multiplyByFloats = function (w, h) {
  4387. return new Size(this.width * w, this.height * h);
  4388. };
  4389. /**
  4390. * Returns a new Size copied from the given one.
  4391. */
  4392. Size.prototype.clone = function () {
  4393. return new Size(this.width, this.height);
  4394. };
  4395. /**
  4396. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4397. */
  4398. Size.prototype.equals = function (other) {
  4399. if (!other) {
  4400. return false;
  4401. }
  4402. return (this.width === other.width) && (this.height === other.height);
  4403. };
  4404. Object.defineProperty(Size.prototype, "surface", {
  4405. /**
  4406. * Returns the surface of the Size : width * height (float).
  4407. */
  4408. get: function () {
  4409. return this.width * this.height;
  4410. },
  4411. enumerable: true,
  4412. configurable: true
  4413. });
  4414. /**
  4415. * Returns a new Size set to (0.0, 0.0)
  4416. */
  4417. Size.Zero = function () {
  4418. return new Size(0.0, 0.0);
  4419. };
  4420. /**
  4421. * Returns a new Size set as the addition result of the current Size and the given one.
  4422. */
  4423. Size.prototype.add = function (otherSize) {
  4424. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4425. return r;
  4426. };
  4427. /**
  4428. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4429. */
  4430. Size.prototype.subtract = function (otherSize) {
  4431. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4432. return r;
  4433. };
  4434. /**
  4435. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4436. */
  4437. Size.Lerp = function (start, end, amount) {
  4438. var w = start.width + ((end.width - start.width) * amount);
  4439. var h = start.height + ((end.height - start.height) * amount);
  4440. return new Size(w, h);
  4441. };
  4442. return Size;
  4443. }());
  4444. BABYLON.Size = Size;
  4445. /**
  4446. * Class used to store quaternion data
  4447. * @see https://en.wikipedia.org/wiki/Quaternion
  4448. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4449. */
  4450. var Quaternion = /** @class */ (function () {
  4451. /**
  4452. * Creates a new Quaternion from the given floats
  4453. * @param x defines the first component (0 by default)
  4454. * @param y defines the second component (0 by default)
  4455. * @param z defines the third component (0 by default)
  4456. * @param w defines the fourth component (1.0 by default)
  4457. */
  4458. function Quaternion(
  4459. /** defines the first component (0 by default) */
  4460. x,
  4461. /** defines the second component (0 by default) */
  4462. y,
  4463. /** defines the third component (0 by default) */
  4464. z,
  4465. /** defines the fourth component (1.0 by default) */
  4466. w) {
  4467. if (x === void 0) { x = 0.0; }
  4468. if (y === void 0) { y = 0.0; }
  4469. if (z === void 0) { z = 0.0; }
  4470. if (w === void 0) { w = 1.0; }
  4471. this.x = x;
  4472. this.y = y;
  4473. this.z = z;
  4474. this.w = w;
  4475. }
  4476. /**
  4477. * Gets a string representation for the current quaternion
  4478. * @returns a string with the Quaternion coordinates
  4479. */
  4480. Quaternion.prototype.toString = function () {
  4481. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4482. };
  4483. /**
  4484. * Gets the class name of the quaternion
  4485. * @returns the string "Quaternion"
  4486. */
  4487. Quaternion.prototype.getClassName = function () {
  4488. return "Quaternion";
  4489. };
  4490. /**
  4491. * Gets a hash code for this quaternion
  4492. * @returns the quaternion hash code
  4493. */
  4494. Quaternion.prototype.getHashCode = function () {
  4495. var hash = this.x || 0;
  4496. hash = (hash * 397) ^ (this.y || 0);
  4497. hash = (hash * 397) ^ (this.z || 0);
  4498. hash = (hash * 397) ^ (this.w || 0);
  4499. return hash;
  4500. };
  4501. /**
  4502. * Copy the quaternion to an array
  4503. * @returns a new array populated with 4 elements from the quaternion coordinates
  4504. */
  4505. Quaternion.prototype.asArray = function () {
  4506. return [this.x, this.y, this.z, this.w];
  4507. };
  4508. /**
  4509. * Check if two quaternions are equals
  4510. * @param otherQuaternion defines the second operand
  4511. * @return true if the current quaternion and the given one coordinates are strictly equals
  4512. */
  4513. Quaternion.prototype.equals = function (otherQuaternion) {
  4514. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4515. };
  4516. /**
  4517. * Clone the current quaternion
  4518. * @returns a new quaternion copied from the current one
  4519. */
  4520. Quaternion.prototype.clone = function () {
  4521. return new Quaternion(this.x, this.y, this.z, this.w);
  4522. };
  4523. /**
  4524. * Copy a quaternion to the current one
  4525. * @param other defines the other quaternion
  4526. * @returns the updated current quaternion
  4527. */
  4528. Quaternion.prototype.copyFrom = function (other) {
  4529. this.x = other.x;
  4530. this.y = other.y;
  4531. this.z = other.z;
  4532. this.w = other.w;
  4533. return this;
  4534. };
  4535. /**
  4536. * Updates the current quaternion with the given float coordinates
  4537. * @param x defines the x coordinate
  4538. * @param y defines the y coordinate
  4539. * @param z defines the z coordinate
  4540. * @param w defines the w coordinate
  4541. * @returns the updated current quaternion
  4542. */
  4543. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4544. this.x = x;
  4545. this.y = y;
  4546. this.z = z;
  4547. this.w = w;
  4548. return this;
  4549. };
  4550. /**
  4551. * Updates the current quaternion from the given float coordinates
  4552. * @param x defines the x coordinate
  4553. * @param y defines the y coordinate
  4554. * @param z defines the z coordinate
  4555. * @param w defines the w coordinate
  4556. * @returns the updated current quaternion
  4557. */
  4558. Quaternion.prototype.set = function (x, y, z, w) {
  4559. return this.copyFromFloats(x, y, z, w);
  4560. };
  4561. /**
  4562. * Adds two quaternions
  4563. * @param other defines the second operand
  4564. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4565. */
  4566. Quaternion.prototype.add = function (other) {
  4567. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4568. };
  4569. /**
  4570. * Add a quaternion to the current one
  4571. * @param other defines the quaternion to add
  4572. * @returns the current quaternion
  4573. */
  4574. Quaternion.prototype.addInPlace = function (other) {
  4575. this.x += other.x;
  4576. this.y += other.y;
  4577. this.z += other.z;
  4578. this.w += other.w;
  4579. return this;
  4580. };
  4581. /**
  4582. * Subtract two quaternions
  4583. * @param other defines the second operand
  4584. * @returns a new quaternion as the subtraction result of the given one from the current one
  4585. */
  4586. Quaternion.prototype.subtract = function (other) {
  4587. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4588. };
  4589. /**
  4590. * Multiplies the current quaternion by a scale factor
  4591. * @param value defines the scale factor
  4592. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4593. */
  4594. Quaternion.prototype.scale = function (value) {
  4595. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4596. };
  4597. /**
  4598. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4599. * @param scale defines the scale factor
  4600. * @param result defines the Quaternion object where to store the result
  4601. * @returns the unmodified current quaternion
  4602. */
  4603. Quaternion.prototype.scaleToRef = function (scale, result) {
  4604. result.x = this.x * scale;
  4605. result.y = this.y * scale;
  4606. result.z = this.z * scale;
  4607. result.w = this.w * scale;
  4608. return this;
  4609. };
  4610. /**
  4611. * Multiplies in place the current quaternion by a scale factor
  4612. * @param value defines the scale factor
  4613. * @returns the current modified quaternion
  4614. */
  4615. Quaternion.prototype.scaleInPlace = function (value) {
  4616. this.x *= value;
  4617. this.y *= value;
  4618. this.z *= value;
  4619. this.w *= value;
  4620. return this;
  4621. };
  4622. /**
  4623. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4624. * @param scale defines the scale factor
  4625. * @param result defines the Quaternion object where to store the result
  4626. * @returns the unmodified current quaternion
  4627. */
  4628. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4629. result.x += this.x * scale;
  4630. result.y += this.y * scale;
  4631. result.z += this.z * scale;
  4632. result.w += this.w * scale;
  4633. return this;
  4634. };
  4635. /**
  4636. * Multiplies two quaternions
  4637. * @param q1 defines the second operand
  4638. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4639. */
  4640. Quaternion.prototype.multiply = function (q1) {
  4641. var result = new Quaternion(0, 0, 0, 1.0);
  4642. this.multiplyToRef(q1, result);
  4643. return result;
  4644. };
  4645. /**
  4646. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4647. * @param q1 defines the second operand
  4648. * @param result defines the target quaternion
  4649. * @returns the current quaternion
  4650. */
  4651. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4652. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4653. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4654. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4655. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4656. result.copyFromFloats(x, y, z, w);
  4657. return this;
  4658. };
  4659. /**
  4660. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4661. * @param q1 defines the second operand
  4662. * @returns the currentupdated quaternion
  4663. */
  4664. Quaternion.prototype.multiplyInPlace = function (q1) {
  4665. this.multiplyToRef(q1, this);
  4666. return this;
  4667. };
  4668. /**
  4669. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4670. * @param ref defines the target quaternion
  4671. * @returns the current quaternion
  4672. */
  4673. Quaternion.prototype.conjugateToRef = function (ref) {
  4674. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4675. return this;
  4676. };
  4677. /**
  4678. * Conjugates in place (1-q) the current quaternion
  4679. * @returns the current updated quaternion
  4680. */
  4681. Quaternion.prototype.conjugateInPlace = function () {
  4682. this.x *= -1;
  4683. this.y *= -1;
  4684. this.z *= -1;
  4685. return this;
  4686. };
  4687. /**
  4688. * Conjugates in place (1-q) the current quaternion
  4689. * @returns a new quaternion
  4690. */
  4691. Quaternion.prototype.conjugate = function () {
  4692. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4693. return result;
  4694. };
  4695. /**
  4696. * Gets length of current quaternion
  4697. * @returns the quaternion length (float)
  4698. */
  4699. Quaternion.prototype.length = function () {
  4700. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4701. };
  4702. /**
  4703. * Normalize in place the current quaternion
  4704. * @returns the current updated quaternion
  4705. */
  4706. Quaternion.prototype.normalize = function () {
  4707. var length = 1.0 / this.length();
  4708. this.x *= length;
  4709. this.y *= length;
  4710. this.z *= length;
  4711. this.w *= length;
  4712. return this;
  4713. };
  4714. /**
  4715. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4716. * @param order is a reserved parameter and is ignore for now
  4717. * @returns a new Vector3 containing the Euler angles
  4718. */
  4719. Quaternion.prototype.toEulerAngles = function (order) {
  4720. if (order === void 0) { order = "YZX"; }
  4721. var result = Vector3.Zero();
  4722. this.toEulerAnglesToRef(result, order);
  4723. return result;
  4724. };
  4725. /**
  4726. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4727. * @param result defines the vector which will be filled with the Euler angles
  4728. * @param order is a reserved parameter and is ignore for now
  4729. * @returns the current unchanged quaternion
  4730. */
  4731. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4732. if (order === void 0) { order = "YZX"; }
  4733. var qz = this.z;
  4734. var qx = this.x;
  4735. var qy = this.y;
  4736. var qw = this.w;
  4737. var sqw = qw * qw;
  4738. var sqz = qz * qz;
  4739. var sqx = qx * qx;
  4740. var sqy = qy * qy;
  4741. var zAxisY = qy * qz - qx * qw;
  4742. var limit = .4999999;
  4743. if (zAxisY < -limit) {
  4744. result.y = 2 * Math.atan2(qy, qw);
  4745. result.x = Math.PI / 2;
  4746. result.z = 0;
  4747. }
  4748. else if (zAxisY > limit) {
  4749. result.y = 2 * Math.atan2(qy, qw);
  4750. result.x = -Math.PI / 2;
  4751. result.z = 0;
  4752. }
  4753. else {
  4754. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4755. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4756. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4757. }
  4758. return this;
  4759. };
  4760. /**
  4761. * Updates the given rotation matrix with the current quaternion values
  4762. * @param result defines the target matrix
  4763. * @returns the current unchanged quaternion
  4764. */
  4765. Quaternion.prototype.toRotationMatrix = function (result) {
  4766. var xx = this.x * this.x;
  4767. var yy = this.y * this.y;
  4768. var zz = this.z * this.z;
  4769. var xy = this.x * this.y;
  4770. var zw = this.z * this.w;
  4771. var zx = this.z * this.x;
  4772. var yw = this.y * this.w;
  4773. var yz = this.y * this.z;
  4774. var xw = this.x * this.w;
  4775. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4776. result.m[1] = 2.0 * (xy + zw);
  4777. result.m[2] = 2.0 * (zx - yw);
  4778. result.m[3] = 0;
  4779. result.m[4] = 2.0 * (xy - zw);
  4780. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4781. result.m[6] = 2.0 * (yz + xw);
  4782. result.m[7] = 0;
  4783. result.m[8] = 2.0 * (zx + yw);
  4784. result.m[9] = 2.0 * (yz - xw);
  4785. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4786. result.m[11] = 0;
  4787. result.m[12] = 0;
  4788. result.m[13] = 0;
  4789. result.m[14] = 0;
  4790. result.m[15] = 1.0;
  4791. result._markAsUpdated();
  4792. return this;
  4793. };
  4794. /**
  4795. * Updates the current quaternion from the given rotation matrix values
  4796. * @param matrix defines the source matrix
  4797. * @returns the current updated quaternion
  4798. */
  4799. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4800. Quaternion.FromRotationMatrixToRef(matrix, this);
  4801. return this;
  4802. };
  4803. // Statics
  4804. /**
  4805. * Creates a new quaternion from a rotation matrix
  4806. * @param matrix defines the source matrix
  4807. * @returns a new quaternion created from the given rotation matrix values
  4808. */
  4809. Quaternion.FromRotationMatrix = function (matrix) {
  4810. var result = new Quaternion();
  4811. Quaternion.FromRotationMatrixToRef(matrix, result);
  4812. return result;
  4813. };
  4814. /**
  4815. * Updates the given quaternion with the given rotation matrix values
  4816. * @param matrix defines the source matrix
  4817. * @param result defines the target quaternion
  4818. */
  4819. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4820. var data = matrix.m;
  4821. var m11 = data[0], m12 = data[4], m13 = data[8];
  4822. var m21 = data[1], m22 = data[5], m23 = data[9];
  4823. var m31 = data[2], m32 = data[6], m33 = data[10];
  4824. var trace = m11 + m22 + m33;
  4825. var s;
  4826. if (trace > 0) {
  4827. s = 0.5 / Math.sqrt(trace + 1.0);
  4828. result.w = 0.25 / s;
  4829. result.x = (m32 - m23) * s;
  4830. result.y = (m13 - m31) * s;
  4831. result.z = (m21 - m12) * s;
  4832. }
  4833. else if (m11 > m22 && m11 > m33) {
  4834. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4835. result.w = (m32 - m23) / s;
  4836. result.x = 0.25 * s;
  4837. result.y = (m12 + m21) / s;
  4838. result.z = (m13 + m31) / s;
  4839. }
  4840. else if (m22 > m33) {
  4841. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4842. result.w = (m13 - m31) / s;
  4843. result.x = (m12 + m21) / s;
  4844. result.y = 0.25 * s;
  4845. result.z = (m23 + m32) / s;
  4846. }
  4847. else {
  4848. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4849. result.w = (m21 - m12) / s;
  4850. result.x = (m13 + m31) / s;
  4851. result.y = (m23 + m32) / s;
  4852. result.z = 0.25 * s;
  4853. }
  4854. };
  4855. /**
  4856. * Returns the dot product (float) between the quaternions "left" and "right"
  4857. * @param left defines the left operand
  4858. * @param right defines the right operand
  4859. * @returns the dot product
  4860. */
  4861. Quaternion.Dot = function (left, right) {
  4862. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4863. };
  4864. /**
  4865. * Checks if the two quaternions are close to each other
  4866. * @param quat0 defines the first quaternion to check
  4867. * @param quat1 defines the second quaternion to check
  4868. * @returns true if the two quaternions are close to each other
  4869. */
  4870. Quaternion.AreClose = function (quat0, quat1) {
  4871. var dot = Quaternion.Dot(quat0, quat1);
  4872. return dot >= 0;
  4873. };
  4874. /**
  4875. * Creates an empty quaternion
  4876. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4877. */
  4878. Quaternion.Zero = function () {
  4879. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4880. };
  4881. /**
  4882. * Inverse a given quaternion
  4883. * @param q defines the source quaternion
  4884. * @returns a new quaternion as the inverted current quaternion
  4885. */
  4886. Quaternion.Inverse = function (q) {
  4887. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4888. };
  4889. /**
  4890. * Creates an identity quaternion
  4891. * @returns the identity quaternion
  4892. */
  4893. Quaternion.Identity = function () {
  4894. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4895. };
  4896. /**
  4897. * Gets a boolean indicating if the given quaternion is identity
  4898. * @param quaternion defines the quaternion to check
  4899. * @returns true if the quaternion is identity
  4900. */
  4901. Quaternion.IsIdentity = function (quaternion) {
  4902. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4903. };
  4904. /**
  4905. * Creates a quaternion from a rotation around an axis
  4906. * @param axis defines the axis to use
  4907. * @param angle defines the angle to use
  4908. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4909. */
  4910. Quaternion.RotationAxis = function (axis, angle) {
  4911. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4912. };
  4913. /**
  4914. * Creates a rotation around an axis and stores it into the given quaternion
  4915. * @param axis defines the axis to use
  4916. * @param angle defines the angle to use
  4917. * @param result defines the target quaternion
  4918. * @returns the target quaternion
  4919. */
  4920. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4921. var sin = Math.sin(angle / 2);
  4922. axis.normalize();
  4923. result.w = Math.cos(angle / 2);
  4924. result.x = axis.x * sin;
  4925. result.y = axis.y * sin;
  4926. result.z = axis.z * sin;
  4927. return result;
  4928. };
  4929. /**
  4930. * Creates a new quaternion from data stored into an array
  4931. * @param array defines the data source
  4932. * @param offset defines the offset in the source array where the data starts
  4933. * @returns a new quaternion
  4934. */
  4935. Quaternion.FromArray = function (array, offset) {
  4936. if (!offset) {
  4937. offset = 0;
  4938. }
  4939. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4940. };
  4941. /**
  4942. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4943. * @param yaw defines the rotation around Y axis
  4944. * @param pitch defines the rotation around X axis
  4945. * @param roll defines the rotation around Z axis
  4946. * @returns the new quaternion
  4947. */
  4948. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4949. var q = new Quaternion();
  4950. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4951. return q;
  4952. };
  4953. /**
  4954. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4955. * @param yaw defines the rotation around Y axis
  4956. * @param pitch defines the rotation around X axis
  4957. * @param roll defines the rotation around Z axis
  4958. * @param result defines the target quaternion
  4959. */
  4960. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4961. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4962. var halfRoll = roll * 0.5;
  4963. var halfPitch = pitch * 0.5;
  4964. var halfYaw = yaw * 0.5;
  4965. var sinRoll = Math.sin(halfRoll);
  4966. var cosRoll = Math.cos(halfRoll);
  4967. var sinPitch = Math.sin(halfPitch);
  4968. var cosPitch = Math.cos(halfPitch);
  4969. var sinYaw = Math.sin(halfYaw);
  4970. var cosYaw = Math.cos(halfYaw);
  4971. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4972. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4973. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4974. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4975. };
  4976. /**
  4977. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4978. * @param alpha defines the rotation around first axis
  4979. * @param beta defines the rotation around second axis
  4980. * @param gamma defines the rotation around third axis
  4981. * @returns the new quaternion
  4982. */
  4983. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4984. var result = new Quaternion();
  4985. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4986. return result;
  4987. };
  4988. /**
  4989. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4990. * @param alpha defines the rotation around first axis
  4991. * @param beta defines the rotation around second axis
  4992. * @param gamma defines the rotation around third axis
  4993. * @param result defines the target quaternion
  4994. */
  4995. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4996. // Produces a quaternion from Euler angles in the z-x-z orientation
  4997. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4998. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4999. var halfBeta = beta * 0.5;
  5000. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5001. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5002. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5003. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5004. };
  5005. /**
  5006. * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation)
  5007. * @param axis1 defines the first axis
  5008. * @param axis2 defines the second axis
  5009. * @param axis3 defines the third axis
  5010. * @returns the new quaternion
  5011. */
  5012. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5013. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5014. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5015. return quat;
  5016. };
  5017. /**
  5018. * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion
  5019. * @param axis1 defines the first axis
  5020. * @param axis2 defines the second axis
  5021. * @param axis3 defines the third axis
  5022. * @param ref defines the target quaternion
  5023. */
  5024. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5025. var rotMat = MathTmp.Matrix[0];
  5026. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5027. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5028. };
  5029. /**
  5030. * Interpolates between two quaternions
  5031. * @param left defines first quaternion
  5032. * @param right defines second quaternion
  5033. * @param amount defines the gradient to use
  5034. * @returns the new interpolated quaternion
  5035. */
  5036. Quaternion.Slerp = function (left, right, amount) {
  5037. var result = Quaternion.Identity();
  5038. Quaternion.SlerpToRef(left, right, amount, result);
  5039. return result;
  5040. };
  5041. /**
  5042. * Interpolates between two quaternions and stores it into a target quaternion
  5043. * @param left defines first quaternion
  5044. * @param right defines second quaternion
  5045. * @param amount defines the gradient to use
  5046. * @param result defines the target quaternion
  5047. */
  5048. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5049. var num2;
  5050. var num3;
  5051. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5052. var flag = false;
  5053. if (num4 < 0) {
  5054. flag = true;
  5055. num4 = -num4;
  5056. }
  5057. if (num4 > 0.999999) {
  5058. num3 = 1 - amount;
  5059. num2 = flag ? -amount : amount;
  5060. }
  5061. else {
  5062. var num5 = Math.acos(num4);
  5063. var num6 = (1.0 / Math.sin(num5));
  5064. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5065. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5066. }
  5067. result.x = (num3 * left.x) + (num2 * right.x);
  5068. result.y = (num3 * left.y) + (num2 * right.y);
  5069. result.z = (num3 * left.z) + (num2 * right.z);
  5070. result.w = (num3 * left.w) + (num2 * right.w);
  5071. };
  5072. /**
  5073. * Interpolate between two quaternions using Hermite interpolation
  5074. * @param value1 defines first quaternion
  5075. * @param tangent1 defines the incoming tangent
  5076. * @param value2 defines second quaternion
  5077. * @param tangent2 defines the outgoing tangent
  5078. * @param amount defines the target quaternion
  5079. * @returns the new interpolated quaternion
  5080. */
  5081. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5082. var squared = amount * amount;
  5083. var cubed = amount * squared;
  5084. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5085. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5086. var part3 = (cubed - (2.0 * squared)) + amount;
  5087. var part4 = cubed - squared;
  5088. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5089. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5090. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5091. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5092. return new Quaternion(x, y, z, w);
  5093. };
  5094. return Quaternion;
  5095. }());
  5096. BABYLON.Quaternion = Quaternion;
  5097. /**
  5098. * Class used to store matrix data (4x4)
  5099. */
  5100. var Matrix = /** @class */ (function () {
  5101. /**
  5102. * Creates an empty matrix (filled with zeros)
  5103. */
  5104. function Matrix() {
  5105. this._isIdentity = false;
  5106. this._isIdentityDirty = true;
  5107. /**
  5108. * Gets or sets the internal data of the matrix
  5109. */
  5110. this.m = new Float32Array(16);
  5111. this._markAsUpdated();
  5112. }
  5113. /** @hidden */
  5114. Matrix.prototype._markAsUpdated = function () {
  5115. this.updateFlag = Matrix._updateFlagSeed++;
  5116. this._isIdentityDirty = true;
  5117. };
  5118. // Properties
  5119. /**
  5120. * Check if the current matrix is indentity
  5121. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5122. * @returns true is the matrix is the identity matrix
  5123. */
  5124. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5125. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5126. if (this._isIdentityDirty) {
  5127. this._isIdentityDirty = false;
  5128. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5129. this._isIdentity = false;
  5130. }
  5131. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5132. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5133. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5134. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5135. this._isIdentity = false;
  5136. }
  5137. else {
  5138. this._isIdentity = true;
  5139. }
  5140. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5141. this._isIdentity = false;
  5142. }
  5143. }
  5144. return this._isIdentity;
  5145. };
  5146. /**
  5147. * Gets the determinant of the matrix
  5148. * @returns the matrix determinant
  5149. */
  5150. Matrix.prototype.determinant = function () {
  5151. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5152. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5153. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5154. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5155. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5156. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5157. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5158. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5159. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5160. };
  5161. // Methods
  5162. /**
  5163. * Returns the matrix as a Float32Array
  5164. * @returns the matrix underlying array
  5165. */
  5166. Matrix.prototype.toArray = function () {
  5167. return this.m;
  5168. };
  5169. /**
  5170. * Returns the matrix as a Float32Array
  5171. * @returns the matrix underlying array.
  5172. */
  5173. Matrix.prototype.asArray = function () {
  5174. return this.toArray();
  5175. };
  5176. /**
  5177. * Inverts the current matrix in place
  5178. * @returns the current inverted matrix
  5179. */
  5180. Matrix.prototype.invert = function () {
  5181. this.invertToRef(this);
  5182. return this;
  5183. };
  5184. /**
  5185. * Sets all the matrix elements to zero
  5186. * @returns the current matrix
  5187. */
  5188. Matrix.prototype.reset = function () {
  5189. for (var index = 0; index < 16; index++) {
  5190. this.m[index] = 0.0;
  5191. }
  5192. this._markAsUpdated();
  5193. return this;
  5194. };
  5195. /**
  5196. * Adds the current matrix with a second one
  5197. * @param other defines the matrix to add
  5198. * @returns a new matrix as the addition of the current matrix and the given one
  5199. */
  5200. Matrix.prototype.add = function (other) {
  5201. var result = new Matrix();
  5202. this.addToRef(other, result);
  5203. return result;
  5204. };
  5205. /**
  5206. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5207. * @param other defines the matrix to add
  5208. * @param result defines the target matrix
  5209. * @returns the current matrix
  5210. */
  5211. Matrix.prototype.addToRef = function (other, result) {
  5212. for (var index = 0; index < 16; index++) {
  5213. result.m[index] = this.m[index] + other.m[index];
  5214. }
  5215. result._markAsUpdated();
  5216. return this;
  5217. };
  5218. /**
  5219. * Adds in place the given matrix to the current matrix
  5220. * @param other defines the second operand
  5221. * @returns the current updated matrix
  5222. */
  5223. Matrix.prototype.addToSelf = function (other) {
  5224. for (var index = 0; index < 16; index++) {
  5225. this.m[index] += other.m[index];
  5226. }
  5227. this._markAsUpdated();
  5228. return this;
  5229. };
  5230. /**
  5231. * Sets the given matrix to the current inverted Matrix
  5232. * @param other defines the target matrix
  5233. * @returns the unmodified current matrix
  5234. */
  5235. Matrix.prototype.invertToRef = function (other) {
  5236. var l1 = this.m[0];
  5237. var l2 = this.m[1];
  5238. var l3 = this.m[2];
  5239. var l4 = this.m[3];
  5240. var l5 = this.m[4];
  5241. var l6 = this.m[5];
  5242. var l7 = this.m[6];
  5243. var l8 = this.m[7];
  5244. var l9 = this.m[8];
  5245. var l10 = this.m[9];
  5246. var l11 = this.m[10];
  5247. var l12 = this.m[11];
  5248. var l13 = this.m[12];
  5249. var l14 = this.m[13];
  5250. var l15 = this.m[14];
  5251. var l16 = this.m[15];
  5252. var l17 = (l11 * l16) - (l12 * l15);
  5253. var l18 = (l10 * l16) - (l12 * l14);
  5254. var l19 = (l10 * l15) - (l11 * l14);
  5255. var l20 = (l9 * l16) - (l12 * l13);
  5256. var l21 = (l9 * l15) - (l11 * l13);
  5257. var l22 = (l9 * l14) - (l10 * l13);
  5258. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5259. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5260. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5261. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5262. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5263. var l28 = (l7 * l16) - (l8 * l15);
  5264. var l29 = (l6 * l16) - (l8 * l14);
  5265. var l30 = (l6 * l15) - (l7 * l14);
  5266. var l31 = (l5 * l16) - (l8 * l13);
  5267. var l32 = (l5 * l15) - (l7 * l13);
  5268. var l33 = (l5 * l14) - (l6 * l13);
  5269. var l34 = (l7 * l12) - (l8 * l11);
  5270. var l35 = (l6 * l12) - (l8 * l10);
  5271. var l36 = (l6 * l11) - (l7 * l10);
  5272. var l37 = (l5 * l12) - (l8 * l9);
  5273. var l38 = (l5 * l11) - (l7 * l9);
  5274. var l39 = (l5 * l10) - (l6 * l9);
  5275. other.m[0] = l23 * l27;
  5276. other.m[4] = l24 * l27;
  5277. other.m[8] = l25 * l27;
  5278. other.m[12] = l26 * l27;
  5279. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5280. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5281. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5282. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5283. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5284. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5285. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5286. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5287. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5288. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5289. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5290. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5291. other._markAsUpdated();
  5292. return this;
  5293. };
  5294. /**
  5295. * Inserts the translation vector (using 3 floats) in the current matrix
  5296. * @param x defines the 1st component of the translation
  5297. * @param y defines the 2nd component of the translation
  5298. * @param z defines the 3rd component of the translation
  5299. * @returns the current updated matrix
  5300. */
  5301. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5302. this.m[12] = x;
  5303. this.m[13] = y;
  5304. this.m[14] = z;
  5305. this._markAsUpdated();
  5306. return this;
  5307. };
  5308. /**
  5309. * Inserts the translation vector in the current matrix
  5310. * @param vector3 defines the translation to insert
  5311. * @returns the current updated matrix
  5312. */
  5313. Matrix.prototype.setTranslation = function (vector3) {
  5314. this.m[12] = vector3.x;
  5315. this.m[13] = vector3.y;
  5316. this.m[14] = vector3.z;
  5317. this._markAsUpdated();
  5318. return this;
  5319. };
  5320. /**
  5321. * Gets the translation value of the current matrix
  5322. * @returns a new Vector3 as the extracted translation from the matrix
  5323. */
  5324. Matrix.prototype.getTranslation = function () {
  5325. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5326. };
  5327. /**
  5328. * Fill a Vector3 with the extracted translation from the matrix
  5329. * @param result defines the Vector3 where to store the translation
  5330. * @returns the current matrix
  5331. */
  5332. Matrix.prototype.getTranslationToRef = function (result) {
  5333. result.x = this.m[12];
  5334. result.y = this.m[13];
  5335. result.z = this.m[14];
  5336. return this;
  5337. };
  5338. /**
  5339. * Remove rotation and scaling part from the matrix
  5340. * @returns the updated matrix
  5341. */
  5342. Matrix.prototype.removeRotationAndScaling = function () {
  5343. this.setRowFromFloats(0, 1, 0, 0, 0);
  5344. this.setRowFromFloats(1, 0, 1, 0, 0);
  5345. this.setRowFromFloats(2, 0, 0, 1, 0);
  5346. return this;
  5347. };
  5348. /**
  5349. * Multiply two matrices
  5350. * @param other defines the second operand
  5351. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5352. */
  5353. Matrix.prototype.multiply = function (other) {
  5354. var result = new Matrix();
  5355. this.multiplyToRef(other, result);
  5356. return result;
  5357. };
  5358. /**
  5359. * Copy the current matrix from the given one
  5360. * @param other defines the source matrix
  5361. * @returns the current updated matrix
  5362. */
  5363. Matrix.prototype.copyFrom = function (other) {
  5364. for (var index = 0; index < 16; index++) {
  5365. this.m[index] = other.m[index];
  5366. }
  5367. this._markAsUpdated();
  5368. return this;
  5369. };
  5370. /**
  5371. * Populates the given array from the starting index with the current matrix values
  5372. * @param array defines the target array
  5373. * @param offset defines the offset in the target array where to start storing values
  5374. * @returns the current matrix
  5375. */
  5376. Matrix.prototype.copyToArray = function (array, offset) {
  5377. if (offset === void 0) { offset = 0; }
  5378. for (var index = 0; index < 16; index++) {
  5379. array[offset + index] = this.m[index];
  5380. }
  5381. return this;
  5382. };
  5383. /**
  5384. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5385. * @param other defines the second operand
  5386. * @param result defines the matrix where to store the multiplication
  5387. * @returns the current matrix
  5388. */
  5389. Matrix.prototype.multiplyToRef = function (other, result) {
  5390. this.multiplyToArray(other, result.m, 0);
  5391. result._markAsUpdated();
  5392. return this;
  5393. };
  5394. /**
  5395. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5396. * @param other defines the second operand
  5397. * @param result defines the array where to store the multiplication
  5398. * @param offset defines the offset in the target array where to start storing values
  5399. * @returns the current matrix
  5400. */
  5401. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5402. var tm0 = this.m[0];
  5403. var tm1 = this.m[1];
  5404. var tm2 = this.m[2];
  5405. var tm3 = this.m[3];
  5406. var tm4 = this.m[4];
  5407. var tm5 = this.m[5];
  5408. var tm6 = this.m[6];
  5409. var tm7 = this.m[7];
  5410. var tm8 = this.m[8];
  5411. var tm9 = this.m[9];
  5412. var tm10 = this.m[10];
  5413. var tm11 = this.m[11];
  5414. var tm12 = this.m[12];
  5415. var tm13 = this.m[13];
  5416. var tm14 = this.m[14];
  5417. var tm15 = this.m[15];
  5418. var om0 = other.m[0];
  5419. var om1 = other.m[1];
  5420. var om2 = other.m[2];
  5421. var om3 = other.m[3];
  5422. var om4 = other.m[4];
  5423. var om5 = other.m[5];
  5424. var om6 = other.m[6];
  5425. var om7 = other.m[7];
  5426. var om8 = other.m[8];
  5427. var om9 = other.m[9];
  5428. var om10 = other.m[10];
  5429. var om11 = other.m[11];
  5430. var om12 = other.m[12];
  5431. var om13 = other.m[13];
  5432. var om14 = other.m[14];
  5433. var om15 = other.m[15];
  5434. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5435. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5436. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5437. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5438. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5439. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5440. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5441. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5442. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5443. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5444. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5445. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5446. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5447. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5448. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5449. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5450. return this;
  5451. };
  5452. /**
  5453. * Check equality between this matrix and a second one
  5454. * @param value defines the second matrix to compare
  5455. * @returns true is the current matrix and the given one values are strictly equal
  5456. */
  5457. Matrix.prototype.equals = function (value) {
  5458. return value &&
  5459. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5460. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5461. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5462. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5463. };
  5464. /**
  5465. * Clone the current matrix
  5466. * @returns a new matrix from the current matrix
  5467. */
  5468. Matrix.prototype.clone = function () {
  5469. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  5470. };
  5471. /**
  5472. * Returns the name of the current matrix class
  5473. * @returns the string "Matrix"
  5474. */
  5475. Matrix.prototype.getClassName = function () {
  5476. return "Matrix";
  5477. };
  5478. /**
  5479. * Gets the hash code of the current matrix
  5480. * @returns the hash code
  5481. */
  5482. Matrix.prototype.getHashCode = function () {
  5483. var hash = this.m[0] || 0;
  5484. for (var i = 1; i < 16; i++) {
  5485. hash = (hash * 397) ^ (this.m[i] || 0);
  5486. }
  5487. return hash;
  5488. };
  5489. /**
  5490. * Decomposes the current Matrix into a translation, rotation and scaling components
  5491. * @param scale defines the scale vector3 given as a reference to update
  5492. * @param rotation defines the rotation quaternion given as a reference to update
  5493. * @param translation defines the translation vector3 given as a reference to update
  5494. * @returns true if operation was successful
  5495. */
  5496. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5497. if (translation) {
  5498. translation.x = this.m[12];
  5499. translation.y = this.m[13];
  5500. translation.z = this.m[14];
  5501. }
  5502. scale = scale || MathTmp.Vector3[0];
  5503. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5504. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5505. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5506. if (this.determinant() <= 0) {
  5507. scale.y *= -1;
  5508. }
  5509. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5510. if (rotation) {
  5511. rotation.x = 0;
  5512. rotation.y = 0;
  5513. rotation.z = 0;
  5514. rotation.w = 1;
  5515. }
  5516. return false;
  5517. }
  5518. if (rotation) {
  5519. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  5520. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5521. }
  5522. return true;
  5523. };
  5524. /**
  5525. * Gets specific row of the matrix
  5526. * @param index defines the number of the row to get
  5527. * @returns the index-th row of the current matrix as a new Vector4
  5528. */
  5529. Matrix.prototype.getRow = function (index) {
  5530. if (index < 0 || index > 3) {
  5531. return null;
  5532. }
  5533. var i = index * 4;
  5534. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5535. };
  5536. /**
  5537. * Sets the index-th row of the current matrix to the vector4 values
  5538. * @param index defines the number of the row to set
  5539. * @param row defines the target vector4
  5540. * @returns the updated current matrix
  5541. */
  5542. Matrix.prototype.setRow = function (index, row) {
  5543. if (index < 0 || index > 3) {
  5544. return this;
  5545. }
  5546. var i = index * 4;
  5547. this.m[i + 0] = row.x;
  5548. this.m[i + 1] = row.y;
  5549. this.m[i + 2] = row.z;
  5550. this.m[i + 3] = row.w;
  5551. this._markAsUpdated();
  5552. return this;
  5553. };
  5554. /**
  5555. * Compute the transpose of the matrix
  5556. * @returns the new transposed matrix
  5557. */
  5558. Matrix.prototype.transpose = function () {
  5559. return Matrix.Transpose(this);
  5560. };
  5561. /**
  5562. * Compute the transpose of the matrix and store it in a given matrix
  5563. * @param result defines the target matrix
  5564. * @returns the current matrix
  5565. */
  5566. Matrix.prototype.transposeToRef = function (result) {
  5567. Matrix.TransposeToRef(this, result);
  5568. return this;
  5569. };
  5570. /**
  5571. * Sets the index-th row of the current matrix with the given 4 x float values
  5572. * @param index defines the row index
  5573. * @param x defines the x component to set
  5574. * @param y defines the y component to set
  5575. * @param z defines the z component to set
  5576. * @param w defines the w component to set
  5577. * @returns the updated current matrix
  5578. */
  5579. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5580. if (index < 0 || index > 3) {
  5581. return this;
  5582. }
  5583. var i = index * 4;
  5584. this.m[i + 0] = x;
  5585. this.m[i + 1] = y;
  5586. this.m[i + 2] = z;
  5587. this.m[i + 3] = w;
  5588. this._markAsUpdated();
  5589. return this;
  5590. };
  5591. /**
  5592. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5593. * @param scale defines the scale factor
  5594. * @returns a new matrix
  5595. */
  5596. Matrix.prototype.scale = function (scale) {
  5597. var result = new Matrix();
  5598. this.scaleToRef(scale, result);
  5599. return result;
  5600. };
  5601. /**
  5602. * Scale the current matrix values by a factor to a given result matrix
  5603. * @param scale defines the scale factor
  5604. * @param result defines the matrix to store the result
  5605. * @returns the current matrix
  5606. */
  5607. Matrix.prototype.scaleToRef = function (scale, result) {
  5608. for (var index = 0; index < 16; index++) {
  5609. result.m[index] = this.m[index] * scale;
  5610. }
  5611. result._markAsUpdated();
  5612. return this;
  5613. };
  5614. /**
  5615. * Scale the current matrix values by a factor and add the result to a given matrix
  5616. * @param scale defines the scale factor
  5617. * @param result defines the Matrix to store the result
  5618. * @returns the current matrix
  5619. */
  5620. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5621. for (var index = 0; index < 16; index++) {
  5622. result.m[index] += this.m[index] * scale;
  5623. }
  5624. result._markAsUpdated();
  5625. return this;
  5626. };
  5627. /**
  5628. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5629. * @param ref matrix to store the result
  5630. */
  5631. Matrix.prototype.toNormalMatrix = function (ref) {
  5632. this.invertToRef(ref);
  5633. ref.transpose();
  5634. var m = ref.m;
  5635. Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
  5636. };
  5637. /**
  5638. * Gets only rotation part of the current matrix
  5639. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5640. */
  5641. Matrix.prototype.getRotationMatrix = function () {
  5642. var result = Matrix.Identity();
  5643. this.getRotationMatrixToRef(result);
  5644. return result;
  5645. };
  5646. /**
  5647. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5648. * @param result defines the target matrix to store data to
  5649. * @returns the current matrix
  5650. */
  5651. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5652. var m = this.m;
  5653. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5654. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5655. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5656. if (this.determinant() <= 0) {
  5657. sy *= -1;
  5658. }
  5659. if (sx === 0 || sy === 0 || sz === 0) {
  5660. Matrix.IdentityToRef(result);
  5661. }
  5662. else {
  5663. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  5664. }
  5665. return this;
  5666. };
  5667. // Statics
  5668. /**
  5669. * Creates a matrix from an array
  5670. * @param array defines the source array
  5671. * @param offset defines an offset in the source array
  5672. * @returns a new Matrix set from the starting index of the given array
  5673. */
  5674. Matrix.FromArray = function (array, offset) {
  5675. var result = new Matrix();
  5676. if (!offset) {
  5677. offset = 0;
  5678. }
  5679. Matrix.FromArrayToRef(array, offset, result);
  5680. return result;
  5681. };
  5682. /**
  5683. * Copy the content of an array into a given matrix
  5684. * @param array defines the source array
  5685. * @param offset defines an offset in the source array
  5686. * @param result defines the target matrix
  5687. */
  5688. Matrix.FromArrayToRef = function (array, offset, result) {
  5689. for (var index = 0; index < 16; index++) {
  5690. result.m[index] = array[index + offset];
  5691. }
  5692. result._markAsUpdated();
  5693. };
  5694. /**
  5695. * Stores an array into a matrix after having multiplied each component by a given factor
  5696. * @param array defines the source array
  5697. * @param offset defines the offset in the source array
  5698. * @param scale defines the scaling factor
  5699. * @param result defines the target matrix
  5700. */
  5701. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5702. for (var index = 0; index < 16; index++) {
  5703. result.m[index] = array[index + offset] * scale;
  5704. }
  5705. result._markAsUpdated();
  5706. };
  5707. /**
  5708. * Stores a list of values (16) inside a given matrix
  5709. * @param initialM11 defines 1st value of 1st row
  5710. * @param initialM12 defines 2nd value of 1st row
  5711. * @param initialM13 defines 3rd value of 1st row
  5712. * @param initialM14 defines 4th value of 1st row
  5713. * @param initialM21 defines 1st value of 2nd row
  5714. * @param initialM22 defines 2nd value of 2nd row
  5715. * @param initialM23 defines 3rd value of 2nd row
  5716. * @param initialM24 defines 4th value of 2nd row
  5717. * @param initialM31 defines 1st value of 3rd row
  5718. * @param initialM32 defines 2nd value of 3rd row
  5719. * @param initialM33 defines 3rd value of 3rd row
  5720. * @param initialM34 defines 4th value of 3rd row
  5721. * @param initialM41 defines 1st value of 4th row
  5722. * @param initialM42 defines 2nd value of 4th row
  5723. * @param initialM43 defines 3rd value of 4th row
  5724. * @param initialM44 defines 4th value of 4th row
  5725. * @param result defines the target matrix
  5726. */
  5727. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5728. result.m[0] = initialM11;
  5729. result.m[1] = initialM12;
  5730. result.m[2] = initialM13;
  5731. result.m[3] = initialM14;
  5732. result.m[4] = initialM21;
  5733. result.m[5] = initialM22;
  5734. result.m[6] = initialM23;
  5735. result.m[7] = initialM24;
  5736. result.m[8] = initialM31;
  5737. result.m[9] = initialM32;
  5738. result.m[10] = initialM33;
  5739. result.m[11] = initialM34;
  5740. result.m[12] = initialM41;
  5741. result.m[13] = initialM42;
  5742. result.m[14] = initialM43;
  5743. result.m[15] = initialM44;
  5744. result._markAsUpdated();
  5745. };
  5746. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5747. /**
  5748. * Gets an identity matrix that must not be updated
  5749. */
  5750. get: function () {
  5751. return Matrix._identityReadOnly;
  5752. },
  5753. enumerable: true,
  5754. configurable: true
  5755. });
  5756. /**
  5757. * Creates new matrix from a list of values (16)
  5758. * @param initialM11 defines 1st value of 1st row
  5759. * @param initialM12 defines 2nd value of 1st row
  5760. * @param initialM13 defines 3rd value of 1st row
  5761. * @param initialM14 defines 4th value of 1st row
  5762. * @param initialM21 defines 1st value of 2nd row
  5763. * @param initialM22 defines 2nd value of 2nd row
  5764. * @param initialM23 defines 3rd value of 2nd row
  5765. * @param initialM24 defines 4th value of 2nd row
  5766. * @param initialM31 defines 1st value of 3rd row
  5767. * @param initialM32 defines 2nd value of 3rd row
  5768. * @param initialM33 defines 3rd value of 3rd row
  5769. * @param initialM34 defines 4th value of 3rd row
  5770. * @param initialM41 defines 1st value of 4th row
  5771. * @param initialM42 defines 2nd value of 4th row
  5772. * @param initialM43 defines 3rd value of 4th row
  5773. * @param initialM44 defines 4th value of 4th row
  5774. * @returns the new matrix
  5775. */
  5776. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5777. var result = new Matrix();
  5778. result.m[0] = initialM11;
  5779. result.m[1] = initialM12;
  5780. result.m[2] = initialM13;
  5781. result.m[3] = initialM14;
  5782. result.m[4] = initialM21;
  5783. result.m[5] = initialM22;
  5784. result.m[6] = initialM23;
  5785. result.m[7] = initialM24;
  5786. result.m[8] = initialM31;
  5787. result.m[9] = initialM32;
  5788. result.m[10] = initialM33;
  5789. result.m[11] = initialM34;
  5790. result.m[12] = initialM41;
  5791. result.m[13] = initialM42;
  5792. result.m[14] = initialM43;
  5793. result.m[15] = initialM44;
  5794. return result;
  5795. };
  5796. /**
  5797. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5798. * @param scale defines the scale vector3
  5799. * @param rotation defines the rotation quaternion
  5800. * @param translation defines the translation vector3
  5801. * @returns a new matrix
  5802. */
  5803. Matrix.Compose = function (scale, rotation, translation) {
  5804. var result = Matrix.Identity();
  5805. Matrix.ComposeToRef(scale, rotation, translation, result);
  5806. return result;
  5807. };
  5808. /**
  5809. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5810. * @param scale defines the scale vector3
  5811. * @param rotation defines the rotation quaternion
  5812. * @param translation defines the translation vector3
  5813. * @param result defines the target matrix
  5814. */
  5815. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5816. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5817. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5818. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5819. result.setTranslation(translation);
  5820. };
  5821. /**
  5822. * Creates a new identity matrix
  5823. * @returns a new identity matrix
  5824. */
  5825. Matrix.Identity = function () {
  5826. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  5827. };
  5828. /**
  5829. * Creates a new identity matrix and stores the result in a given matrix
  5830. * @param result defines the target matrix
  5831. */
  5832. Matrix.IdentityToRef = function (result) {
  5833. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  5834. };
  5835. /**
  5836. * Creates a new zero matrix
  5837. * @returns a new zero matrix
  5838. */
  5839. Matrix.Zero = function () {
  5840. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  5841. };
  5842. /**
  5843. * Creates a new rotation matrix for "angle" radians around the X axis
  5844. * @param angle defines the angle (in radians) to use
  5845. * @return the new matrix
  5846. */
  5847. Matrix.RotationX = function (angle) {
  5848. var result = new Matrix();
  5849. Matrix.RotationXToRef(angle, result);
  5850. return result;
  5851. };
  5852. /**
  5853. * Creates a new matrix as the invert of a given matrix
  5854. * @param source defines the source matrix
  5855. * @returns the new matrix
  5856. */
  5857. Matrix.Invert = function (source) {
  5858. var result = new Matrix();
  5859. source.invertToRef(result);
  5860. return result;
  5861. };
  5862. /**
  5863. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5864. * @param angle defines the angle (in radians) to use
  5865. * @param result defines the target matrix
  5866. */
  5867. Matrix.RotationXToRef = function (angle, result) {
  5868. var s = Math.sin(angle);
  5869. var c = Math.cos(angle);
  5870. result.m[0] = 1.0;
  5871. result.m[15] = 1.0;
  5872. result.m[5] = c;
  5873. result.m[10] = c;
  5874. result.m[9] = -s;
  5875. result.m[6] = s;
  5876. result.m[1] = 0.0;
  5877. result.m[2] = 0.0;
  5878. result.m[3] = 0.0;
  5879. result.m[4] = 0.0;
  5880. result.m[7] = 0.0;
  5881. result.m[8] = 0.0;
  5882. result.m[11] = 0.0;
  5883. result.m[12] = 0.0;
  5884. result.m[13] = 0.0;
  5885. result.m[14] = 0.0;
  5886. result._markAsUpdated();
  5887. };
  5888. /**
  5889. * Creates a new rotation matrix for "angle" radians around the Y axis
  5890. * @param angle defines the angle (in radians) to use
  5891. * @return the new matrix
  5892. */
  5893. Matrix.RotationY = function (angle) {
  5894. var result = new Matrix();
  5895. Matrix.RotationYToRef(angle, result);
  5896. return result;
  5897. };
  5898. /**
  5899. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5900. * @param angle defines the angle (in radians) to use
  5901. * @param result defines the target matrix
  5902. */
  5903. Matrix.RotationYToRef = function (angle, result) {
  5904. var s = Math.sin(angle);
  5905. var c = Math.cos(angle);
  5906. result.m[5] = 1.0;
  5907. result.m[15] = 1.0;
  5908. result.m[0] = c;
  5909. result.m[2] = -s;
  5910. result.m[8] = s;
  5911. result.m[10] = c;
  5912. result.m[1] = 0.0;
  5913. result.m[3] = 0.0;
  5914. result.m[4] = 0.0;
  5915. result.m[6] = 0.0;
  5916. result.m[7] = 0.0;
  5917. result.m[9] = 0.0;
  5918. result.m[11] = 0.0;
  5919. result.m[12] = 0.0;
  5920. result.m[13] = 0.0;
  5921. result.m[14] = 0.0;
  5922. result._markAsUpdated();
  5923. };
  5924. /**
  5925. * Creates a new rotation matrix for "angle" radians around the Z axis
  5926. * @param angle defines the angle (in radians) to use
  5927. * @return the new matrix
  5928. */
  5929. Matrix.RotationZ = function (angle) {
  5930. var result = new Matrix();
  5931. Matrix.RotationZToRef(angle, result);
  5932. return result;
  5933. };
  5934. /**
  5935. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5936. * @param angle defines the angle (in radians) to use
  5937. * @param result defines the target matrix
  5938. */
  5939. Matrix.RotationZToRef = function (angle, result) {
  5940. var s = Math.sin(angle);
  5941. var c = Math.cos(angle);
  5942. result.m[10] = 1.0;
  5943. result.m[15] = 1.0;
  5944. result.m[0] = c;
  5945. result.m[1] = s;
  5946. result.m[4] = -s;
  5947. result.m[5] = c;
  5948. result.m[2] = 0.0;
  5949. result.m[3] = 0.0;
  5950. result.m[6] = 0.0;
  5951. result.m[7] = 0.0;
  5952. result.m[8] = 0.0;
  5953. result.m[9] = 0.0;
  5954. result.m[11] = 0.0;
  5955. result.m[12] = 0.0;
  5956. result.m[13] = 0.0;
  5957. result.m[14] = 0.0;
  5958. result._markAsUpdated();
  5959. };
  5960. /**
  5961. * Creates a new rotation matrix for "angle" radians around the given axis
  5962. * @param axis defines the axis to use
  5963. * @param angle defines the angle (in radians) to use
  5964. * @return the new matrix
  5965. */
  5966. Matrix.RotationAxis = function (axis, angle) {
  5967. var result = Matrix.Zero();
  5968. Matrix.RotationAxisToRef(axis, angle, result);
  5969. return result;
  5970. };
  5971. /**
  5972. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5973. * @param axis defines the axis to use
  5974. * @param angle defines the angle (in radians) to use
  5975. * @param result defines the target matrix
  5976. */
  5977. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5978. var s = Math.sin(-angle);
  5979. var c = Math.cos(-angle);
  5980. var c1 = 1 - c;
  5981. axis.normalize();
  5982. result.m[0] = (axis.x * axis.x) * c1 + c;
  5983. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5984. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5985. result.m[3] = 0.0;
  5986. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5987. result.m[5] = (axis.y * axis.y) * c1 + c;
  5988. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5989. result.m[7] = 0.0;
  5990. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5991. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5992. result.m[10] = (axis.z * axis.z) * c1 + c;
  5993. result.m[11] = 0.0;
  5994. result.m[15] = 1.0;
  5995. result._markAsUpdated();
  5996. };
  5997. /**
  5998. * Creates a rotation matrix
  5999. * @param yaw defines the yaw angle in radians (Y axis)
  6000. * @param pitch defines the pitch angle in radians (X axis)
  6001. * @param roll defines the roll angle in radians (X axis)
  6002. * @returns the new rotation matrix
  6003. */
  6004. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  6005. var result = new Matrix();
  6006. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6007. return result;
  6008. };
  6009. /**
  6010. * Creates a rotation matrix and stores it in a given matrix
  6011. * @param yaw defines the yaw angle in radians (Y axis)
  6012. * @param pitch defines the pitch angle in radians (X axis)
  6013. * @param roll defines the roll angle in radians (X axis)
  6014. * @param result defines the target matrix
  6015. */
  6016. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6017. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6018. this._tempQuaternion.toRotationMatrix(result);
  6019. };
  6020. /**
  6021. * Creates a scaling matrix
  6022. * @param x defines the scale factor on X axis
  6023. * @param y defines the scale factor on Y axis
  6024. * @param z defines the scale factor on Z axis
  6025. * @returns the new matrix
  6026. */
  6027. Matrix.Scaling = function (x, y, z) {
  6028. var result = Matrix.Zero();
  6029. Matrix.ScalingToRef(x, y, z, result);
  6030. return result;
  6031. };
  6032. /**
  6033. * Creates a scaling matrix and stores it in a given matrix
  6034. * @param x defines the scale factor on X axis
  6035. * @param y defines the scale factor on Y axis
  6036. * @param z defines the scale factor on Z axis
  6037. * @param result defines the target matrix
  6038. */
  6039. Matrix.ScalingToRef = function (x, y, z, result) {
  6040. result.m[0] = x;
  6041. result.m[1] = 0.0;
  6042. result.m[2] = 0.0;
  6043. result.m[3] = 0.0;
  6044. result.m[4] = 0.0;
  6045. result.m[5] = y;
  6046. result.m[6] = 0.0;
  6047. result.m[7] = 0.0;
  6048. result.m[8] = 0.0;
  6049. result.m[9] = 0.0;
  6050. result.m[10] = z;
  6051. result.m[11] = 0.0;
  6052. result.m[12] = 0.0;
  6053. result.m[13] = 0.0;
  6054. result.m[14] = 0.0;
  6055. result.m[15] = 1.0;
  6056. result._markAsUpdated();
  6057. };
  6058. /**
  6059. * Creates a translation matrix
  6060. * @param x defines the translation on X axis
  6061. * @param y defines the translation on Y axis
  6062. * @param z defines the translationon Z axis
  6063. * @returns the new matrix
  6064. */
  6065. Matrix.Translation = function (x, y, z) {
  6066. var result = Matrix.Identity();
  6067. Matrix.TranslationToRef(x, y, z, result);
  6068. return result;
  6069. };
  6070. /**
  6071. * Creates a translation matrix and stores it in a given matrix
  6072. * @param x defines the translation on X axis
  6073. * @param y defines the translation on Y axis
  6074. * @param z defines the translationon Z axis
  6075. * @param result defines the target matrix
  6076. */
  6077. Matrix.TranslationToRef = function (x, y, z, result) {
  6078. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  6079. };
  6080. /**
  6081. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6082. * @param startValue defines the start value
  6083. * @param endValue defines the end value
  6084. * @param gradient defines the gradient factor
  6085. * @returns the new matrix
  6086. */
  6087. Matrix.Lerp = function (startValue, endValue, gradient) {
  6088. var result = Matrix.Zero();
  6089. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6090. return result;
  6091. };
  6092. /**
  6093. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6094. * @param startValue defines the start value
  6095. * @param endValue defines the end value
  6096. * @param gradient defines the gradient factor
  6097. * @param result defines the Matrix object where to store data
  6098. */
  6099. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6100. for (var index = 0; index < 16; index++) {
  6101. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6102. }
  6103. result._markAsUpdated();
  6104. };
  6105. /**
  6106. * Builds a new matrix whose values are computed by:
  6107. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6108. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6109. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6110. * @param startValue defines the first matrix
  6111. * @param endValue defines the second matrix
  6112. * @param gradient defines the gradient between the two matrices
  6113. * @returns the new matrix
  6114. */
  6115. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6116. var result = Matrix.Zero();
  6117. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6118. return result;
  6119. };
  6120. /**
  6121. * Update a matrix to values which are computed by:
  6122. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6123. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6124. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6125. * @param startValue defines the first matrix
  6126. * @param endValue defines the second matrix
  6127. * @param gradient defines the gradient between the two matrices
  6128. * @param result defines the target matrix
  6129. */
  6130. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6131. var startScale = MathTmp.Vector3[0];
  6132. var startRotation = MathTmp.Quaternion[0];
  6133. var startTranslation = MathTmp.Vector3[1];
  6134. startValue.decompose(startScale, startRotation, startTranslation);
  6135. var endScale = MathTmp.Vector3[2];
  6136. var endRotation = MathTmp.Quaternion[1];
  6137. var endTranslation = MathTmp.Vector3[3];
  6138. endValue.decompose(endScale, endRotation, endTranslation);
  6139. var resultScale = MathTmp.Vector3[4];
  6140. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6141. var resultRotation = MathTmp.Quaternion[2];
  6142. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6143. var resultTranslation = MathTmp.Vector3[5];
  6144. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6145. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6146. };
  6147. /**
  6148. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6149. * This function works in left handed mode
  6150. * @param eye defines the final position of the entity
  6151. * @param target defines where the entity should look at
  6152. * @param up defines the up vector for the entity
  6153. * @returns the new matrix
  6154. */
  6155. Matrix.LookAtLH = function (eye, target, up) {
  6156. var result = Matrix.Zero();
  6157. Matrix.LookAtLHToRef(eye, target, up, result);
  6158. return result;
  6159. };
  6160. /**
  6161. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6162. * This function works in left handed mode
  6163. * @param eye defines the final position of the entity
  6164. * @param target defines where the entity should look at
  6165. * @param up defines the up vector for the entity
  6166. * @param result defines the target matrix
  6167. */
  6168. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6169. // Z axis
  6170. target.subtractToRef(eye, this._zAxis);
  6171. this._zAxis.normalize();
  6172. // X axis
  6173. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6174. if (this._xAxis.lengthSquared() === 0) {
  6175. this._xAxis.x = 1.0;
  6176. }
  6177. else {
  6178. this._xAxis.normalize();
  6179. }
  6180. // Y axis
  6181. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6182. this._yAxis.normalize();
  6183. // Eye angles
  6184. var ex = -Vector3.Dot(this._xAxis, eye);
  6185. var ey = -Vector3.Dot(this._yAxis, eye);
  6186. var ez = -Vector3.Dot(this._zAxis, eye);
  6187. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  6188. };
  6189. /**
  6190. * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
  6191. * This function works in right handed mode
  6192. * @param eye defines the final position of the entity
  6193. * @param target defines where the entity should look at
  6194. * @param up defines the up vector for the entity
  6195. * @returns the new matrix
  6196. */
  6197. Matrix.LookAtRH = function (eye, target, up) {
  6198. var result = Matrix.Zero();
  6199. Matrix.LookAtRHToRef(eye, target, up, result);
  6200. return result;
  6201. };
  6202. /**
  6203. * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
  6204. * This function works in right handed mode
  6205. * @param eye defines the final position of the entity
  6206. * @param target defines where the entity should look at
  6207. * @param up defines the up vector for the entity
  6208. * @param result defines the target matrix
  6209. */
  6210. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6211. // Z axis
  6212. eye.subtractToRef(target, this._zAxis);
  6213. this._zAxis.normalize();
  6214. // X axis
  6215. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6216. if (this._xAxis.lengthSquared() === 0) {
  6217. this._xAxis.x = 1.0;
  6218. }
  6219. else {
  6220. this._xAxis.normalize();
  6221. }
  6222. // Y axis
  6223. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6224. this._yAxis.normalize();
  6225. // Eye angles
  6226. var ex = -Vector3.Dot(this._xAxis, eye);
  6227. var ey = -Vector3.Dot(this._yAxis, eye);
  6228. var ez = -Vector3.Dot(this._zAxis, eye);
  6229. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  6230. };
  6231. /**
  6232. * Create a left-handed orthographic projection matrix
  6233. * @param width defines the viewport width
  6234. * @param height defines the viewport height
  6235. * @param znear defines the near clip plane
  6236. * @param zfar defines the far clip plane
  6237. * @returns a new matrix as a left-handed orthographic projection matrix
  6238. */
  6239. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6240. var matrix = Matrix.Zero();
  6241. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6242. return matrix;
  6243. };
  6244. /**
  6245. * Store a left-handed orthographic projection to a given matrix
  6246. * @param width defines the viewport width
  6247. * @param height defines the viewport height
  6248. * @param znear defines the near clip plane
  6249. * @param zfar defines the far clip plane
  6250. * @param result defines the target matrix
  6251. */
  6252. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6253. var n = znear;
  6254. var f = zfar;
  6255. var a = 2.0 / width;
  6256. var b = 2.0 / height;
  6257. var c = 2.0 / (f - n);
  6258. var d = -(f + n) / (f - n);
  6259. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  6260. };
  6261. /**
  6262. * Create a left-handed orthographic projection matrix
  6263. * @param left defines the viewport left coordinate
  6264. * @param right defines the viewport right coordinate
  6265. * @param bottom defines the viewport bottom coordinate
  6266. * @param top defines the viewport top coordinate
  6267. * @param znear defines the near clip plane
  6268. * @param zfar defines the far clip plane
  6269. * @returns a new matrix as a left-handed orthographic projection matrix
  6270. */
  6271. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6272. var matrix = Matrix.Zero();
  6273. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6274. return matrix;
  6275. };
  6276. /**
  6277. * Stores a left-handed orthographic projection into a given matrix
  6278. * @param left defines the viewport left coordinate
  6279. * @param right defines the viewport right coordinate
  6280. * @param bottom defines the viewport bottom coordinate
  6281. * @param top defines the viewport top coordinate
  6282. * @param znear defines the near clip plane
  6283. * @param zfar defines the far clip plane
  6284. * @param result defines the target matrix
  6285. */
  6286. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6287. var n = znear;
  6288. var f = zfar;
  6289. var a = 2.0 / (right - left);
  6290. var b = 2.0 / (top - bottom);
  6291. var c = 2.0 / (f - n);
  6292. var d = -(f + n) / (f - n);
  6293. var i0 = (left + right) / (left - right);
  6294. var i1 = (top + bottom) / (bottom - top);
  6295. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  6296. };
  6297. /**
  6298. * Creates a right-handed orthographic projection matrix
  6299. * @param left defines the viewport left coordinate
  6300. * @param right defines the viewport right coordinate
  6301. * @param bottom defines the viewport bottom coordinate
  6302. * @param top defines the viewport top coordinate
  6303. * @param znear defines the near clip plane
  6304. * @param zfar defines the far clip plane
  6305. * @returns a new matrix as a right-handed orthographic projection matrix
  6306. */
  6307. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6308. var matrix = Matrix.Zero();
  6309. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6310. return matrix;
  6311. };
  6312. /**
  6313. * Stores a right-handed orthographic projection into a given matrix
  6314. * @param left defines the viewport left coordinate
  6315. * @param right defines the viewport right coordinate
  6316. * @param bottom defines the viewport bottom coordinate
  6317. * @param top defines the viewport top coordinate
  6318. * @param znear defines the near clip plane
  6319. * @param zfar defines the far clip plane
  6320. * @param result defines the target matrix
  6321. */
  6322. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6323. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6324. result.m[10] *= -1.0;
  6325. };
  6326. /**
  6327. * Creates a left-handed perspective projection matrix
  6328. * @param width defines the viewport width
  6329. * @param height defines the viewport height
  6330. * @param znear defines the near clip plane
  6331. * @param zfar defines the far clip plane
  6332. * @returns a new matrix as a left-handed perspective projection matrix
  6333. */
  6334. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6335. var matrix = Matrix.Zero();
  6336. var n = znear;
  6337. var f = zfar;
  6338. var a = 2.0 * n / width;
  6339. var b = 2.0 * n / height;
  6340. var c = (f + n) / (f - n);
  6341. var d = -2.0 * f * n / (f - n);
  6342. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  6343. return matrix;
  6344. };
  6345. /**
  6346. * Creates a left-handed perspective projection matrix
  6347. * @param fov defines the horizontal field of view
  6348. * @param aspect defines the aspect ratio
  6349. * @param znear defines the near clip plane
  6350. * @param zfar defines the far clip plane
  6351. * @returns a new matrix as a left-handed perspective projection matrix
  6352. */
  6353. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6354. var matrix = Matrix.Zero();
  6355. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6356. return matrix;
  6357. };
  6358. /**
  6359. * Stores a left-handed perspective projection into a given matrix
  6360. * @param fov defines the horizontal field of view
  6361. * @param aspect defines the aspect ratio
  6362. * @param znear defines the near clip plane
  6363. * @param zfar defines the far clip plane
  6364. * @param result defines the target matrix
  6365. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6366. */
  6367. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6368. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6369. var n = znear;
  6370. var f = zfar;
  6371. var t = 1.0 / (Math.tan(fov * 0.5));
  6372. var a = isVerticalFovFixed ? (t / aspect) : t;
  6373. var b = isVerticalFovFixed ? t : (t * aspect);
  6374. var c = (f + n) / (f - n);
  6375. var d = -2.0 * f * n / (f - n);
  6376. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  6377. };
  6378. /**
  6379. * Creates a right-handed perspective projection matrix
  6380. * @param fov defines the horizontal field of view
  6381. * @param aspect defines the aspect ratio
  6382. * @param znear defines the near clip plane
  6383. * @param zfar defines the far clip plane
  6384. * @returns a new matrix as a right-handed perspective projection matrix
  6385. */
  6386. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6387. var matrix = Matrix.Zero();
  6388. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6389. return matrix;
  6390. };
  6391. /**
  6392. * Stores a right-handed perspective projection into a given matrix
  6393. * @param fov defines the horizontal field of view
  6394. * @param aspect defines the aspect ratio
  6395. * @param znear defines the near clip plane
  6396. * @param zfar defines the far clip plane
  6397. * @param result defines the target matrix
  6398. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6399. */
  6400. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6401. //alternatively this could be expressed as:
  6402. // m = PerspectiveFovLHToRef
  6403. // m[10] *= -1.0;
  6404. // m[11] *= -1.0;
  6405. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6406. var n = znear;
  6407. var f = zfar;
  6408. var t = 1.0 / (Math.tan(fov * 0.5));
  6409. var a = isVerticalFovFixed ? (t / aspect) : t;
  6410. var b = isVerticalFovFixed ? t : (t * aspect);
  6411. var c = -(f + n) / (f - n);
  6412. var d = -2 * f * n / (f - n);
  6413. Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  6414. };
  6415. /**
  6416. * Stores a perspective projection for WebVR info a given matrix
  6417. * @param fov defines the field of view
  6418. * @param znear defines the near clip plane
  6419. * @param zfar defines the far clip plane
  6420. * @param result defines the target matrix
  6421. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6422. */
  6423. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6424. if (rightHanded === void 0) { rightHanded = false; }
  6425. var rightHandedFactor = rightHanded ? -1 : 1;
  6426. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6427. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6428. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6429. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6430. var xScale = 2.0 / (leftTan + rightTan);
  6431. var yScale = 2.0 / (upTan + downTan);
  6432. result.m[0] = xScale;
  6433. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6434. result.m[5] = yScale;
  6435. result.m[6] = result.m[7] = 0.0;
  6436. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6437. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6438. result.m[10] = -zfar / (znear - zfar);
  6439. result.m[11] = 1.0 * rightHandedFactor;
  6440. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6441. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6442. result._markAsUpdated();
  6443. };
  6444. /**
  6445. * Computes a complete transformation matrix
  6446. * @param viewport defines the viewport to use
  6447. * @param world defines the world matrix
  6448. * @param view defines the view matrix
  6449. * @param projection defines the projection matrix
  6450. * @param zmin defines the near clip plane
  6451. * @param zmax defines the far clip plane
  6452. * @returns the transformation matrix
  6453. */
  6454. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6455. var cw = viewport.width;
  6456. var ch = viewport.height;
  6457. var cx = viewport.x;
  6458. var cy = viewport.y;
  6459. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  6460. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6461. };
  6462. /**
  6463. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6464. * @param matrix defines the matrix to use
  6465. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6466. */
  6467. Matrix.GetAsMatrix2x2 = function (matrix) {
  6468. return new Float32Array([
  6469. matrix.m[0], matrix.m[1],
  6470. matrix.m[4], matrix.m[5]
  6471. ]);
  6472. };
  6473. /**
  6474. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6475. * @param matrix defines the matrix to use
  6476. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6477. */
  6478. Matrix.GetAsMatrix3x3 = function (matrix) {
  6479. return new Float32Array([
  6480. matrix.m[0], matrix.m[1], matrix.m[2],
  6481. matrix.m[4], matrix.m[5], matrix.m[6],
  6482. matrix.m[8], matrix.m[9], matrix.m[10]
  6483. ]);
  6484. };
  6485. /**
  6486. * Compute the transpose of a given matrix
  6487. * @param matrix defines the matrix to transpose
  6488. * @returns the new matrix
  6489. */
  6490. Matrix.Transpose = function (matrix) {
  6491. var result = new Matrix();
  6492. Matrix.TransposeToRef(matrix, result);
  6493. return result;
  6494. };
  6495. /**
  6496. * Compute the transpose of a matrix and store it in a target matrix
  6497. * @param matrix defines the matrix to transpose
  6498. * @param result defines the target matrix
  6499. */
  6500. Matrix.TransposeToRef = function (matrix, result) {
  6501. result.m[0] = matrix.m[0];
  6502. result.m[1] = matrix.m[4];
  6503. result.m[2] = matrix.m[8];
  6504. result.m[3] = matrix.m[12];
  6505. result.m[4] = matrix.m[1];
  6506. result.m[5] = matrix.m[5];
  6507. result.m[6] = matrix.m[9];
  6508. result.m[7] = matrix.m[13];
  6509. result.m[8] = matrix.m[2];
  6510. result.m[9] = matrix.m[6];
  6511. result.m[10] = matrix.m[10];
  6512. result.m[11] = matrix.m[14];
  6513. result.m[12] = matrix.m[3];
  6514. result.m[13] = matrix.m[7];
  6515. result.m[14] = matrix.m[11];
  6516. result.m[15] = matrix.m[15];
  6517. };
  6518. /**
  6519. * Computes a reflection matrix from a plane
  6520. * @param plane defines the reflection plane
  6521. * @returns a new matrix
  6522. */
  6523. Matrix.Reflection = function (plane) {
  6524. var matrix = new Matrix();
  6525. Matrix.ReflectionToRef(plane, matrix);
  6526. return matrix;
  6527. };
  6528. /**
  6529. * Computes a reflection matrix from a plane
  6530. * @param plane defines the reflection plane
  6531. * @param result defines the target matrix
  6532. */
  6533. Matrix.ReflectionToRef = function (plane, result) {
  6534. plane.normalize();
  6535. var x = plane.normal.x;
  6536. var y = plane.normal.y;
  6537. var z = plane.normal.z;
  6538. var temp = -2 * x;
  6539. var temp2 = -2 * y;
  6540. var temp3 = -2 * z;
  6541. result.m[0] = (temp * x) + 1;
  6542. result.m[1] = temp2 * x;
  6543. result.m[2] = temp3 * x;
  6544. result.m[3] = 0.0;
  6545. result.m[4] = temp * y;
  6546. result.m[5] = (temp2 * y) + 1;
  6547. result.m[6] = temp3 * y;
  6548. result.m[7] = 0.0;
  6549. result.m[8] = temp * z;
  6550. result.m[9] = temp2 * z;
  6551. result.m[10] = (temp3 * z) + 1;
  6552. result.m[11] = 0.0;
  6553. result.m[12] = temp * plane.d;
  6554. result.m[13] = temp2 * plane.d;
  6555. result.m[14] = temp3 * plane.d;
  6556. result.m[15] = 1.0;
  6557. result._markAsUpdated();
  6558. };
  6559. /**
  6560. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6561. * @param xaxis defines the value of the 1st axis
  6562. * @param yaxis defines the value of the 2nd axis
  6563. * @param zaxis defines the value of the 3rd axis
  6564. * @param result defines the target matrix
  6565. */
  6566. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6567. result.m[0] = xaxis.x;
  6568. result.m[1] = xaxis.y;
  6569. result.m[2] = xaxis.z;
  6570. result.m[3] = 0.0;
  6571. result.m[4] = yaxis.x;
  6572. result.m[5] = yaxis.y;
  6573. result.m[6] = yaxis.z;
  6574. result.m[7] = 0.0;
  6575. result.m[8] = zaxis.x;
  6576. result.m[9] = zaxis.y;
  6577. result.m[10] = zaxis.z;
  6578. result.m[11] = 0.0;
  6579. result.m[12] = 0.0;
  6580. result.m[13] = 0.0;
  6581. result.m[14] = 0.0;
  6582. result.m[15] = 1.0;
  6583. result._markAsUpdated();
  6584. };
  6585. /**
  6586. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6587. * @param quat defines the quaternion to use
  6588. * @param result defines the target matrix
  6589. */
  6590. Matrix.FromQuaternionToRef = function (quat, result) {
  6591. var xx = quat.x * quat.x;
  6592. var yy = quat.y * quat.y;
  6593. var zz = quat.z * quat.z;
  6594. var xy = quat.x * quat.y;
  6595. var zw = quat.z * quat.w;
  6596. var zx = quat.z * quat.x;
  6597. var yw = quat.y * quat.w;
  6598. var yz = quat.y * quat.z;
  6599. var xw = quat.x * quat.w;
  6600. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6601. result.m[1] = 2.0 * (xy + zw);
  6602. result.m[2] = 2.0 * (zx - yw);
  6603. result.m[3] = 0.0;
  6604. result.m[4] = 2.0 * (xy - zw);
  6605. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6606. result.m[6] = 2.0 * (yz + xw);
  6607. result.m[7] = 0.0;
  6608. result.m[8] = 2.0 * (zx + yw);
  6609. result.m[9] = 2.0 * (yz - xw);
  6610. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6611. result.m[11] = 0.0;
  6612. result.m[12] = 0.0;
  6613. result.m[13] = 0.0;
  6614. result.m[14] = 0.0;
  6615. result.m[15] = 1.0;
  6616. result._markAsUpdated();
  6617. };
  6618. Matrix._tempQuaternion = new Quaternion();
  6619. Matrix._xAxis = Vector3.Zero();
  6620. Matrix._yAxis = Vector3.Zero();
  6621. Matrix._zAxis = Vector3.Zero();
  6622. Matrix._updateFlagSeed = 0;
  6623. Matrix._identityReadOnly = Matrix.Identity();
  6624. return Matrix;
  6625. }());
  6626. BABYLON.Matrix = Matrix;
  6627. var Plane = /** @class */ (function () {
  6628. /**
  6629. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6630. */
  6631. function Plane(a, b, c, d) {
  6632. this.normal = new Vector3(a, b, c);
  6633. this.d = d;
  6634. }
  6635. /**
  6636. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6637. */
  6638. Plane.prototype.asArray = function () {
  6639. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6640. };
  6641. // Methods
  6642. /**
  6643. * Returns a new plane copied from the current Plane.
  6644. */
  6645. Plane.prototype.clone = function () {
  6646. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6647. };
  6648. /**
  6649. * Returns the string "Plane".
  6650. */
  6651. Plane.prototype.getClassName = function () {
  6652. return "Plane";
  6653. };
  6654. /**
  6655. * Returns the Plane hash code.
  6656. */
  6657. Plane.prototype.getHashCode = function () {
  6658. var hash = this.normal.getHashCode();
  6659. hash = (hash * 397) ^ (this.d || 0);
  6660. return hash;
  6661. };
  6662. /**
  6663. * Normalize the current Plane in place.
  6664. * Returns the updated Plane.
  6665. */
  6666. Plane.prototype.normalize = function () {
  6667. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6668. var magnitude = 0.0;
  6669. if (norm !== 0) {
  6670. magnitude = 1.0 / norm;
  6671. }
  6672. this.normal.x *= magnitude;
  6673. this.normal.y *= magnitude;
  6674. this.normal.z *= magnitude;
  6675. this.d *= magnitude;
  6676. return this;
  6677. };
  6678. /**
  6679. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6680. */
  6681. Plane.prototype.transform = function (transformation) {
  6682. var transposedMatrix = Matrix.Transpose(transformation);
  6683. var x = this.normal.x;
  6684. var y = this.normal.y;
  6685. var z = this.normal.z;
  6686. var d = this.d;
  6687. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6688. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6689. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6690. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6691. return new Plane(normalX, normalY, normalZ, finalD);
  6692. };
  6693. /**
  6694. * Returns the dot product (float) of the point coordinates and the plane normal.
  6695. */
  6696. Plane.prototype.dotCoordinate = function (point) {
  6697. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6698. };
  6699. /**
  6700. * Updates the current Plane from the plane defined by the three given points.
  6701. * Returns the updated Plane.
  6702. */
  6703. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6704. var x1 = point2.x - point1.x;
  6705. var y1 = point2.y - point1.y;
  6706. var z1 = point2.z - point1.z;
  6707. var x2 = point3.x - point1.x;
  6708. var y2 = point3.y - point1.y;
  6709. var z2 = point3.z - point1.z;
  6710. var yz = (y1 * z2) - (z1 * y2);
  6711. var xz = (z1 * x2) - (x1 * z2);
  6712. var xy = (x1 * y2) - (y1 * x2);
  6713. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6714. var invPyth;
  6715. if (pyth !== 0) {
  6716. invPyth = 1.0 / pyth;
  6717. }
  6718. else {
  6719. invPyth = 0.0;
  6720. }
  6721. this.normal.x = yz * invPyth;
  6722. this.normal.y = xz * invPyth;
  6723. this.normal.z = xy * invPyth;
  6724. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6725. return this;
  6726. };
  6727. /**
  6728. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6729. */
  6730. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6731. var dot = Vector3.Dot(this.normal, direction);
  6732. return (dot <= epsilon);
  6733. };
  6734. /**
  6735. * Returns the signed distance (float) from the given point to the Plane.
  6736. */
  6737. Plane.prototype.signedDistanceTo = function (point) {
  6738. return Vector3.Dot(point, this.normal) + this.d;
  6739. };
  6740. // Statics
  6741. /**
  6742. * Returns a new Plane from the given array.
  6743. */
  6744. Plane.FromArray = function (array) {
  6745. return new Plane(array[0], array[1], array[2], array[3]);
  6746. };
  6747. /**
  6748. * Returns a new Plane defined by the three given points.
  6749. */
  6750. Plane.FromPoints = function (point1, point2, point3) {
  6751. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6752. result.copyFromPoints(point1, point2, point3);
  6753. return result;
  6754. };
  6755. /**
  6756. * Returns a new Plane the normal vector to this plane at the given origin point.
  6757. * Note : the vector "normal" is updated because normalized.
  6758. */
  6759. Plane.FromPositionAndNormal = function (origin, normal) {
  6760. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6761. normal.normalize();
  6762. result.normal = normal;
  6763. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6764. return result;
  6765. };
  6766. /**
  6767. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6768. */
  6769. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6770. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6771. return Vector3.Dot(point, normal) + d;
  6772. };
  6773. return Plane;
  6774. }());
  6775. BABYLON.Plane = Plane;
  6776. var Viewport = /** @class */ (function () {
  6777. /**
  6778. * Creates a Viewport object located at (x, y) and sized (width, height).
  6779. */
  6780. function Viewport(x, y, width, height) {
  6781. this.x = x;
  6782. this.y = y;
  6783. this.width = width;
  6784. this.height = height;
  6785. }
  6786. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6787. if (renderWidthOrEngine.getRenderWidth) {
  6788. var engine = renderWidthOrEngine;
  6789. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6790. }
  6791. var renderWidth = renderWidthOrEngine;
  6792. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6793. };
  6794. /**
  6795. * Returns a new Viewport copied from the current one.
  6796. */
  6797. Viewport.prototype.clone = function () {
  6798. return new Viewport(this.x, this.y, this.width, this.height);
  6799. };
  6800. return Viewport;
  6801. }());
  6802. BABYLON.Viewport = Viewport;
  6803. var Frustum = /** @class */ (function () {
  6804. function Frustum() {
  6805. }
  6806. /**
  6807. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6808. */
  6809. Frustum.GetPlanes = function (transform) {
  6810. var frustumPlanes = [];
  6811. for (var index = 0; index < 6; index++) {
  6812. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6813. }
  6814. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6815. return frustumPlanes;
  6816. };
  6817. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6818. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6819. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6820. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6821. frustumPlane.d = transform.m[15] + transform.m[14];
  6822. frustumPlane.normalize();
  6823. };
  6824. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6825. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6826. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6827. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6828. frustumPlane.d = transform.m[15] - transform.m[14];
  6829. frustumPlane.normalize();
  6830. };
  6831. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6832. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6833. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6834. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6835. frustumPlane.d = transform.m[15] + transform.m[12];
  6836. frustumPlane.normalize();
  6837. };
  6838. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6839. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6840. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6841. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6842. frustumPlane.d = transform.m[15] - transform.m[12];
  6843. frustumPlane.normalize();
  6844. };
  6845. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6846. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6847. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6848. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6849. frustumPlane.d = transform.m[15] - transform.m[13];
  6850. frustumPlane.normalize();
  6851. };
  6852. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6853. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6854. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6855. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6856. frustumPlane.d = transform.m[15] + transform.m[13];
  6857. frustumPlane.normalize();
  6858. };
  6859. /**
  6860. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6861. */
  6862. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6863. // Near
  6864. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6865. // Far
  6866. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6867. // Left
  6868. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6869. // Right
  6870. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6871. // Top
  6872. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6873. // Bottom
  6874. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6875. };
  6876. return Frustum;
  6877. }());
  6878. BABYLON.Frustum = Frustum;
  6879. /** Defines supported spaces */
  6880. var Space;
  6881. (function (Space) {
  6882. /** Local (object) space */
  6883. Space[Space["LOCAL"] = 0] = "LOCAL";
  6884. /** World space */
  6885. Space[Space["WORLD"] = 1] = "WORLD";
  6886. /** Bone space */
  6887. Space[Space["BONE"] = 2] = "BONE";
  6888. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6889. /** Defines the 3 main axes */
  6890. var Axis = /** @class */ (function () {
  6891. function Axis() {
  6892. }
  6893. /** X axis */
  6894. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6895. /** Y axis */
  6896. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6897. /** Z axis */
  6898. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6899. return Axis;
  6900. }());
  6901. BABYLON.Axis = Axis;
  6902. ;
  6903. var BezierCurve = /** @class */ (function () {
  6904. function BezierCurve() {
  6905. }
  6906. /**
  6907. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6908. */
  6909. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6910. // Extract X (which is equal to time here)
  6911. var f0 = 1 - 3 * x2 + 3 * x1;
  6912. var f1 = 3 * x2 - 6 * x1;
  6913. var f2 = 3 * x1;
  6914. var refinedT = t;
  6915. for (var i = 0; i < 5; i++) {
  6916. var refinedT2 = refinedT * refinedT;
  6917. var refinedT3 = refinedT2 * refinedT;
  6918. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6919. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6920. refinedT -= (x - t) * slope;
  6921. refinedT = Math.min(1, Math.max(0, refinedT));
  6922. }
  6923. // Resolve cubic bezier for the given x
  6924. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6925. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6926. Math.pow(refinedT, 3);
  6927. };
  6928. return BezierCurve;
  6929. }());
  6930. BABYLON.BezierCurve = BezierCurve;
  6931. /**
  6932. * Defines potential orientation for back face culling
  6933. */
  6934. var Orientation;
  6935. (function (Orientation) {
  6936. /**
  6937. * Clockwise
  6938. */
  6939. Orientation[Orientation["CW"] = 0] = "CW";
  6940. /** Counter clockwise */
  6941. Orientation[Orientation["CCW"] = 1] = "CCW";
  6942. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6943. /**
  6944. * Defines angle representation
  6945. */
  6946. var Angle = /** @class */ (function () {
  6947. /**
  6948. * Creates an Angle object of "radians" radians (float).
  6949. */
  6950. function Angle(radians) {
  6951. this._radians = radians;
  6952. if (this._radians < 0.0)
  6953. this._radians += (2.0 * Math.PI);
  6954. }
  6955. /**
  6956. * Get value in degrees
  6957. * @returns the Angle value in degrees (float)
  6958. */
  6959. Angle.prototype.degrees = function () {
  6960. return this._radians * 180.0 / Math.PI;
  6961. };
  6962. /**
  6963. * Get value in radians
  6964. * @returns the Angle value in radians (float)
  6965. */
  6966. Angle.prototype.radians = function () {
  6967. return this._radians;
  6968. };
  6969. /**
  6970. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6971. * @param a defines first vector
  6972. * @param b defines second vector
  6973. * @returns a new Angle
  6974. */
  6975. Angle.BetweenTwoPoints = function (a, b) {
  6976. var delta = b.subtract(a);
  6977. var theta = Math.atan2(delta.y, delta.x);
  6978. return new Angle(theta);
  6979. };
  6980. /**
  6981. * Gets a new Angle object from the given float in radians
  6982. * @param radians defines the angle value in radians
  6983. * @returns a new Angle
  6984. */
  6985. Angle.FromRadians = function (radians) {
  6986. return new Angle(radians);
  6987. };
  6988. /**
  6989. * Gets a new Angle object from the given float in degrees
  6990. * @param degrees defines the angle value in degrees
  6991. * @returns a new Angle
  6992. */
  6993. Angle.FromDegrees = function (degrees) {
  6994. return new Angle(degrees * Math.PI / 180.0);
  6995. };
  6996. return Angle;
  6997. }());
  6998. BABYLON.Angle = Angle;
  6999. var Arc2 = /** @class */ (function () {
  7000. /**
  7001. * Creates an Arc object from the three given points : start, middle and end.
  7002. */
  7003. function Arc2(startPoint, midPoint, endPoint) {
  7004. this.startPoint = startPoint;
  7005. this.midPoint = midPoint;
  7006. this.endPoint = endPoint;
  7007. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7008. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7009. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7010. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7011. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  7012. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7013. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7014. var a1 = this.startAngle.degrees();
  7015. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7016. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7017. // angles correction
  7018. if (a2 - a1 > +180.0)
  7019. a2 -= 360.0;
  7020. if (a2 - a1 < -180.0)
  7021. a2 += 360.0;
  7022. if (a3 - a2 > +180.0)
  7023. a3 -= 360.0;
  7024. if (a3 - a2 < -180.0)
  7025. a3 += 360.0;
  7026. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7027. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7028. }
  7029. return Arc2;
  7030. }());
  7031. BABYLON.Arc2 = Arc2;
  7032. var Path2 = /** @class */ (function () {
  7033. /**
  7034. * Creates a Path2 object from the starting 2D coordinates x and y.
  7035. */
  7036. function Path2(x, y) {
  7037. this._points = new Array();
  7038. this._length = 0.0;
  7039. this.closed = false;
  7040. this._points.push(new Vector2(x, y));
  7041. }
  7042. /**
  7043. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7044. * Returns the updated Path2.
  7045. */
  7046. Path2.prototype.addLineTo = function (x, y) {
  7047. if (this.closed) {
  7048. return this;
  7049. }
  7050. var newPoint = new Vector2(x, y);
  7051. var previousPoint = this._points[this._points.length - 1];
  7052. this._points.push(newPoint);
  7053. this._length += newPoint.subtract(previousPoint).length();
  7054. return this;
  7055. };
  7056. /**
  7057. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  7058. * Returns the updated Path2.
  7059. */
  7060. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7061. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7062. if (this.closed) {
  7063. return this;
  7064. }
  7065. var startPoint = this._points[this._points.length - 1];
  7066. var midPoint = new Vector2(midX, midY);
  7067. var endPoint = new Vector2(endX, endY);
  7068. var arc = new Arc2(startPoint, midPoint, endPoint);
  7069. var increment = arc.angle.radians() / numberOfSegments;
  7070. if (arc.orientation === Orientation.CW)
  7071. increment *= -1;
  7072. var currentAngle = arc.startAngle.radians() + increment;
  7073. for (var i = 0; i < numberOfSegments; i++) {
  7074. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7075. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7076. this.addLineTo(x, y);
  7077. currentAngle += increment;
  7078. }
  7079. return this;
  7080. };
  7081. /**
  7082. * Closes the Path2.
  7083. * Returns the Path2.
  7084. */
  7085. Path2.prototype.close = function () {
  7086. this.closed = true;
  7087. return this;
  7088. };
  7089. /**
  7090. * Returns the Path2 total length (float).
  7091. */
  7092. Path2.prototype.length = function () {
  7093. var result = this._length;
  7094. if (!this.closed) {
  7095. var lastPoint = this._points[this._points.length - 1];
  7096. var firstPoint = this._points[0];
  7097. result += (firstPoint.subtract(lastPoint).length());
  7098. }
  7099. return result;
  7100. };
  7101. /**
  7102. * Returns the Path2 internal array of points.
  7103. */
  7104. Path2.prototype.getPoints = function () {
  7105. return this._points;
  7106. };
  7107. /**
  7108. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7109. */
  7110. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7111. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7112. return Vector2.Zero();
  7113. }
  7114. var lengthPosition = normalizedLengthPosition * this.length();
  7115. var previousOffset = 0;
  7116. for (var i = 0; i < this._points.length; i++) {
  7117. var j = (i + 1) % this._points.length;
  7118. var a = this._points[i];
  7119. var b = this._points[j];
  7120. var bToA = b.subtract(a);
  7121. var nextOffset = (bToA.length() + previousOffset);
  7122. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7123. var dir = bToA.normalize();
  7124. var localOffset = lengthPosition - previousOffset;
  7125. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7126. }
  7127. previousOffset = nextOffset;
  7128. }
  7129. return Vector2.Zero();
  7130. };
  7131. /**
  7132. * Returns a new Path2 starting at the coordinates (x, y).
  7133. */
  7134. Path2.StartingAt = function (x, y) {
  7135. return new Path2(x, y);
  7136. };
  7137. return Path2;
  7138. }());
  7139. BABYLON.Path2 = Path2;
  7140. var Path3D = /** @class */ (function () {
  7141. /**
  7142. * new Path3D(path, normal, raw)
  7143. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7144. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7145. * path : an array of Vector3, the curve axis of the Path3D
  7146. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7147. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7148. */
  7149. function Path3D(path, firstNormal, raw) {
  7150. if (firstNormal === void 0) { firstNormal = null; }
  7151. this.path = path;
  7152. this._curve = new Array();
  7153. this._distances = new Array();
  7154. this._tangents = new Array();
  7155. this._normals = new Array();
  7156. this._binormals = new Array();
  7157. for (var p = 0; p < path.length; p++) {
  7158. this._curve[p] = path[p].clone(); // hard copy
  7159. }
  7160. this._raw = raw || false;
  7161. this._compute(firstNormal);
  7162. }
  7163. /**
  7164. * Returns the Path3D array of successive Vector3 designing its curve.
  7165. */
  7166. Path3D.prototype.getCurve = function () {
  7167. return this._curve;
  7168. };
  7169. /**
  7170. * Returns an array populated with tangent vectors on each Path3D curve point.
  7171. */
  7172. Path3D.prototype.getTangents = function () {
  7173. return this._tangents;
  7174. };
  7175. /**
  7176. * Returns an array populated with normal vectors on each Path3D curve point.
  7177. */
  7178. Path3D.prototype.getNormals = function () {
  7179. return this._normals;
  7180. };
  7181. /**
  7182. * Returns an array populated with binormal vectors on each Path3D curve point.
  7183. */
  7184. Path3D.prototype.getBinormals = function () {
  7185. return this._binormals;
  7186. };
  7187. /**
  7188. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7189. */
  7190. Path3D.prototype.getDistances = function () {
  7191. return this._distances;
  7192. };
  7193. /**
  7194. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7195. * Returns the same object updated.
  7196. */
  7197. Path3D.prototype.update = function (path, firstNormal) {
  7198. if (firstNormal === void 0) { firstNormal = null; }
  7199. for (var p = 0; p < path.length; p++) {
  7200. this._curve[p].x = path[p].x;
  7201. this._curve[p].y = path[p].y;
  7202. this._curve[p].z = path[p].z;
  7203. }
  7204. this._compute(firstNormal);
  7205. return this;
  7206. };
  7207. // private function compute() : computes tangents, normals and binormals
  7208. Path3D.prototype._compute = function (firstNormal) {
  7209. var l = this._curve.length;
  7210. // first and last tangents
  7211. this._tangents[0] = this._getFirstNonNullVector(0);
  7212. if (!this._raw) {
  7213. this._tangents[0].normalize();
  7214. }
  7215. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7216. if (!this._raw) {
  7217. this._tangents[l - 1].normalize();
  7218. }
  7219. // normals and binormals at first point : arbitrary vector with _normalVector()
  7220. var tg0 = this._tangents[0];
  7221. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7222. this._normals[0] = pp0;
  7223. if (!this._raw) {
  7224. this._normals[0].normalize();
  7225. }
  7226. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7227. if (!this._raw) {
  7228. this._binormals[0].normalize();
  7229. }
  7230. this._distances[0] = 0.0;
  7231. // normals and binormals : next points
  7232. var prev; // previous vector (segment)
  7233. var cur; // current vector (segment)
  7234. var curTang; // current tangent
  7235. // previous normal
  7236. var prevBinor; // previous binormal
  7237. for (var i = 1; i < l; i++) {
  7238. // tangents
  7239. prev = this._getLastNonNullVector(i);
  7240. if (i < l - 1) {
  7241. cur = this._getFirstNonNullVector(i);
  7242. this._tangents[i] = prev.add(cur);
  7243. this._tangents[i].normalize();
  7244. }
  7245. this._distances[i] = this._distances[i - 1] + prev.length();
  7246. // normals and binormals
  7247. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7248. curTang = this._tangents[i];
  7249. prevBinor = this._binormals[i - 1];
  7250. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7251. if (!this._raw) {
  7252. this._normals[i].normalize();
  7253. }
  7254. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7255. if (!this._raw) {
  7256. this._binormals[i].normalize();
  7257. }
  7258. }
  7259. };
  7260. // private function getFirstNonNullVector(index)
  7261. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7262. Path3D.prototype._getFirstNonNullVector = function (index) {
  7263. var i = 1;
  7264. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7265. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7266. i++;
  7267. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7268. }
  7269. return nNVector;
  7270. };
  7271. // private function getLastNonNullVector(index)
  7272. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7273. Path3D.prototype._getLastNonNullVector = function (index) {
  7274. var i = 1;
  7275. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7276. while (nLVector.length() === 0 && index > i + 1) {
  7277. i++;
  7278. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7279. }
  7280. return nLVector;
  7281. };
  7282. // private function normalVector(v0, vt, va) :
  7283. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7284. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7285. Path3D.prototype._normalVector = function (v0, vt, va) {
  7286. var normal0;
  7287. var tgl = vt.length();
  7288. if (tgl === 0.0) {
  7289. tgl = 1.0;
  7290. }
  7291. if (va === undefined || va === null) {
  7292. var point;
  7293. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7294. point = new Vector3(0.0, -1.0, 0.0);
  7295. }
  7296. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7297. point = new Vector3(1.0, 0.0, 0.0);
  7298. }
  7299. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7300. point = new Vector3(0.0, 0.0, 1.0);
  7301. }
  7302. else {
  7303. point = Vector3.Zero();
  7304. }
  7305. normal0 = Vector3.Cross(vt, point);
  7306. }
  7307. else {
  7308. normal0 = Vector3.Cross(vt, va);
  7309. Vector3.CrossToRef(normal0, vt, normal0);
  7310. }
  7311. normal0.normalize();
  7312. return normal0;
  7313. };
  7314. return Path3D;
  7315. }());
  7316. BABYLON.Path3D = Path3D;
  7317. var Curve3 = /** @class */ (function () {
  7318. /**
  7319. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7320. * A Curve3 is designed from a series of successive Vector3.
  7321. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7322. */
  7323. function Curve3(points) {
  7324. this._length = 0.0;
  7325. this._points = points;
  7326. this._length = this._computeLength(points);
  7327. }
  7328. /**
  7329. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7330. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7331. * @param v1 (Vector3) the control point
  7332. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7333. * @param nbPoints (integer) the wanted number of points in the curve
  7334. */
  7335. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7336. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7337. var bez = new Array();
  7338. var equation = function (t, val0, val1, val2) {
  7339. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7340. return res;
  7341. };
  7342. for (var i = 0; i <= nbPoints; i++) {
  7343. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  7344. }
  7345. return new Curve3(bez);
  7346. };
  7347. /**
  7348. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7349. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7350. * @param v1 (Vector3) the first control point
  7351. * @param v2 (Vector3) the second control point
  7352. * @param v3 (Vector3) the end point of the Cubic Bezier
  7353. * @param nbPoints (integer) the wanted number of points in the curve
  7354. */
  7355. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7356. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7357. var bez = new Array();
  7358. var equation = function (t, val0, val1, val2, val3) {
  7359. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  7360. return res;
  7361. };
  7362. for (var i = 0; i <= nbPoints; i++) {
  7363. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  7364. }
  7365. return new Curve3(bez);
  7366. };
  7367. /**
  7368. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7369. * @param p1 (Vector3) the origin point of the Hermite Spline
  7370. * @param t1 (Vector3) the tangent vector at the origin point
  7371. * @param p2 (Vector3) the end point of the Hermite Spline
  7372. * @param t2 (Vector3) the tangent vector at the end point
  7373. * @param nbPoints (integer) the wanted number of points in the curve
  7374. */
  7375. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7376. var hermite = new Array();
  7377. var step = 1.0 / nbPoints;
  7378. for (var i = 0; i <= nbPoints; i++) {
  7379. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7380. }
  7381. return new Curve3(hermite);
  7382. };
  7383. /**
  7384. * Returns a Curve3 object along a CatmullRom Spline curve :
  7385. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7386. * @param nbPoints (integer) the wanted number of points between each curve control points
  7387. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7388. */
  7389. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7390. var catmullRom = new Array();
  7391. var step = 1.0 / nbPoints;
  7392. var amount = 0.0;
  7393. if (closed) {
  7394. var pointsCount = points.length;
  7395. for (var i = 0; i < pointsCount; i++) {
  7396. amount = 0;
  7397. for (var c = 0; c < nbPoints; c++) {
  7398. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7399. amount += step;
  7400. }
  7401. }
  7402. catmullRom.push(catmullRom[0]);
  7403. }
  7404. else {
  7405. var totalPoints = new Array();
  7406. totalPoints.push(points[0].clone());
  7407. Array.prototype.push.apply(totalPoints, points);
  7408. totalPoints.push(points[points.length - 1].clone());
  7409. for (var i = 0; i < totalPoints.length - 3; i++) {
  7410. amount = 0;
  7411. for (var c = 0; c < nbPoints; c++) {
  7412. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7413. amount += step;
  7414. }
  7415. }
  7416. i--;
  7417. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7418. }
  7419. return new Curve3(catmullRom);
  7420. };
  7421. /**
  7422. * Returns the Curve3 stored array of successive Vector3
  7423. */
  7424. Curve3.prototype.getPoints = function () {
  7425. return this._points;
  7426. };
  7427. /**
  7428. * Returns the computed length (float) of the curve.
  7429. */
  7430. Curve3.prototype.length = function () {
  7431. return this._length;
  7432. };
  7433. /**
  7434. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7435. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7436. * curveA and curveB keep unchanged.
  7437. */
  7438. Curve3.prototype.continue = function (curve) {
  7439. var lastPoint = this._points[this._points.length - 1];
  7440. var continuedPoints = this._points.slice();
  7441. var curvePoints = curve.getPoints();
  7442. for (var i = 1; i < curvePoints.length; i++) {
  7443. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7444. }
  7445. var continuedCurve = new Curve3(continuedPoints);
  7446. return continuedCurve;
  7447. };
  7448. Curve3.prototype._computeLength = function (path) {
  7449. var l = 0;
  7450. for (var i = 1; i < path.length; i++) {
  7451. l += (path[i].subtract(path[i - 1])).length();
  7452. }
  7453. return l;
  7454. };
  7455. return Curve3;
  7456. }());
  7457. BABYLON.Curve3 = Curve3;
  7458. // Vertex formats
  7459. var PositionNormalVertex = /** @class */ (function () {
  7460. function PositionNormalVertex(position, normal) {
  7461. if (position === void 0) { position = Vector3.Zero(); }
  7462. if (normal === void 0) { normal = Vector3.Up(); }
  7463. this.position = position;
  7464. this.normal = normal;
  7465. }
  7466. PositionNormalVertex.prototype.clone = function () {
  7467. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7468. };
  7469. return PositionNormalVertex;
  7470. }());
  7471. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7472. var PositionNormalTextureVertex = /** @class */ (function () {
  7473. function PositionNormalTextureVertex(position, normal, uv) {
  7474. if (position === void 0) { position = Vector3.Zero(); }
  7475. if (normal === void 0) { normal = Vector3.Up(); }
  7476. if (uv === void 0) { uv = Vector2.Zero(); }
  7477. this.position = position;
  7478. this.normal = normal;
  7479. this.uv = uv;
  7480. }
  7481. PositionNormalTextureVertex.prototype.clone = function () {
  7482. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7483. };
  7484. return PositionNormalTextureVertex;
  7485. }());
  7486. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7487. // Temporary pre-allocated objects for engine internal use
  7488. // usage in any internal function :
  7489. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7490. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7491. var Tmp = /** @class */ (function () {
  7492. function Tmp() {
  7493. }
  7494. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7495. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7496. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7497. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7498. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7499. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7500. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7501. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7502. Matrix.Zero(), Matrix.Zero(),
  7503. Matrix.Zero(), Matrix.Zero(),
  7504. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7505. return Tmp;
  7506. }());
  7507. BABYLON.Tmp = Tmp;
  7508. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7509. var MathTmp = /** @class */ (function () {
  7510. function MathTmp() {
  7511. }
  7512. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7513. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7514. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7515. return MathTmp;
  7516. }());
  7517. })(BABYLON || (BABYLON = {}));
  7518. //# sourceMappingURL=babylon.math.js.map
  7519. var BABYLON;
  7520. (function (BABYLON) {
  7521. var Scalar = /** @class */ (function () {
  7522. function Scalar() {
  7523. }
  7524. /**
  7525. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7526. */
  7527. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7528. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7529. var num = a - b;
  7530. return -epsilon <= num && num <= epsilon;
  7531. };
  7532. /**
  7533. * Returns a string : the upper case translation of the number i to hexadecimal.
  7534. */
  7535. Scalar.ToHex = function (i) {
  7536. var str = i.toString(16);
  7537. if (i <= 15) {
  7538. return ("0" + str).toUpperCase();
  7539. }
  7540. return str.toUpperCase();
  7541. };
  7542. /**
  7543. * Returns -1 if value is negative and +1 is value is positive.
  7544. * Returns the value itself if it's equal to zero.
  7545. */
  7546. Scalar.Sign = function (value) {
  7547. value = +value; // convert to a number
  7548. if (value === 0 || isNaN(value))
  7549. return value;
  7550. return value > 0 ? 1 : -1;
  7551. };
  7552. /**
  7553. * Returns the value itself if it's between min and max.
  7554. * Returns min if the value is lower than min.
  7555. * Returns max if the value is greater than max.
  7556. */
  7557. Scalar.Clamp = function (value, min, max) {
  7558. if (min === void 0) { min = 0; }
  7559. if (max === void 0) { max = 1; }
  7560. return Math.min(max, Math.max(min, value));
  7561. };
  7562. /**
  7563. * Returns the log2 of value.
  7564. */
  7565. Scalar.Log2 = function (value) {
  7566. return Math.log(value) * Math.LOG2E;
  7567. };
  7568. /**
  7569. * Loops the value, so that it is never larger than length and never smaller than 0.
  7570. *
  7571. * This is similar to the modulo operator but it works with floating point numbers.
  7572. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7573. * With t = 5 and length = 2.5, the result would be 0.0.
  7574. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7575. */
  7576. Scalar.Repeat = function (value, length) {
  7577. return value - Math.floor(value / length) * length;
  7578. };
  7579. /**
  7580. * Normalize the value between 0.0 and 1.0 using min and max values
  7581. */
  7582. Scalar.Normalize = function (value, min, max) {
  7583. return (value - min) / (max - min);
  7584. };
  7585. /**
  7586. * Denormalize the value from 0.0 and 1.0 using min and max values
  7587. */
  7588. Scalar.Denormalize = function (normalized, min, max) {
  7589. return (normalized * (max - min) + min);
  7590. };
  7591. /**
  7592. * Calculates the shortest difference between two given angles given in degrees.
  7593. */
  7594. Scalar.DeltaAngle = function (current, target) {
  7595. var num = Scalar.Repeat(target - current, 360.0);
  7596. if (num > 180.0) {
  7597. num -= 360.0;
  7598. }
  7599. return num;
  7600. };
  7601. /**
  7602. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7603. *
  7604. * The returned value will move back and forth between 0 and length
  7605. */
  7606. Scalar.PingPong = function (tx, length) {
  7607. var t = Scalar.Repeat(tx, length * 2.0);
  7608. return length - Math.abs(t - length);
  7609. };
  7610. /**
  7611. * Interpolates between min and max with smoothing at the limits.
  7612. *
  7613. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7614. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7615. */
  7616. Scalar.SmoothStep = function (from, to, tx) {
  7617. var t = Scalar.Clamp(tx);
  7618. t = -2.0 * t * t * t + 3.0 * t * t;
  7619. return to * t + from * (1.0 - t);
  7620. };
  7621. /**
  7622. * Moves a value current towards target.
  7623. *
  7624. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7625. * Negative values of maxDelta pushes the value away from target.
  7626. */
  7627. Scalar.MoveTowards = function (current, target, maxDelta) {
  7628. var result = 0;
  7629. if (Math.abs(target - current) <= maxDelta) {
  7630. result = target;
  7631. }
  7632. else {
  7633. result = current + Scalar.Sign(target - current) * maxDelta;
  7634. }
  7635. return result;
  7636. };
  7637. /**
  7638. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7639. *
  7640. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7641. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7642. */
  7643. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7644. var num = Scalar.DeltaAngle(current, target);
  7645. var result = 0;
  7646. if (-maxDelta < num && num < maxDelta) {
  7647. result = target;
  7648. }
  7649. else {
  7650. target = current + num;
  7651. result = Scalar.MoveTowards(current, target, maxDelta);
  7652. }
  7653. return result;
  7654. };
  7655. /**
  7656. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7657. */
  7658. Scalar.Lerp = function (start, end, amount) {
  7659. return start + ((end - start) * amount);
  7660. };
  7661. /**
  7662. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7663. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7664. */
  7665. Scalar.LerpAngle = function (start, end, amount) {
  7666. var num = Scalar.Repeat(end - start, 360.0);
  7667. if (num > 180.0) {
  7668. num -= 360.0;
  7669. }
  7670. return start + num * Scalar.Clamp(amount);
  7671. };
  7672. /**
  7673. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7674. */
  7675. Scalar.InverseLerp = function (a, b, value) {
  7676. var result = 0;
  7677. if (a != b) {
  7678. result = Scalar.Clamp((value - a) / (b - a));
  7679. }
  7680. else {
  7681. result = 0.0;
  7682. }
  7683. return result;
  7684. };
  7685. /**
  7686. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7687. */
  7688. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7689. var squared = amount * amount;
  7690. var cubed = amount * squared;
  7691. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7692. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7693. var part3 = (cubed - (2.0 * squared)) + amount;
  7694. var part4 = cubed - squared;
  7695. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7696. };
  7697. /**
  7698. * Returns a random float number between and min and max values
  7699. */
  7700. Scalar.RandomRange = function (min, max) {
  7701. if (min === max)
  7702. return min;
  7703. return ((Math.random() * (max - min)) + min);
  7704. };
  7705. /**
  7706. * This function returns percentage of a number in a given range.
  7707. *
  7708. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7709. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7710. */
  7711. Scalar.RangeToPercent = function (number, min, max) {
  7712. return ((number - min) / (max - min));
  7713. };
  7714. /**
  7715. * This function returns number that corresponds to the percentage in a given range.
  7716. *
  7717. * PercentToRange(0.34,0,100) will return 34.
  7718. */
  7719. Scalar.PercentToRange = function (percent, min, max) {
  7720. return ((max - min) * percent + min);
  7721. };
  7722. /**
  7723. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7724. * @param angle The angle to normalize in radian.
  7725. * @return The converted angle.
  7726. */
  7727. Scalar.NormalizeRadians = function (angle) {
  7728. // More precise but slower version kept for reference.
  7729. // angle = angle % Tools.TwoPi;
  7730. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7731. //if (angle > Math.PI) {
  7732. // angle -= Tools.TwoPi;
  7733. //}
  7734. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7735. return angle;
  7736. };
  7737. /**
  7738. * Two pi constants convenient for computation.
  7739. */
  7740. Scalar.TwoPi = Math.PI * 2;
  7741. return Scalar;
  7742. }());
  7743. BABYLON.Scalar = Scalar;
  7744. })(BABYLON || (BABYLON = {}));
  7745. //# sourceMappingURL=babylon.math.scalar.js.map
  7746. //# sourceMappingURL=babylon.mixins.js.map
  7747. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7748. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7749. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7750. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7751. //# sourceMappingURL=babylon.webgl2.js.map
  7752. var BABYLON;
  7753. (function (BABYLON) {
  7754. var __decoratorInitialStore = {};
  7755. var __mergedStore = {};
  7756. var _copySource = function (creationFunction, source, instanciate) {
  7757. var destination = creationFunction();
  7758. // Tags
  7759. if (BABYLON.Tags) {
  7760. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7761. }
  7762. var classStore = getMergedStore(destination);
  7763. // Properties
  7764. for (var property in classStore) {
  7765. var propertyDescriptor = classStore[property];
  7766. var sourceProperty = source[property];
  7767. var propertyType = propertyDescriptor.type;
  7768. if (sourceProperty !== undefined && sourceProperty !== null) {
  7769. switch (propertyType) {
  7770. case 0: // Value
  7771. case 6: // Mesh reference
  7772. case 11: // Camera reference
  7773. destination[property] = sourceProperty;
  7774. break;
  7775. case 1: // Texture
  7776. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7777. break;
  7778. case 2: // Color3
  7779. case 3: // FresnelParameters
  7780. case 4: // Vector2
  7781. case 5: // Vector3
  7782. case 7: // Color Curves
  7783. case 10: // Quaternion
  7784. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7785. break;
  7786. }
  7787. }
  7788. }
  7789. return destination;
  7790. };
  7791. function getDirectStore(target) {
  7792. var classKey = target.getClassName();
  7793. if (!__decoratorInitialStore[classKey]) {
  7794. __decoratorInitialStore[classKey] = {};
  7795. }
  7796. return __decoratorInitialStore[classKey];
  7797. }
  7798. /**
  7799. * Return the list of properties flagged as serializable
  7800. * @param target: host object
  7801. */
  7802. function getMergedStore(target) {
  7803. var classKey = target.getClassName();
  7804. if (__mergedStore[classKey]) {
  7805. return __mergedStore[classKey];
  7806. }
  7807. __mergedStore[classKey] = {};
  7808. var store = __mergedStore[classKey];
  7809. var currentTarget = target;
  7810. var currentKey = classKey;
  7811. while (currentKey) {
  7812. var initialStore = __decoratorInitialStore[currentKey];
  7813. for (var property in initialStore) {
  7814. store[property] = initialStore[property];
  7815. }
  7816. var parent_1 = void 0;
  7817. var done = false;
  7818. do {
  7819. parent_1 = Object.getPrototypeOf(currentTarget);
  7820. if (!parent_1.getClassName) {
  7821. done = true;
  7822. break;
  7823. }
  7824. if (parent_1.getClassName() !== currentKey) {
  7825. break;
  7826. }
  7827. currentTarget = parent_1;
  7828. } while (parent_1);
  7829. if (done) {
  7830. break;
  7831. }
  7832. currentKey = parent_1.getClassName();
  7833. currentTarget = parent_1;
  7834. }
  7835. return store;
  7836. }
  7837. function generateSerializableMember(type, sourceName) {
  7838. return function (target, propertyKey) {
  7839. var classStore = getDirectStore(target);
  7840. if (!classStore[propertyKey]) {
  7841. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7842. }
  7843. };
  7844. }
  7845. function generateExpandMember(setCallback, targetKey) {
  7846. if (targetKey === void 0) { targetKey = null; }
  7847. return function (target, propertyKey) {
  7848. var key = targetKey || ("_" + propertyKey);
  7849. Object.defineProperty(target, propertyKey, {
  7850. get: function () {
  7851. return this[key];
  7852. },
  7853. set: function (value) {
  7854. if (this[key] === value) {
  7855. return;
  7856. }
  7857. this[key] = value;
  7858. target[setCallback].apply(this);
  7859. },
  7860. enumerable: true,
  7861. configurable: true
  7862. });
  7863. };
  7864. }
  7865. function expandToProperty(callback, targetKey) {
  7866. if (targetKey === void 0) { targetKey = null; }
  7867. return generateExpandMember(callback, targetKey);
  7868. }
  7869. BABYLON.expandToProperty = expandToProperty;
  7870. function serialize(sourceName) {
  7871. return generateSerializableMember(0, sourceName); // value member
  7872. }
  7873. BABYLON.serialize = serialize;
  7874. function serializeAsTexture(sourceName) {
  7875. return generateSerializableMember(1, sourceName); // texture member
  7876. }
  7877. BABYLON.serializeAsTexture = serializeAsTexture;
  7878. function serializeAsColor3(sourceName) {
  7879. return generateSerializableMember(2, sourceName); // color3 member
  7880. }
  7881. BABYLON.serializeAsColor3 = serializeAsColor3;
  7882. function serializeAsFresnelParameters(sourceName) {
  7883. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7884. }
  7885. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7886. function serializeAsVector2(sourceName) {
  7887. return generateSerializableMember(4, sourceName); // vector2 member
  7888. }
  7889. BABYLON.serializeAsVector2 = serializeAsVector2;
  7890. function serializeAsVector3(sourceName) {
  7891. return generateSerializableMember(5, sourceName); // vector3 member
  7892. }
  7893. BABYLON.serializeAsVector3 = serializeAsVector3;
  7894. function serializeAsMeshReference(sourceName) {
  7895. return generateSerializableMember(6, sourceName); // mesh reference member
  7896. }
  7897. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7898. function serializeAsColorCurves(sourceName) {
  7899. return generateSerializableMember(7, sourceName); // color curves
  7900. }
  7901. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7902. function serializeAsColor4(sourceName) {
  7903. return generateSerializableMember(8, sourceName); // color 4
  7904. }
  7905. BABYLON.serializeAsColor4 = serializeAsColor4;
  7906. function serializeAsImageProcessingConfiguration(sourceName) {
  7907. return generateSerializableMember(9, sourceName); // image processing
  7908. }
  7909. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7910. function serializeAsQuaternion(sourceName) {
  7911. return generateSerializableMember(10, sourceName); // quaternion member
  7912. }
  7913. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7914. /**
  7915. * Decorator used to define property that can be serialized as reference to a camera
  7916. * @param sourceName defines the name of the property to decorate
  7917. */
  7918. function serializeAsCameraReference(sourceName) {
  7919. return generateSerializableMember(11, sourceName); // camera reference member
  7920. }
  7921. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7922. var SerializationHelper = /** @class */ (function () {
  7923. function SerializationHelper() {
  7924. }
  7925. SerializationHelper.Serialize = function (entity, serializationObject) {
  7926. if (!serializationObject) {
  7927. serializationObject = {};
  7928. }
  7929. // Tags
  7930. if (BABYLON.Tags) {
  7931. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7932. }
  7933. var serializedProperties = getMergedStore(entity);
  7934. // Properties
  7935. for (var property in serializedProperties) {
  7936. var propertyDescriptor = serializedProperties[property];
  7937. var targetPropertyName = propertyDescriptor.sourceName || property;
  7938. var propertyType = propertyDescriptor.type;
  7939. var sourceProperty = entity[property];
  7940. if (sourceProperty !== undefined && sourceProperty !== null) {
  7941. switch (propertyType) {
  7942. case 0: // Value
  7943. serializationObject[targetPropertyName] = sourceProperty;
  7944. break;
  7945. case 1: // Texture
  7946. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7947. break;
  7948. case 2: // Color3
  7949. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7950. break;
  7951. case 3: // FresnelParameters
  7952. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7953. break;
  7954. case 4: // Vector2
  7955. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7956. break;
  7957. case 5: // Vector3
  7958. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7959. break;
  7960. case 6: // Mesh reference
  7961. serializationObject[targetPropertyName] = sourceProperty.id;
  7962. break;
  7963. case 7: // Color Curves
  7964. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7965. break;
  7966. case 8: // Color 4
  7967. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7968. break;
  7969. case 9: // Image Processing
  7970. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7971. break;
  7972. case 10: // Quaternion
  7973. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7974. break;
  7975. case 11: // Camera reference
  7976. serializationObject[targetPropertyName] = sourceProperty.id;
  7977. break;
  7978. }
  7979. }
  7980. }
  7981. return serializationObject;
  7982. };
  7983. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7984. if (rootUrl === void 0) { rootUrl = null; }
  7985. var destination = creationFunction();
  7986. if (!rootUrl) {
  7987. rootUrl = "";
  7988. }
  7989. // Tags
  7990. if (BABYLON.Tags) {
  7991. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7992. }
  7993. var classStore = getMergedStore(destination);
  7994. // Properties
  7995. for (var property in classStore) {
  7996. var propertyDescriptor = classStore[property];
  7997. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7998. var propertyType = propertyDescriptor.type;
  7999. if (sourceProperty !== undefined && sourceProperty !== null) {
  8000. var dest = destination;
  8001. switch (propertyType) {
  8002. case 0: // Value
  8003. dest[property] = sourceProperty;
  8004. break;
  8005. case 1: // Texture
  8006. if (scene) {
  8007. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8008. }
  8009. break;
  8010. case 2: // Color3
  8011. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8012. break;
  8013. case 3: // FresnelParameters
  8014. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8015. break;
  8016. case 4: // Vector2
  8017. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8018. break;
  8019. case 5: // Vector3
  8020. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8021. break;
  8022. case 6: // Mesh reference
  8023. if (scene) {
  8024. dest[property] = scene.getLastMeshByID(sourceProperty);
  8025. }
  8026. break;
  8027. case 7: // Color Curves
  8028. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8029. break;
  8030. case 8: // Color 4
  8031. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8032. break;
  8033. case 9: // Image Processing
  8034. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8035. break;
  8036. case 10: // Quaternion
  8037. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8038. break;
  8039. case 11: // Camera reference
  8040. if (scene) {
  8041. dest[property] = scene.getCameraByID(sourceProperty);
  8042. }
  8043. break;
  8044. }
  8045. }
  8046. }
  8047. return destination;
  8048. };
  8049. SerializationHelper.Clone = function (creationFunction, source) {
  8050. return _copySource(creationFunction, source, false);
  8051. };
  8052. SerializationHelper.Instanciate = function (creationFunction, source) {
  8053. return _copySource(creationFunction, source, true);
  8054. };
  8055. return SerializationHelper;
  8056. }());
  8057. BABYLON.SerializationHelper = SerializationHelper;
  8058. })(BABYLON || (BABYLON = {}));
  8059. //# sourceMappingURL=babylon.decorators.js.map
  8060. var BABYLON;
  8061. (function (BABYLON) {
  8062. /**
  8063. * Wrapper class for promise with external resolve and reject.
  8064. */
  8065. var Deferred = /** @class */ (function () {
  8066. /**
  8067. * Constructor for this deferred object.
  8068. */
  8069. function Deferred() {
  8070. var _this = this;
  8071. this.promise = new Promise(function (resolve, reject) {
  8072. _this._resolve = resolve;
  8073. _this._reject = reject;
  8074. });
  8075. }
  8076. Object.defineProperty(Deferred.prototype, "resolve", {
  8077. /**
  8078. * The resolve method of the promise associated with this deferred object.
  8079. */
  8080. get: function () {
  8081. return this._resolve;
  8082. },
  8083. enumerable: true,
  8084. configurable: true
  8085. });
  8086. Object.defineProperty(Deferred.prototype, "reject", {
  8087. /**
  8088. * The reject method of the promise associated with this deferred object.
  8089. */
  8090. get: function () {
  8091. return this._reject;
  8092. },
  8093. enumerable: true,
  8094. configurable: true
  8095. });
  8096. return Deferred;
  8097. }());
  8098. BABYLON.Deferred = Deferred;
  8099. })(BABYLON || (BABYLON = {}));
  8100. //# sourceMappingURL=babylon.deferred.js.map
  8101. var BABYLON;
  8102. (function (BABYLON) {
  8103. /**
  8104. * A class serves as a medium between the observable and its observers
  8105. */
  8106. var EventState = /** @class */ (function () {
  8107. /**
  8108. * Create a new EventState
  8109. * @param mask defines the mask associated with this state
  8110. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8111. * @param target defines the original target of the state
  8112. * @param currentTarget defines the current target of the state
  8113. */
  8114. function EventState(mask, skipNextObservers, target, currentTarget) {
  8115. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8116. this.initalize(mask, skipNextObservers, target, currentTarget);
  8117. }
  8118. /**
  8119. * Initialize the current event state
  8120. * @param mask defines the mask associated with this state
  8121. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8122. * @param target defines the original target of the state
  8123. * @param currentTarget defines the current target of the state
  8124. * @returns the current event state
  8125. */
  8126. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8127. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8128. this.mask = mask;
  8129. this.skipNextObservers = skipNextObservers;
  8130. this.target = target;
  8131. this.currentTarget = currentTarget;
  8132. return this;
  8133. };
  8134. return EventState;
  8135. }());
  8136. BABYLON.EventState = EventState;
  8137. /**
  8138. * Represent an Observer registered to a given Observable object.
  8139. */
  8140. var Observer = /** @class */ (function () {
  8141. /**
  8142. * Creates a new observer
  8143. * @param callback defines the callback to call when the observer is notified
  8144. * @param mask defines the mask of the observer (used to filter notifications)
  8145. * @param scope defines the current scope used to restore the JS context
  8146. */
  8147. function Observer(
  8148. /**
  8149. * Defines the callback to call when the observer is notified
  8150. */
  8151. callback,
  8152. /**
  8153. * Defines the mask of the observer (used to filter notifications)
  8154. */
  8155. mask,
  8156. /**
  8157. * Defines the current scope used to restore the JS context
  8158. */
  8159. scope) {
  8160. if (scope === void 0) { scope = null; }
  8161. this.callback = callback;
  8162. this.mask = mask;
  8163. this.scope = scope;
  8164. /** @hidden */
  8165. this._willBeUnregistered = false;
  8166. /**
  8167. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8168. */
  8169. this.unregisterOnNextCall = false;
  8170. }
  8171. return Observer;
  8172. }());
  8173. BABYLON.Observer = Observer;
  8174. /**
  8175. * Represent a list of observers registered to multiple Observables object.
  8176. */
  8177. var MultiObserver = /** @class */ (function () {
  8178. function MultiObserver() {
  8179. }
  8180. /**
  8181. * Release associated resources
  8182. */
  8183. MultiObserver.prototype.dispose = function () {
  8184. if (this._observers && this._observables) {
  8185. for (var index = 0; index < this._observers.length; index++) {
  8186. this._observables[index].remove(this._observers[index]);
  8187. }
  8188. }
  8189. this._observers = null;
  8190. this._observables = null;
  8191. };
  8192. /**
  8193. * Raise a callback when one of the observable will notify
  8194. * @param observables defines a list of observables to watch
  8195. * @param callback defines the callback to call on notification
  8196. * @param mask defines the mask used to filter notifications
  8197. * @param scope defines the current scope used to restore the JS context
  8198. * @returns the new MultiObserver
  8199. */
  8200. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8201. if (mask === void 0) { mask = -1; }
  8202. if (scope === void 0) { scope = null; }
  8203. var result = new MultiObserver();
  8204. result._observers = new Array();
  8205. result._observables = observables;
  8206. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8207. var observable = observables_1[_i];
  8208. var observer = observable.add(callback, mask, false, scope);
  8209. if (observer) {
  8210. result._observers.push(observer);
  8211. }
  8212. }
  8213. return result;
  8214. };
  8215. return MultiObserver;
  8216. }());
  8217. BABYLON.MultiObserver = MultiObserver;
  8218. /**
  8219. * The Observable class is a simple implementation of the Observable pattern.
  8220. *
  8221. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  8222. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8223. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  8224. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  8225. */
  8226. var Observable = /** @class */ (function () {
  8227. /**
  8228. * Creates a new observable
  8229. * @param onObserverAdded defines a callback to call when a new observer is added
  8230. */
  8231. function Observable(onObserverAdded) {
  8232. this._observers = new Array();
  8233. this._eventState = new EventState(0);
  8234. if (onObserverAdded) {
  8235. this._onObserverAdded = onObserverAdded;
  8236. }
  8237. }
  8238. /**
  8239. * Create a new Observer with the specified callback
  8240. * @param callback the callback that will be executed for that Observer
  8241. * @param mask the mask used to filter observers
  8242. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  8243. * @param scope optional scope for the callback to be called from
  8244. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8245. * @returns the new observer created for the callback
  8246. */
  8247. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8248. if (mask === void 0) { mask = -1; }
  8249. if (insertFirst === void 0) { insertFirst = false; }
  8250. if (scope === void 0) { scope = null; }
  8251. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8252. if (!callback) {
  8253. return null;
  8254. }
  8255. var observer = new Observer(callback, mask, scope);
  8256. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8257. if (insertFirst) {
  8258. this._observers.unshift(observer);
  8259. }
  8260. else {
  8261. this._observers.push(observer);
  8262. }
  8263. if (this._onObserverAdded) {
  8264. this._onObserverAdded(observer);
  8265. }
  8266. return observer;
  8267. };
  8268. /**
  8269. * Create a new Observer with the specified callback and unregisters after the next notification
  8270. * @param callback the callback that will be executed for that Observer
  8271. * @returns the new observer created for the callback
  8272. */
  8273. Observable.prototype.addOnce = function (callback) {
  8274. return this.add(callback, undefined, undefined, undefined, true);
  8275. };
  8276. /**
  8277. * Remove an Observer from the Observable object
  8278. * @param observer the instance of the Observer to remove
  8279. * @returns false if it doesn't belong to this Observable
  8280. */
  8281. Observable.prototype.remove = function (observer) {
  8282. if (!observer) {
  8283. return false;
  8284. }
  8285. var index = this._observers.indexOf(observer);
  8286. if (index !== -1) {
  8287. this._deferUnregister(observer);
  8288. return true;
  8289. }
  8290. return false;
  8291. };
  8292. /**
  8293. * Remove a callback from the Observable object
  8294. * @param callback the callback to remove
  8295. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8296. * @returns false if it doesn't belong to this Observable
  8297. */
  8298. Observable.prototype.removeCallback = function (callback, scope) {
  8299. for (var index = 0; index < this._observers.length; index++) {
  8300. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8301. this._deferUnregister(this._observers[index]);
  8302. return true;
  8303. }
  8304. }
  8305. return false;
  8306. };
  8307. Observable.prototype._deferUnregister = function (observer) {
  8308. var _this = this;
  8309. observer.unregisterOnNextCall = false;
  8310. observer._willBeUnregistered = true;
  8311. BABYLON.Tools.SetImmediate(function () {
  8312. _this._remove(observer);
  8313. });
  8314. };
  8315. // This should only be called when not iterating over _observers to avoid callback skipping.
  8316. // Removes an observer from the _observer Array.
  8317. Observable.prototype._remove = function (observer) {
  8318. if (!observer) {
  8319. return false;
  8320. }
  8321. var index = this._observers.indexOf(observer);
  8322. if (index !== -1) {
  8323. this._observers.splice(index, 1);
  8324. return true;
  8325. }
  8326. return false;
  8327. };
  8328. /**
  8329. * Notify all Observers by calling their respective callback with the given data
  8330. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8331. * @param eventData defines the data to send to all observers
  8332. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8333. * @param target defines the original target of the state
  8334. * @param currentTarget defines the current target of the state
  8335. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8336. */
  8337. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8338. if (mask === void 0) { mask = -1; }
  8339. if (!this._observers.length) {
  8340. return true;
  8341. }
  8342. var state = this._eventState;
  8343. state.mask = mask;
  8344. state.target = target;
  8345. state.currentTarget = currentTarget;
  8346. state.skipNextObservers = false;
  8347. state.lastReturnValue = eventData;
  8348. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8349. var obs = _a[_i];
  8350. if (obs._willBeUnregistered) {
  8351. continue;
  8352. }
  8353. if (obs.mask & mask) {
  8354. if (obs.scope) {
  8355. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8356. }
  8357. else {
  8358. state.lastReturnValue = obs.callback(eventData, state);
  8359. }
  8360. if (obs.unregisterOnNextCall) {
  8361. this._deferUnregister(obs);
  8362. }
  8363. }
  8364. if (state.skipNextObservers) {
  8365. return false;
  8366. }
  8367. }
  8368. return true;
  8369. };
  8370. /**
  8371. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8372. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8373. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8374. * and it is crucial that all callbacks will be executed.
  8375. * The order of the callbacks is kept, callbacks are not executed parallel.
  8376. *
  8377. * @param eventData The data to be sent to each callback
  8378. * @param mask is used to filter observers defaults to -1
  8379. * @param target defines the callback target (see EventState)
  8380. * @param currentTarget defines he current object in the bubbling phase
  8381. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8382. */
  8383. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8384. var _this = this;
  8385. if (mask === void 0) { mask = -1; }
  8386. // create an empty promise
  8387. var p = Promise.resolve(eventData);
  8388. // no observers? return this promise.
  8389. if (!this._observers.length) {
  8390. return p;
  8391. }
  8392. var state = this._eventState;
  8393. state.mask = mask;
  8394. state.target = target;
  8395. state.currentTarget = currentTarget;
  8396. state.skipNextObservers = false;
  8397. // execute one callback after another (not using Promise.all, the order is important)
  8398. this._observers.forEach(function (obs) {
  8399. if (state.skipNextObservers) {
  8400. return;
  8401. }
  8402. if (obs._willBeUnregistered) {
  8403. return;
  8404. }
  8405. if (obs.mask & mask) {
  8406. if (obs.scope) {
  8407. p = p.then(function (lastReturnedValue) {
  8408. state.lastReturnValue = lastReturnedValue;
  8409. return obs.callback.apply(obs.scope, [eventData, state]);
  8410. });
  8411. }
  8412. else {
  8413. p = p.then(function (lastReturnedValue) {
  8414. state.lastReturnValue = lastReturnedValue;
  8415. return obs.callback(eventData, state);
  8416. });
  8417. }
  8418. if (obs.unregisterOnNextCall) {
  8419. _this._deferUnregister(obs);
  8420. }
  8421. }
  8422. });
  8423. // return the eventData
  8424. return p.then(function () { return eventData; });
  8425. };
  8426. /**
  8427. * Notify a specific observer
  8428. * @param observer defines the observer to notify
  8429. * @param eventData defines the data to be sent to each callback
  8430. * @param mask is used to filter observers defaults to -1
  8431. */
  8432. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8433. if (mask === void 0) { mask = -1; }
  8434. var state = this._eventState;
  8435. state.mask = mask;
  8436. state.skipNextObservers = false;
  8437. observer.callback(eventData, state);
  8438. };
  8439. /**
  8440. * Gets a boolean indicating if the observable has at least one observer
  8441. * @returns true is the Observable has at least one Observer registered
  8442. */
  8443. Observable.prototype.hasObservers = function () {
  8444. return this._observers.length > 0;
  8445. };
  8446. /**
  8447. * Clear the list of observers
  8448. */
  8449. Observable.prototype.clear = function () {
  8450. this._observers = new Array();
  8451. this._onObserverAdded = null;
  8452. };
  8453. /**
  8454. * Clone the current observable
  8455. * @returns a new observable
  8456. */
  8457. Observable.prototype.clone = function () {
  8458. var result = new Observable();
  8459. result._observers = this._observers.slice(0);
  8460. return result;
  8461. };
  8462. /**
  8463. * Does this observable handles observer registered with a given mask
  8464. * @param mask defines the mask to be tested
  8465. * @return whether or not one observer registered with the given mask is handeled
  8466. **/
  8467. Observable.prototype.hasSpecificMask = function (mask) {
  8468. if (mask === void 0) { mask = -1; }
  8469. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8470. var obs = _a[_i];
  8471. if (obs.mask & mask || obs.mask === mask) {
  8472. return true;
  8473. }
  8474. }
  8475. return false;
  8476. };
  8477. return Observable;
  8478. }());
  8479. BABYLON.Observable = Observable;
  8480. })(BABYLON || (BABYLON = {}));
  8481. //# sourceMappingURL=babylon.observable.js.map
  8482. var BABYLON;
  8483. (function (BABYLON) {
  8484. var SmartArray = /** @class */ (function () {
  8485. function SmartArray(capacity) {
  8486. this.length = 0;
  8487. this.data = new Array(capacity);
  8488. this._id = SmartArray._GlobalId++;
  8489. }
  8490. SmartArray.prototype.push = function (value) {
  8491. this.data[this.length++] = value;
  8492. if (this.length > this.data.length) {
  8493. this.data.length *= 2;
  8494. }
  8495. };
  8496. SmartArray.prototype.forEach = function (func) {
  8497. for (var index = 0; index < this.length; index++) {
  8498. func(this.data[index]);
  8499. }
  8500. };
  8501. SmartArray.prototype.sort = function (compareFn) {
  8502. this.data.sort(compareFn);
  8503. };
  8504. SmartArray.prototype.reset = function () {
  8505. this.length = 0;
  8506. };
  8507. SmartArray.prototype.dispose = function () {
  8508. this.reset();
  8509. if (this.data) {
  8510. this.data.length = 0;
  8511. this.data = [];
  8512. }
  8513. };
  8514. SmartArray.prototype.concat = function (array) {
  8515. if (array.length === 0) {
  8516. return;
  8517. }
  8518. if (this.length + array.length > this.data.length) {
  8519. this.data.length = (this.length + array.length) * 2;
  8520. }
  8521. for (var index = 0; index < array.length; index++) {
  8522. this.data[this.length++] = (array.data || array)[index];
  8523. }
  8524. };
  8525. SmartArray.prototype.indexOf = function (value) {
  8526. var position = this.data.indexOf(value);
  8527. if (position >= this.length) {
  8528. return -1;
  8529. }
  8530. return position;
  8531. };
  8532. SmartArray.prototype.contains = function (value) {
  8533. return this.data.indexOf(value) !== -1;
  8534. };
  8535. // Statics
  8536. SmartArray._GlobalId = 0;
  8537. return SmartArray;
  8538. }());
  8539. BABYLON.SmartArray = SmartArray;
  8540. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8541. __extends(SmartArrayNoDuplicate, _super);
  8542. function SmartArrayNoDuplicate() {
  8543. var _this = _super !== null && _super.apply(this, arguments) || this;
  8544. _this._duplicateId = 0;
  8545. return _this;
  8546. }
  8547. SmartArrayNoDuplicate.prototype.push = function (value) {
  8548. _super.prototype.push.call(this, value);
  8549. if (!value.__smartArrayFlags) {
  8550. value.__smartArrayFlags = {};
  8551. }
  8552. value.__smartArrayFlags[this._id] = this._duplicateId;
  8553. };
  8554. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8555. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8556. return false;
  8557. }
  8558. this.push(value);
  8559. return true;
  8560. };
  8561. SmartArrayNoDuplicate.prototype.reset = function () {
  8562. _super.prototype.reset.call(this);
  8563. this._duplicateId++;
  8564. };
  8565. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8566. if (array.length === 0) {
  8567. return;
  8568. }
  8569. if (this.length + array.length > this.data.length) {
  8570. this.data.length = (this.length + array.length) * 2;
  8571. }
  8572. for (var index = 0; index < array.length; index++) {
  8573. var item = (array.data || array)[index];
  8574. this.pushNoDuplicate(item);
  8575. }
  8576. };
  8577. return SmartArrayNoDuplicate;
  8578. }(SmartArray));
  8579. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8580. })(BABYLON || (BABYLON = {}));
  8581. //# sourceMappingURL=babylon.smartArray.js.map
  8582. var BABYLON;
  8583. (function (BABYLON) {
  8584. /** Class used to store color gradient */
  8585. var ColorGradient = /** @class */ (function () {
  8586. function ColorGradient() {
  8587. }
  8588. /**
  8589. * Will get a color picked randomly between color1 and color2.
  8590. * If color2 is undefined then color1 will be used
  8591. * @param result defines the target Color4 to store the result in
  8592. */
  8593. ColorGradient.prototype.getColorToRef = function (result) {
  8594. if (!this.color2) {
  8595. result.copyFrom(this.color1);
  8596. return;
  8597. }
  8598. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8599. };
  8600. return ColorGradient;
  8601. }());
  8602. BABYLON.ColorGradient = ColorGradient;
  8603. /** Class used to store factor gradient */
  8604. var FactorGradient = /** @class */ (function () {
  8605. function FactorGradient() {
  8606. }
  8607. /**
  8608. * Will get a number picked randomly between factor1 and factor2.
  8609. * If factor2 is undefined then factor1 will be used
  8610. * @returns the picked number
  8611. */
  8612. FactorGradient.prototype.getFactor = function () {
  8613. if (this.factor2 === undefined) {
  8614. return this.factor1;
  8615. }
  8616. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8617. };
  8618. return FactorGradient;
  8619. }());
  8620. BABYLON.FactorGradient = FactorGradient;
  8621. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8622. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8623. var LoadFileError = /** @class */ (function (_super) {
  8624. __extends(LoadFileError, _super);
  8625. function LoadFileError(message, request) {
  8626. var _this = _super.call(this, message) || this;
  8627. _this.request = request;
  8628. _this.name = "LoadFileError";
  8629. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8630. return _this;
  8631. }
  8632. // Polyfill for Object.setPrototypeOf if necessary.
  8633. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8634. return LoadFileError;
  8635. }(Error));
  8636. BABYLON.LoadFileError = LoadFileError;
  8637. var RetryStrategy = /** @class */ (function () {
  8638. function RetryStrategy() {
  8639. }
  8640. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8641. if (maxRetries === void 0) { maxRetries = 3; }
  8642. if (baseInterval === void 0) { baseInterval = 500; }
  8643. return function (url, request, retryIndex) {
  8644. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8645. return -1;
  8646. }
  8647. return Math.pow(2, retryIndex) * baseInterval;
  8648. };
  8649. };
  8650. return RetryStrategy;
  8651. }());
  8652. BABYLON.RetryStrategy = RetryStrategy;
  8653. // Screenshots
  8654. var screenshotCanvas;
  8655. var cloneValue = function (source, destinationObject) {
  8656. if (!source)
  8657. return null;
  8658. if (source instanceof BABYLON.Mesh) {
  8659. return null;
  8660. }
  8661. if (source instanceof BABYLON.SubMesh) {
  8662. return source.clone(destinationObject);
  8663. }
  8664. else if (source.clone) {
  8665. return source.clone();
  8666. }
  8667. return null;
  8668. };
  8669. var Tools = /** @class */ (function () {
  8670. function Tools() {
  8671. }
  8672. /**
  8673. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  8674. * @param u defines the coordinate on X axis
  8675. * @param v defines the coordinate on Y axis
  8676. * @param width defines the width of the source data
  8677. * @param height defines the height of the source data
  8678. * @param pixels defines the source byte array
  8679. * @param color defines the output color
  8680. */
  8681. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  8682. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  8683. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  8684. var position = (wrappedU + wrappedV * width) * 4;
  8685. color.r = pixels[position] / 255;
  8686. color.g = pixels[position + 1] / 255;
  8687. color.b = pixels[position + 2] / 255;
  8688. color.a = pixels[position + 3] / 255;
  8689. };
  8690. /**
  8691. * Interpolates between a and b via alpha
  8692. * @param a The lower value (returned when alpha = 0)
  8693. * @param b The upper value (returned when alpha = 1)
  8694. * @param alpha The interpolation-factor
  8695. * @return The mixed value
  8696. */
  8697. Tools.Mix = function (a, b, alpha) {
  8698. return a * (1 - alpha) + b * alpha;
  8699. };
  8700. Tools.Instantiate = function (className) {
  8701. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8702. return Tools.RegisteredExternalClasses[className];
  8703. }
  8704. var arr = className.split(".");
  8705. var fn = (window || this);
  8706. for (var i = 0, len = arr.length; i < len; i++) {
  8707. fn = fn[arr[i]];
  8708. }
  8709. if (typeof fn !== "function") {
  8710. return null;
  8711. }
  8712. return fn;
  8713. };
  8714. /**
  8715. * Provides a slice function that will work even on IE
  8716. * @param data defines the array to slice
  8717. * @param start defines the start of the data (optional)
  8718. * @param end defines the end of the data (optional)
  8719. * @returns the new sliced array
  8720. */
  8721. Tools.Slice = function (data, start, end) {
  8722. if (data.slice) {
  8723. return data.slice(start, end);
  8724. }
  8725. return Array.prototype.slice.call(data, start, end);
  8726. };
  8727. Tools.SetImmediate = function (action) {
  8728. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  8729. window.setImmediate(action);
  8730. }
  8731. else {
  8732. setTimeout(action, 1);
  8733. }
  8734. };
  8735. Tools.IsExponentOfTwo = function (value) {
  8736. var count = 1;
  8737. do {
  8738. count *= 2;
  8739. } while (count < value);
  8740. return count === value;
  8741. };
  8742. /**
  8743. * Returns the nearest 32-bit single precision float representation of a Number
  8744. * @param value A Number. If the parameter is of a different type, it will get converted
  8745. * to a number or to NaN if it cannot be converted
  8746. * @returns number
  8747. */
  8748. Tools.FloatRound = function (value) {
  8749. if (Math.fround) {
  8750. return Math.fround(value);
  8751. }
  8752. return (Tools._tmpFloatArray[0] = value);
  8753. };
  8754. /**
  8755. * Find the next highest power of two.
  8756. * @param x Number to start search from.
  8757. * @return Next highest power of two.
  8758. */
  8759. Tools.CeilingPOT = function (x) {
  8760. x--;
  8761. x |= x >> 1;
  8762. x |= x >> 2;
  8763. x |= x >> 4;
  8764. x |= x >> 8;
  8765. x |= x >> 16;
  8766. x++;
  8767. return x;
  8768. };
  8769. /**
  8770. * Find the next lowest power of two.
  8771. * @param x Number to start search from.
  8772. * @return Next lowest power of two.
  8773. */
  8774. Tools.FloorPOT = function (x) {
  8775. x = x | (x >> 1);
  8776. x = x | (x >> 2);
  8777. x = x | (x >> 4);
  8778. x = x | (x >> 8);
  8779. x = x | (x >> 16);
  8780. return x - (x >> 1);
  8781. };
  8782. /**
  8783. * Find the nearest power of two.
  8784. * @param x Number to start search from.
  8785. * @return Next nearest power of two.
  8786. */
  8787. Tools.NearestPOT = function (x) {
  8788. var c = Tools.CeilingPOT(x);
  8789. var f = Tools.FloorPOT(x);
  8790. return (c - x) > (x - f) ? f : c;
  8791. };
  8792. Tools.GetExponentOfTwo = function (value, max, mode) {
  8793. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8794. var pot;
  8795. switch (mode) {
  8796. case BABYLON.Engine.SCALEMODE_FLOOR:
  8797. pot = Tools.FloorPOT(value);
  8798. break;
  8799. case BABYLON.Engine.SCALEMODE_NEAREST:
  8800. pot = Tools.NearestPOT(value);
  8801. break;
  8802. case BABYLON.Engine.SCALEMODE_CEILING:
  8803. default:
  8804. pot = Tools.CeilingPOT(value);
  8805. break;
  8806. }
  8807. return Math.min(pot, max);
  8808. };
  8809. Tools.GetFilename = function (path) {
  8810. var index = path.lastIndexOf("/");
  8811. if (index < 0)
  8812. return path;
  8813. return path.substring(index + 1);
  8814. };
  8815. /**
  8816. * Extracts the "folder" part of a path (everything before the filename).
  8817. * @param uri The URI to extract the info from
  8818. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8819. * @returns The "folder" part of the path
  8820. */
  8821. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8822. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8823. var index = uri.lastIndexOf("/");
  8824. if (index < 0) {
  8825. if (returnUnchangedIfNoSlash) {
  8826. return uri;
  8827. }
  8828. return "";
  8829. }
  8830. return uri.substring(0, index + 1);
  8831. };
  8832. Tools.GetDOMTextContent = function (element) {
  8833. var result = "";
  8834. var child = element.firstChild;
  8835. while (child) {
  8836. if (child.nodeType === 3) {
  8837. result += child.textContent;
  8838. }
  8839. child = child.nextSibling;
  8840. }
  8841. return result;
  8842. };
  8843. Tools.ToDegrees = function (angle) {
  8844. return angle * 180 / Math.PI;
  8845. };
  8846. Tools.ToRadians = function (angle) {
  8847. return angle * Math.PI / 180;
  8848. };
  8849. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8850. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8851. var output = "";
  8852. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8853. var i = 0;
  8854. var bytes = new Uint8Array(buffer);
  8855. while (i < bytes.length) {
  8856. chr1 = bytes[i++];
  8857. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8858. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8859. enc1 = chr1 >> 2;
  8860. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8861. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8862. enc4 = chr3 & 63;
  8863. if (isNaN(chr2)) {
  8864. enc3 = enc4 = 64;
  8865. }
  8866. else if (isNaN(chr3)) {
  8867. enc4 = 64;
  8868. }
  8869. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8870. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8871. }
  8872. return "data:image/png;base64," + output;
  8873. };
  8874. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8875. if (bias === void 0) { bias = null; }
  8876. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8877. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8878. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8879. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8880. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8881. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8882. }
  8883. if (bias) {
  8884. minimum.x -= minimum.x * bias.x + bias.y;
  8885. minimum.y -= minimum.y * bias.x + bias.y;
  8886. minimum.z -= minimum.z * bias.x + bias.y;
  8887. maximum.x += maximum.x * bias.x + bias.y;
  8888. maximum.y += maximum.y * bias.x + bias.y;
  8889. maximum.z += maximum.z * bias.x + bias.y;
  8890. }
  8891. return {
  8892. minimum: minimum,
  8893. maximum: maximum
  8894. };
  8895. };
  8896. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8897. if (bias === void 0) { bias = null; }
  8898. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8899. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8900. if (!stride) {
  8901. stride = 3;
  8902. }
  8903. for (var index = start; index < start + count; index++) {
  8904. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8905. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8906. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8907. }
  8908. if (bias) {
  8909. minimum.x -= minimum.x * bias.x + bias.y;
  8910. minimum.y -= minimum.y * bias.x + bias.y;
  8911. minimum.z -= minimum.z * bias.x + bias.y;
  8912. maximum.x += maximum.x * bias.x + bias.y;
  8913. maximum.y += maximum.y * bias.x + bias.y;
  8914. maximum.z += maximum.z * bias.x + bias.y;
  8915. }
  8916. return {
  8917. minimum: minimum,
  8918. maximum: maximum
  8919. };
  8920. };
  8921. Tools.Vector2ArrayFeeder = function (array) {
  8922. return function (index) {
  8923. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8924. var length = isFloatArray ? array.length / 2 : array.length;
  8925. if (index >= length) {
  8926. return null;
  8927. }
  8928. if (isFloatArray) {
  8929. var fa = array;
  8930. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8931. }
  8932. var a = array;
  8933. return a[index];
  8934. };
  8935. };
  8936. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8937. if (bias === void 0) { bias = null; }
  8938. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8939. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8940. var i = 0;
  8941. var cur = feeder(i++);
  8942. while (cur) {
  8943. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8944. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8945. cur = feeder(i++);
  8946. }
  8947. if (bias) {
  8948. minimum.x -= minimum.x * bias.x + bias.y;
  8949. minimum.y -= minimum.y * bias.x + bias.y;
  8950. maximum.x += maximum.x * bias.x + bias.y;
  8951. maximum.y += maximum.y * bias.x + bias.y;
  8952. }
  8953. return {
  8954. minimum: minimum,
  8955. maximum: maximum
  8956. };
  8957. };
  8958. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8959. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8960. return null;
  8961. return Array.isArray(obj) ? obj : [obj];
  8962. };
  8963. // Misc.
  8964. Tools.GetPointerPrefix = function () {
  8965. var eventPrefix = "pointer";
  8966. // Check if pointer events are supported
  8967. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8968. eventPrefix = "mouse";
  8969. }
  8970. return eventPrefix;
  8971. };
  8972. /**
  8973. * @param func - the function to be called
  8974. * @param requester - the object that will request the next frame. Falls back to window.
  8975. */
  8976. Tools.QueueNewFrame = function (func, requester) {
  8977. if (!Tools.IsWindowObjectExist()) {
  8978. return setTimeout(func, 16);
  8979. }
  8980. if (!requester) {
  8981. requester = window;
  8982. }
  8983. if (requester.requestAnimationFrame) {
  8984. return requester.requestAnimationFrame(func);
  8985. }
  8986. else if (requester.msRequestAnimationFrame) {
  8987. return requester.msRequestAnimationFrame(func);
  8988. }
  8989. else if (requester.webkitRequestAnimationFrame) {
  8990. return requester.webkitRequestAnimationFrame(func);
  8991. }
  8992. else if (requester.mozRequestAnimationFrame) {
  8993. return requester.mozRequestAnimationFrame(func);
  8994. }
  8995. else if (requester.oRequestAnimationFrame) {
  8996. return requester.oRequestAnimationFrame(func);
  8997. }
  8998. else {
  8999. return window.setTimeout(func, 16);
  9000. }
  9001. };
  9002. Tools.RequestFullscreen = function (element) {
  9003. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  9004. if (!requestFunction)
  9005. return;
  9006. requestFunction.call(element);
  9007. };
  9008. Tools.ExitFullscreen = function () {
  9009. if (document.exitFullscreen) {
  9010. document.exitFullscreen();
  9011. }
  9012. else if (document.mozCancelFullScreen) {
  9013. document.mozCancelFullScreen();
  9014. }
  9015. else if (document.webkitCancelFullScreen) {
  9016. document.webkitCancelFullScreen();
  9017. }
  9018. else if (document.msCancelFullScreen) {
  9019. document.msCancelFullScreen();
  9020. }
  9021. };
  9022. Tools.SetCorsBehavior = function (url, element) {
  9023. if (url && url.indexOf("data:") === 0) {
  9024. return;
  9025. }
  9026. if (Tools.CorsBehavior) {
  9027. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9028. element.crossOrigin = Tools.CorsBehavior;
  9029. }
  9030. else {
  9031. var result = Tools.CorsBehavior(url);
  9032. if (result) {
  9033. element.crossOrigin = result;
  9034. }
  9035. }
  9036. }
  9037. };
  9038. // External files
  9039. Tools.CleanUrl = function (url) {
  9040. url = url.replace(/#/mg, "%23");
  9041. return url;
  9042. };
  9043. /**
  9044. * Loads an image as an HTMLImageElement.
  9045. * @param input url string, ArrayBuffer, or Blob to load
  9046. * @param onLoad callback called when the image successfully loads
  9047. * @param onError callback called when the image fails to load
  9048. * @param database database for caching
  9049. * @returns the HTMLImageElement of the loaded image
  9050. */
  9051. Tools.LoadImage = function (input, onLoad, onError, database) {
  9052. var url;
  9053. var usingObjectURL = false;
  9054. if (input instanceof ArrayBuffer) {
  9055. url = URL.createObjectURL(new Blob([input]));
  9056. usingObjectURL = true;
  9057. }
  9058. else if (input instanceof Blob) {
  9059. url = URL.createObjectURL(input);
  9060. usingObjectURL = true;
  9061. }
  9062. else {
  9063. url = Tools.CleanUrl(input);
  9064. url = Tools.PreprocessUrl(input);
  9065. }
  9066. var img = new Image();
  9067. Tools.SetCorsBehavior(url, img);
  9068. var loadHandler = function () {
  9069. if (usingObjectURL && img.src) {
  9070. URL.revokeObjectURL(img.src);
  9071. }
  9072. img.removeEventListener("load", loadHandler);
  9073. img.removeEventListener("error", errorHandler);
  9074. onLoad(img);
  9075. };
  9076. var errorHandler = function (err) {
  9077. if (usingObjectURL && img.src) {
  9078. URL.revokeObjectURL(img.src);
  9079. }
  9080. img.removeEventListener("load", loadHandler);
  9081. img.removeEventListener("error", errorHandler);
  9082. Tools.Error("Error while trying to load image: " + input);
  9083. if (onError) {
  9084. onError("Error while trying to load image: " + input, err);
  9085. }
  9086. };
  9087. img.addEventListener("load", loadHandler);
  9088. img.addEventListener("error", errorHandler);
  9089. var noIndexedDB = function () {
  9090. img.src = url;
  9091. };
  9092. var loadFromIndexedDB = function () {
  9093. if (database) {
  9094. database.loadImageFromDB(url, img);
  9095. }
  9096. };
  9097. //ANY database to do!
  9098. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9099. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9100. }
  9101. else {
  9102. if (url.indexOf("file:") !== -1) {
  9103. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9104. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9105. try {
  9106. var blobURL;
  9107. try {
  9108. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9109. }
  9110. catch (ex) {
  9111. // Chrome doesn't support oneTimeOnly parameter
  9112. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9113. }
  9114. img.src = blobURL;
  9115. usingObjectURL = true;
  9116. }
  9117. catch (e) {
  9118. img.src = "";
  9119. }
  9120. return img;
  9121. }
  9122. }
  9123. noIndexedDB();
  9124. }
  9125. return img;
  9126. };
  9127. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9128. url = Tools.CleanUrl(url);
  9129. url = Tools.PreprocessUrl(url);
  9130. // If file and file input are set
  9131. if (url.indexOf("file:") !== -1) {
  9132. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9133. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9134. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9135. }
  9136. }
  9137. var loadUrl = Tools.BaseUrl + url;
  9138. var aborted = false;
  9139. var fileRequest = {
  9140. onCompleteObservable: new BABYLON.Observable(),
  9141. abort: function () { return aborted = true; },
  9142. };
  9143. var requestFile = function () {
  9144. var request = new XMLHttpRequest();
  9145. var retryHandle = null;
  9146. fileRequest.abort = function () {
  9147. aborted = true;
  9148. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9149. request.abort();
  9150. }
  9151. if (retryHandle !== null) {
  9152. clearTimeout(retryHandle);
  9153. retryHandle = null;
  9154. }
  9155. };
  9156. var retryLoop = function (retryIndex) {
  9157. request.open('GET', loadUrl, true);
  9158. if (useArrayBuffer) {
  9159. request.responseType = "arraybuffer";
  9160. }
  9161. if (onProgress) {
  9162. request.addEventListener("progress", onProgress);
  9163. }
  9164. var onLoadEnd = function () {
  9165. request.removeEventListener("loadend", onLoadEnd);
  9166. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9167. fileRequest.onCompleteObservable.clear();
  9168. };
  9169. request.addEventListener("loadend", onLoadEnd);
  9170. var onReadyStateChange = function () {
  9171. if (aborted) {
  9172. return;
  9173. }
  9174. // In case of undefined state in some browsers.
  9175. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9176. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9177. request.removeEventListener("readystatechange", onReadyStateChange);
  9178. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9179. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9180. return;
  9181. }
  9182. var retryStrategy = Tools.DefaultRetryStrategy;
  9183. if (retryStrategy) {
  9184. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9185. if (waitTime !== -1) {
  9186. // Prevent the request from completing for retry.
  9187. request.removeEventListener("loadend", onLoadEnd);
  9188. request = new XMLHttpRequest();
  9189. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9190. return;
  9191. }
  9192. }
  9193. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9194. if (onError) {
  9195. onError(request, e);
  9196. }
  9197. else {
  9198. throw e;
  9199. }
  9200. }
  9201. };
  9202. request.addEventListener("readystatechange", onReadyStateChange);
  9203. request.send();
  9204. };
  9205. retryLoop(0);
  9206. };
  9207. // Caching all files
  9208. if (database && database.enableSceneOffline) {
  9209. var noIndexedDB_1 = function (request) {
  9210. if (request && request.status > 400) {
  9211. if (onError) {
  9212. onError(request);
  9213. }
  9214. }
  9215. else {
  9216. if (!aborted) {
  9217. requestFile();
  9218. }
  9219. }
  9220. };
  9221. var loadFromIndexedDB = function () {
  9222. // TODO: database needs to support aborting and should return a IFileRequest
  9223. if (aborted) {
  9224. return;
  9225. }
  9226. if (database) {
  9227. database.loadFileFromDB(url, function (data) {
  9228. if (!aborted) {
  9229. onSuccess(data);
  9230. }
  9231. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9232. }, onProgress ? function (event) {
  9233. if (!aborted) {
  9234. onProgress(event);
  9235. }
  9236. } : undefined, noIndexedDB_1, useArrayBuffer);
  9237. }
  9238. };
  9239. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9240. }
  9241. else {
  9242. requestFile();
  9243. }
  9244. return fileRequest;
  9245. };
  9246. /**
  9247. * Load a script (identified by an url). When the url returns, the
  9248. * content of this file is added into a new script element, attached to the DOM (body element)
  9249. */
  9250. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9251. var head = document.getElementsByTagName('head')[0];
  9252. var script = document.createElement('script');
  9253. script.type = 'text/javascript';
  9254. script.src = scriptUrl;
  9255. script.onload = function () {
  9256. if (onSuccess) {
  9257. onSuccess();
  9258. }
  9259. };
  9260. script.onerror = function (e) {
  9261. if (onError) {
  9262. onError("Unable to load script '" + scriptUrl + "'", e);
  9263. }
  9264. };
  9265. head.appendChild(script);
  9266. };
  9267. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9268. var reader = new FileReader();
  9269. var request = {
  9270. onCompleteObservable: new BABYLON.Observable(),
  9271. abort: function () { return reader.abort(); },
  9272. };
  9273. reader.onloadend = function (e) {
  9274. request.onCompleteObservable.notifyObservers(request);
  9275. };
  9276. reader.onload = function (e) {
  9277. //target doesn't have result from ts 1.3
  9278. callback(e.target['result']);
  9279. };
  9280. reader.onprogress = progressCallback;
  9281. reader.readAsDataURL(fileToLoad);
  9282. return request;
  9283. };
  9284. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9285. var reader = new FileReader();
  9286. var request = {
  9287. onCompleteObservable: new BABYLON.Observable(),
  9288. abort: function () { return reader.abort(); },
  9289. };
  9290. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9291. reader.onerror = function (e) {
  9292. Tools.Log("Error while reading file: " + fileToLoad.name);
  9293. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9294. };
  9295. reader.onload = function (e) {
  9296. //target doesn't have result from ts 1.3
  9297. callback(e.target['result']);
  9298. };
  9299. if (progressCallBack) {
  9300. reader.onprogress = progressCallBack;
  9301. }
  9302. if (!useArrayBuffer) {
  9303. // Asynchronous read
  9304. reader.readAsText(fileToLoad);
  9305. }
  9306. else {
  9307. reader.readAsArrayBuffer(fileToLoad);
  9308. }
  9309. return request;
  9310. };
  9311. //returns a downloadable url to a file content.
  9312. Tools.FileAsURL = function (content) {
  9313. var fileBlob = new Blob([content]);
  9314. var url = window.URL || window.webkitURL;
  9315. var link = url.createObjectURL(fileBlob);
  9316. return link;
  9317. };
  9318. // Misc.
  9319. Tools.Format = function (value, decimals) {
  9320. if (decimals === void 0) { decimals = 2; }
  9321. return value.toFixed(decimals);
  9322. };
  9323. Tools.CheckExtends = function (v, min, max) {
  9324. if (v.x < min.x)
  9325. min.x = v.x;
  9326. if (v.y < min.y)
  9327. min.y = v.y;
  9328. if (v.z < min.z)
  9329. min.z = v.z;
  9330. if (v.x > max.x)
  9331. max.x = v.x;
  9332. if (v.y > max.y)
  9333. max.y = v.y;
  9334. if (v.z > max.z)
  9335. max.z = v.z;
  9336. };
  9337. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9338. for (var prop in source) {
  9339. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9340. continue;
  9341. }
  9342. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9343. continue;
  9344. }
  9345. var sourceValue = source[prop];
  9346. var typeOfSourceValue = typeof sourceValue;
  9347. if (typeOfSourceValue === "function") {
  9348. continue;
  9349. }
  9350. try {
  9351. if (typeOfSourceValue === "object") {
  9352. if (sourceValue instanceof Array) {
  9353. destination[prop] = [];
  9354. if (sourceValue.length > 0) {
  9355. if (typeof sourceValue[0] == "object") {
  9356. for (var index = 0; index < sourceValue.length; index++) {
  9357. var clonedValue = cloneValue(sourceValue[index], destination);
  9358. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9359. destination[prop].push(clonedValue);
  9360. }
  9361. }
  9362. }
  9363. else {
  9364. destination[prop] = sourceValue.slice(0);
  9365. }
  9366. }
  9367. }
  9368. else {
  9369. destination[prop] = cloneValue(sourceValue, destination);
  9370. }
  9371. }
  9372. else {
  9373. destination[prop] = sourceValue;
  9374. }
  9375. }
  9376. catch (e) {
  9377. // Just ignore error (it could be because of a read-only property)
  9378. }
  9379. }
  9380. };
  9381. Tools.IsEmpty = function (obj) {
  9382. for (var i in obj) {
  9383. if (obj.hasOwnProperty(i)) {
  9384. return false;
  9385. }
  9386. }
  9387. return true;
  9388. };
  9389. Tools.RegisterTopRootEvents = function (events) {
  9390. for (var index = 0; index < events.length; index++) {
  9391. var event = events[index];
  9392. window.addEventListener(event.name, event.handler, false);
  9393. try {
  9394. if (window.parent) {
  9395. window.parent.addEventListener(event.name, event.handler, false);
  9396. }
  9397. }
  9398. catch (e) {
  9399. // Silently fails...
  9400. }
  9401. }
  9402. };
  9403. Tools.UnregisterTopRootEvents = function (events) {
  9404. for (var index = 0; index < events.length; index++) {
  9405. var event = events[index];
  9406. window.removeEventListener(event.name, event.handler);
  9407. try {
  9408. if (window.parent) {
  9409. window.parent.removeEventListener(event.name, event.handler);
  9410. }
  9411. }
  9412. catch (e) {
  9413. // Silently fails...
  9414. }
  9415. }
  9416. };
  9417. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9418. if (mimeType === void 0) { mimeType = "image/png"; }
  9419. // Read the contents of the framebuffer
  9420. var numberOfChannelsByLine = width * 4;
  9421. var halfHeight = height / 2;
  9422. //Reading datas from WebGL
  9423. var data = engine.readPixels(0, 0, width, height);
  9424. //To flip image on Y axis.
  9425. for (var i = 0; i < halfHeight; i++) {
  9426. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9427. var currentCell = j + i * numberOfChannelsByLine;
  9428. var targetLine = height - i - 1;
  9429. var targetCell = j + targetLine * numberOfChannelsByLine;
  9430. var temp = data[currentCell];
  9431. data[currentCell] = data[targetCell];
  9432. data[targetCell] = temp;
  9433. }
  9434. }
  9435. // Create a 2D canvas to store the result
  9436. if (!screenshotCanvas) {
  9437. screenshotCanvas = document.createElement('canvas');
  9438. }
  9439. screenshotCanvas.width = width;
  9440. screenshotCanvas.height = height;
  9441. var context = screenshotCanvas.getContext('2d');
  9442. if (context) {
  9443. // Copy the pixels to a 2D canvas
  9444. var imageData = context.createImageData(width, height);
  9445. var castData = (imageData.data);
  9446. castData.set(data);
  9447. context.putImageData(imageData, 0, 0);
  9448. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9449. }
  9450. };
  9451. /**
  9452. * Converts the canvas data to blob.
  9453. * This acts as a polyfill for browsers not supporting the to blob function.
  9454. * @param canvas Defines the canvas to extract the data from
  9455. * @param successCallback Defines the callback triggered once the data are available
  9456. * @param mimeType Defines the mime type of the result
  9457. */
  9458. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9459. if (mimeType === void 0) { mimeType = "image/png"; }
  9460. // We need HTMLCanvasElement.toBlob for HD screenshots
  9461. if (!canvas.toBlob) {
  9462. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9463. canvas.toBlob = function (callback, type, quality) {
  9464. var _this = this;
  9465. setTimeout(function () {
  9466. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9467. for (var i = 0; i < len; i++) {
  9468. arr[i] = binStr.charCodeAt(i);
  9469. }
  9470. callback(new Blob([arr]));
  9471. });
  9472. };
  9473. }
  9474. canvas.toBlob(function (blob) {
  9475. successCallback(blob);
  9476. }, mimeType);
  9477. };
  9478. /**
  9479. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9480. * @param successCallback Defines the callback triggered once the data are available
  9481. * @param mimeType Defines the mime type of the result
  9482. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9483. */
  9484. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9485. if (mimeType === void 0) { mimeType = "image/png"; }
  9486. if (successCallback) {
  9487. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9488. successCallback(base64Image);
  9489. }
  9490. else {
  9491. this.ToBlob(screenshotCanvas, function (blob) {
  9492. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9493. if (("download" in document.createElement("a"))) {
  9494. if (!fileName) {
  9495. var date = new Date();
  9496. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9497. fileName = "screenshot_" + stringDate + ".png";
  9498. }
  9499. Tools.Download(blob, fileName);
  9500. }
  9501. else {
  9502. var url = URL.createObjectURL(blob);
  9503. var newWindow = window.open("");
  9504. if (!newWindow)
  9505. return;
  9506. var img = newWindow.document.createElement("img");
  9507. img.onload = function () {
  9508. // no longer need to read the blob so it's revoked
  9509. URL.revokeObjectURL(url);
  9510. };
  9511. img.src = url;
  9512. newWindow.document.body.appendChild(img);
  9513. }
  9514. }, mimeType);
  9515. }
  9516. };
  9517. /**
  9518. * Downloads a blob in the browser
  9519. * @param blob defines the blob to download
  9520. * @param fileName defines the name of the downloaded file
  9521. */
  9522. Tools.Download = function (blob, fileName) {
  9523. if (navigator && navigator.msSaveBlob) {
  9524. navigator.msSaveBlob(blob, fileName);
  9525. return;
  9526. }
  9527. var url = window.URL.createObjectURL(blob);
  9528. var a = document.createElement("a");
  9529. document.body.appendChild(a);
  9530. a.style.display = "none";
  9531. a.href = url;
  9532. a.download = fileName;
  9533. a.addEventListener("click", function () {
  9534. if (a.parentElement) {
  9535. a.parentElement.removeChild(a);
  9536. }
  9537. });
  9538. a.click();
  9539. window.URL.revokeObjectURL(url);
  9540. };
  9541. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9542. if (mimeType === void 0) { mimeType = "image/png"; }
  9543. var width;
  9544. var height;
  9545. // If a precision value is specified
  9546. if (size.precision) {
  9547. width = Math.round(engine.getRenderWidth() * size.precision);
  9548. height = Math.round(width / engine.getAspectRatio(camera));
  9549. }
  9550. else if (size.width && size.height) {
  9551. width = size.width;
  9552. height = size.height;
  9553. }
  9554. //If passing only width, computing height to keep display canvas ratio.
  9555. else if (size.width && !size.height) {
  9556. width = size.width;
  9557. height = Math.round(width / engine.getAspectRatio(camera));
  9558. }
  9559. //If passing only height, computing width to keep display canvas ratio.
  9560. else if (size.height && !size.width) {
  9561. height = size.height;
  9562. width = Math.round(height * engine.getAspectRatio(camera));
  9563. }
  9564. //Assuming here that "size" parameter is a number
  9565. else if (!isNaN(size)) {
  9566. height = size;
  9567. width = size;
  9568. }
  9569. else {
  9570. Tools.Error("Invalid 'size' parameter !");
  9571. return;
  9572. }
  9573. if (!screenshotCanvas) {
  9574. screenshotCanvas = document.createElement('canvas');
  9575. }
  9576. screenshotCanvas.width = width;
  9577. screenshotCanvas.height = height;
  9578. var renderContext = screenshotCanvas.getContext("2d");
  9579. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9580. var newWidth = width;
  9581. var newHeight = newWidth / ratio;
  9582. if (newHeight > height) {
  9583. newHeight = height;
  9584. newWidth = newHeight * ratio;
  9585. }
  9586. var offsetX = Math.max(0, width - newWidth) / 2;
  9587. var offsetY = Math.max(0, height - newHeight) / 2;
  9588. var renderingCanvas = engine.getRenderingCanvas();
  9589. if (renderContext && renderingCanvas) {
  9590. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9591. }
  9592. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9593. };
  9594. /**
  9595. * Generates an image screenshot from the specified camera.
  9596. *
  9597. * @param engine The engine to use for rendering
  9598. * @param camera The camera to use for rendering
  9599. * @param size This parameter can be set to a single number or to an object with the
  9600. * following (optional) properties: precision, width, height. If a single number is passed,
  9601. * it will be used for both width and height. If an object is passed, the screenshot size
  9602. * will be derived from the parameters. The precision property is a multiplier allowing
  9603. * rendering at a higher or lower resolution.
  9604. * @param successCallback The callback receives a single parameter which contains the
  9605. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9606. * src parameter of an <img> to display it.
  9607. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9608. * Check your browser for supported MIME types.
  9609. * @param samples Texture samples (default: 1)
  9610. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9611. * @param fileName A name for for the downloaded file.
  9612. * @constructor
  9613. */
  9614. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9615. if (mimeType === void 0) { mimeType = "image/png"; }
  9616. if (samples === void 0) { samples = 1; }
  9617. if (antialiasing === void 0) { antialiasing = false; }
  9618. var width;
  9619. var height;
  9620. //If a precision value is specified
  9621. if (size.precision) {
  9622. width = Math.round(engine.getRenderWidth() * size.precision);
  9623. height = Math.round(width / engine.getAspectRatio(camera));
  9624. size = { width: width, height: height };
  9625. }
  9626. else if (size.width && size.height) {
  9627. width = size.width;
  9628. height = size.height;
  9629. }
  9630. //If passing only width, computing height to keep display canvas ratio.
  9631. else if (size.width && !size.height) {
  9632. width = size.width;
  9633. height = Math.round(width / engine.getAspectRatio(camera));
  9634. size = { width: width, height: height };
  9635. }
  9636. //If passing only height, computing width to keep display canvas ratio.
  9637. else if (size.height && !size.width) {
  9638. height = size.height;
  9639. width = Math.round(height * engine.getAspectRatio(camera));
  9640. size = { width: width, height: height };
  9641. }
  9642. //Assuming here that "size" parameter is a number
  9643. else if (!isNaN(size)) {
  9644. height = size;
  9645. width = size;
  9646. }
  9647. else {
  9648. Tools.Error("Invalid 'size' parameter !");
  9649. return;
  9650. }
  9651. var scene = camera.getScene();
  9652. var previousCamera = null;
  9653. if (scene.activeCamera !== camera) {
  9654. previousCamera = scene.activeCamera;
  9655. scene.activeCamera = camera;
  9656. }
  9657. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9658. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9659. texture.renderList = null;
  9660. texture.samples = samples;
  9661. if (antialiasing) {
  9662. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9663. }
  9664. texture.onAfterRenderObservable.add(function () {
  9665. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9666. });
  9667. scene.incrementRenderId();
  9668. scene.resetCachedMaterial();
  9669. texture.render(true);
  9670. texture.dispose();
  9671. if (previousCamera) {
  9672. scene.activeCamera = previousCamera;
  9673. }
  9674. camera.getProjectionMatrix(true); // Force cache refresh;
  9675. };
  9676. // XHR response validator for local file scenario
  9677. Tools.ValidateXHRData = function (xhr, dataType) {
  9678. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9679. if (dataType === void 0) { dataType = 7; }
  9680. try {
  9681. if (dataType & 1) {
  9682. if (xhr.responseText && xhr.responseText.length > 0) {
  9683. return true;
  9684. }
  9685. else if (dataType === 1) {
  9686. return false;
  9687. }
  9688. }
  9689. if (dataType & 2) {
  9690. // Check header width and height since there is no "TGA" magic number
  9691. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9692. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9693. return true;
  9694. }
  9695. else if (dataType === 2) {
  9696. return false;
  9697. }
  9698. }
  9699. if (dataType & 4) {
  9700. // Check for the "DDS" magic number
  9701. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9702. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9703. return true;
  9704. }
  9705. else {
  9706. return false;
  9707. }
  9708. }
  9709. }
  9710. catch (e) {
  9711. // Global protection
  9712. }
  9713. return false;
  9714. };
  9715. /**
  9716. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9717. * Be aware Math.random() could cause collisions, but:
  9718. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  9719. */
  9720. Tools.RandomId = function () {
  9721. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9722. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9723. return v.toString(16);
  9724. });
  9725. };
  9726. /**
  9727. * Test if the given uri is a base64 string.
  9728. * @param uri The uri to test
  9729. * @return True if the uri is a base64 string or false otherwise.
  9730. */
  9731. Tools.IsBase64 = function (uri) {
  9732. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9733. };
  9734. /**
  9735. * Decode the given base64 uri.
  9736. * @param uri The uri to decode
  9737. * @return The decoded base64 data.
  9738. */
  9739. Tools.DecodeBase64 = function (uri) {
  9740. var decodedString = atob(uri.split(",")[1]);
  9741. var bufferLength = decodedString.length;
  9742. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9743. for (var i = 0; i < bufferLength; i++) {
  9744. bufferView[i] = decodedString.charCodeAt(i);
  9745. }
  9746. return bufferView.buffer;
  9747. };
  9748. Object.defineProperty(Tools, "NoneLogLevel", {
  9749. get: function () {
  9750. return Tools._NoneLogLevel;
  9751. },
  9752. enumerable: true,
  9753. configurable: true
  9754. });
  9755. Object.defineProperty(Tools, "MessageLogLevel", {
  9756. get: function () {
  9757. return Tools._MessageLogLevel;
  9758. },
  9759. enumerable: true,
  9760. configurable: true
  9761. });
  9762. Object.defineProperty(Tools, "WarningLogLevel", {
  9763. get: function () {
  9764. return Tools._WarningLogLevel;
  9765. },
  9766. enumerable: true,
  9767. configurable: true
  9768. });
  9769. Object.defineProperty(Tools, "ErrorLogLevel", {
  9770. get: function () {
  9771. return Tools._ErrorLogLevel;
  9772. },
  9773. enumerable: true,
  9774. configurable: true
  9775. });
  9776. Object.defineProperty(Tools, "AllLogLevel", {
  9777. get: function () {
  9778. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9779. },
  9780. enumerable: true,
  9781. configurable: true
  9782. });
  9783. Tools._AddLogEntry = function (entry) {
  9784. Tools._LogCache = entry + Tools._LogCache;
  9785. if (Tools.OnNewCacheEntry) {
  9786. Tools.OnNewCacheEntry(entry);
  9787. }
  9788. };
  9789. Tools._FormatMessage = function (message) {
  9790. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9791. var date = new Date();
  9792. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9793. };
  9794. Tools._LogDisabled = function (message) {
  9795. // nothing to do
  9796. };
  9797. Tools._LogEnabled = function (message) {
  9798. var formattedMessage = Tools._FormatMessage(message);
  9799. console.log("BJS - " + formattedMessage);
  9800. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9801. Tools._AddLogEntry(entry);
  9802. };
  9803. Tools._WarnDisabled = function (message) {
  9804. // nothing to do
  9805. };
  9806. Tools._WarnEnabled = function (message) {
  9807. var formattedMessage = Tools._FormatMessage(message);
  9808. console.warn("BJS - " + formattedMessage);
  9809. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9810. Tools._AddLogEntry(entry);
  9811. };
  9812. Tools._ErrorDisabled = function (message) {
  9813. // nothing to do
  9814. };
  9815. Tools._ErrorEnabled = function (message) {
  9816. Tools.errorsCount++;
  9817. var formattedMessage = Tools._FormatMessage(message);
  9818. console.error("BJS - " + formattedMessage);
  9819. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9820. Tools._AddLogEntry(entry);
  9821. };
  9822. Object.defineProperty(Tools, "LogCache", {
  9823. get: function () {
  9824. return Tools._LogCache;
  9825. },
  9826. enumerable: true,
  9827. configurable: true
  9828. });
  9829. Tools.ClearLogCache = function () {
  9830. Tools._LogCache = "";
  9831. Tools.errorsCount = 0;
  9832. };
  9833. Object.defineProperty(Tools, "LogLevels", {
  9834. set: function (level) {
  9835. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9836. Tools.Log = Tools._LogEnabled;
  9837. }
  9838. else {
  9839. Tools.Log = Tools._LogDisabled;
  9840. }
  9841. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9842. Tools.Warn = Tools._WarnEnabled;
  9843. }
  9844. else {
  9845. Tools.Warn = Tools._WarnDisabled;
  9846. }
  9847. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9848. Tools.Error = Tools._ErrorEnabled;
  9849. }
  9850. else {
  9851. Tools.Error = Tools._ErrorDisabled;
  9852. }
  9853. },
  9854. enumerable: true,
  9855. configurable: true
  9856. });
  9857. Tools.IsWindowObjectExist = function () {
  9858. return (typeof window) !== "undefined";
  9859. };
  9860. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9861. get: function () {
  9862. return Tools._PerformanceNoneLogLevel;
  9863. },
  9864. enumerable: true,
  9865. configurable: true
  9866. });
  9867. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9868. get: function () {
  9869. return Tools._PerformanceUserMarkLogLevel;
  9870. },
  9871. enumerable: true,
  9872. configurable: true
  9873. });
  9874. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9875. get: function () {
  9876. return Tools._PerformanceConsoleLogLevel;
  9877. },
  9878. enumerable: true,
  9879. configurable: true
  9880. });
  9881. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9882. set: function (level) {
  9883. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9884. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9885. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9886. return;
  9887. }
  9888. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9889. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9890. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9891. return;
  9892. }
  9893. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9894. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9895. },
  9896. enumerable: true,
  9897. configurable: true
  9898. });
  9899. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9900. };
  9901. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9902. };
  9903. Tools._StartUserMark = function (counterName, condition) {
  9904. if (condition === void 0) { condition = true; }
  9905. if (!Tools._performance) {
  9906. if (!Tools.IsWindowObjectExist()) {
  9907. return;
  9908. }
  9909. Tools._performance = window.performance;
  9910. }
  9911. if (!condition || !Tools._performance.mark) {
  9912. return;
  9913. }
  9914. Tools._performance.mark(counterName + "-Begin");
  9915. };
  9916. Tools._EndUserMark = function (counterName, condition) {
  9917. if (condition === void 0) { condition = true; }
  9918. if (!condition || !Tools._performance.mark) {
  9919. return;
  9920. }
  9921. Tools._performance.mark(counterName + "-End");
  9922. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9923. };
  9924. Tools._StartPerformanceConsole = function (counterName, condition) {
  9925. if (condition === void 0) { condition = true; }
  9926. if (!condition) {
  9927. return;
  9928. }
  9929. Tools._StartUserMark(counterName, condition);
  9930. if (console.time) {
  9931. console.time(counterName);
  9932. }
  9933. };
  9934. Tools._EndPerformanceConsole = function (counterName, condition) {
  9935. if (condition === void 0) { condition = true; }
  9936. if (!condition) {
  9937. return;
  9938. }
  9939. Tools._EndUserMark(counterName, condition);
  9940. if (console.time) {
  9941. console.timeEnd(counterName);
  9942. }
  9943. };
  9944. Object.defineProperty(Tools, "Now", {
  9945. get: function () {
  9946. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9947. return window.performance.now();
  9948. }
  9949. return Date.now();
  9950. },
  9951. enumerable: true,
  9952. configurable: true
  9953. });
  9954. /**
  9955. * This method will return the name of the class used to create the instance of the given object.
  9956. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9957. * @param object the object to get the class name from
  9958. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9959. */
  9960. Tools.GetClassName = function (object, isType) {
  9961. if (isType === void 0) { isType = false; }
  9962. var name = null;
  9963. if (!isType && object.getClassName) {
  9964. name = object.getClassName();
  9965. }
  9966. else {
  9967. if (object instanceof Object) {
  9968. var classObj = isType ? object : Object.getPrototypeOf(object);
  9969. name = classObj.constructor["__bjsclassName__"];
  9970. }
  9971. if (!name) {
  9972. name = typeof object;
  9973. }
  9974. }
  9975. return name;
  9976. };
  9977. Tools.First = function (array, predicate) {
  9978. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9979. var el = array_1[_i];
  9980. if (predicate(el)) {
  9981. return el;
  9982. }
  9983. }
  9984. return null;
  9985. };
  9986. /**
  9987. * This method will return the name of the full name of the class, including its owning module (if any).
  9988. * 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).
  9989. * @param object the object to get the class name from
  9990. * @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.
  9991. */
  9992. Tools.getFullClassName = function (object, isType) {
  9993. if (isType === void 0) { isType = false; }
  9994. var className = null;
  9995. var moduleName = null;
  9996. if (!isType && object.getClassName) {
  9997. className = object.getClassName();
  9998. }
  9999. else {
  10000. if (object instanceof Object) {
  10001. var classObj = isType ? object : Object.getPrototypeOf(object);
  10002. className = classObj.constructor["__bjsclassName__"];
  10003. moduleName = classObj.constructor["__bjsmoduleName__"];
  10004. }
  10005. if (!className) {
  10006. className = typeof object;
  10007. }
  10008. }
  10009. if (!className) {
  10010. return null;
  10011. }
  10012. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  10013. };
  10014. /**
  10015. * 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.
  10016. * @param array
  10017. */
  10018. Tools.arrayOrStringFeeder = function (array) {
  10019. return function (index) {
  10020. if (index >= array.length) {
  10021. return null;
  10022. }
  10023. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  10024. if (val && val.getHashCode) {
  10025. val = val.getHashCode();
  10026. }
  10027. if (typeof val === "string") {
  10028. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  10029. }
  10030. return val;
  10031. };
  10032. };
  10033. /**
  10034. * Compute the hashCode of a stream of number
  10035. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  10036. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  10037. * @return the hash code computed
  10038. */
  10039. Tools.hashCodeFromStream = function (feeder) {
  10040. // Based from here: http://stackoverflow.com/a/7616484/802124
  10041. var hash = 0;
  10042. var index = 0;
  10043. var chr = feeder(index++);
  10044. while (chr != null) {
  10045. hash = ((hash << 5) - hash) + chr;
  10046. hash |= 0; // Convert to 32bit integer
  10047. chr = feeder(index++);
  10048. }
  10049. return hash;
  10050. };
  10051. /**
  10052. * Returns a promise that resolves after the given amount of time.
  10053. * @param delay Number of milliseconds to delay
  10054. * @returns Promise that resolves after the given amount of time
  10055. */
  10056. Tools.DelayAsync = function (delay) {
  10057. return new Promise(function (resolve) {
  10058. setTimeout(function () {
  10059. resolve();
  10060. }, delay);
  10061. });
  10062. };
  10063. /**
  10064. * Gets the current gradient from an array of IValueGradient
  10065. * @param ratio defines the current ratio to get
  10066. * @param gradients defines the array of IValueGradient
  10067. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10068. */
  10069. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10070. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10071. var currentGradient = gradients[gradientIndex];
  10072. var nextGradient = gradients[gradientIndex + 1];
  10073. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10074. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10075. updateFunc(currentGradient, nextGradient, scale);
  10076. }
  10077. }
  10078. };
  10079. Tools.BaseUrl = "";
  10080. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10081. /**
  10082. * Default behaviour for cors in the application.
  10083. * It can be a string if the expected behavior is identical in the entire app.
  10084. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10085. */
  10086. Tools.CorsBehavior = "anonymous";
  10087. Tools.UseFallbackTexture = true;
  10088. /**
  10089. * Use this object to register external classes like custom textures or material
  10090. * to allow the laoders to instantiate them
  10091. */
  10092. Tools.RegisteredExternalClasses = {};
  10093. // Used in case of a texture loading problem
  10094. 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";
  10095. Tools._tmpFloatArray = new Float32Array(1);
  10096. Tools.PreprocessUrl = function (url) {
  10097. return url;
  10098. };
  10099. // Logs
  10100. Tools._NoneLogLevel = 0;
  10101. Tools._MessageLogLevel = 1;
  10102. Tools._WarningLogLevel = 2;
  10103. Tools._ErrorLogLevel = 4;
  10104. Tools._LogCache = "";
  10105. Tools.errorsCount = 0;
  10106. Tools.Log = Tools._LogEnabled;
  10107. Tools.Warn = Tools._WarnEnabled;
  10108. Tools.Error = Tools._ErrorEnabled;
  10109. // Performances
  10110. Tools._PerformanceNoneLogLevel = 0;
  10111. Tools._PerformanceUserMarkLogLevel = 1;
  10112. Tools._PerformanceConsoleLogLevel = 2;
  10113. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10114. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10115. return Tools;
  10116. }());
  10117. BABYLON.Tools = Tools;
  10118. /**
  10119. * This class is used to track a performance counter which is number based.
  10120. * The user has access to many properties which give statistics of different nature
  10121. *
  10122. * The implementer can track two kinds of Performance Counter: time and count
  10123. * 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.
  10124. * 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.
  10125. */
  10126. var PerfCounter = /** @class */ (function () {
  10127. function PerfCounter() {
  10128. this._startMonitoringTime = 0;
  10129. this._min = 0;
  10130. this._max = 0;
  10131. this._average = 0;
  10132. this._lastSecAverage = 0;
  10133. this._current = 0;
  10134. this._totalValueCount = 0;
  10135. this._totalAccumulated = 0;
  10136. this._lastSecAccumulated = 0;
  10137. this._lastSecTime = 0;
  10138. this._lastSecValueCount = 0;
  10139. }
  10140. Object.defineProperty(PerfCounter.prototype, "min", {
  10141. /**
  10142. * Returns the smallest value ever
  10143. */
  10144. get: function () {
  10145. return this._min;
  10146. },
  10147. enumerable: true,
  10148. configurable: true
  10149. });
  10150. Object.defineProperty(PerfCounter.prototype, "max", {
  10151. /**
  10152. * Returns the biggest value ever
  10153. */
  10154. get: function () {
  10155. return this._max;
  10156. },
  10157. enumerable: true,
  10158. configurable: true
  10159. });
  10160. Object.defineProperty(PerfCounter.prototype, "average", {
  10161. /**
  10162. * Returns the average value since the performance counter is running
  10163. */
  10164. get: function () {
  10165. return this._average;
  10166. },
  10167. enumerable: true,
  10168. configurable: true
  10169. });
  10170. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10171. /**
  10172. * Returns the average value of the last second the counter was monitored
  10173. */
  10174. get: function () {
  10175. return this._lastSecAverage;
  10176. },
  10177. enumerable: true,
  10178. configurable: true
  10179. });
  10180. Object.defineProperty(PerfCounter.prototype, "current", {
  10181. /**
  10182. * Returns the current value
  10183. */
  10184. get: function () {
  10185. return this._current;
  10186. },
  10187. enumerable: true,
  10188. configurable: true
  10189. });
  10190. Object.defineProperty(PerfCounter.prototype, "total", {
  10191. get: function () {
  10192. return this._totalAccumulated;
  10193. },
  10194. enumerable: true,
  10195. configurable: true
  10196. });
  10197. Object.defineProperty(PerfCounter.prototype, "count", {
  10198. get: function () {
  10199. return this._totalValueCount;
  10200. },
  10201. enumerable: true,
  10202. configurable: true
  10203. });
  10204. /**
  10205. * Call this method to start monitoring a new frame.
  10206. * 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.
  10207. */
  10208. PerfCounter.prototype.fetchNewFrame = function () {
  10209. this._totalValueCount++;
  10210. this._current = 0;
  10211. this._lastSecValueCount++;
  10212. };
  10213. /**
  10214. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10215. * @param newCount the count value to add to the monitored count
  10216. * @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.
  10217. */
  10218. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10219. if (!PerfCounter.Enabled) {
  10220. return;
  10221. }
  10222. this._current += newCount;
  10223. if (fetchResult) {
  10224. this._fetchResult();
  10225. }
  10226. };
  10227. /**
  10228. * Start monitoring this performance counter
  10229. */
  10230. PerfCounter.prototype.beginMonitoring = function () {
  10231. if (!PerfCounter.Enabled) {
  10232. return;
  10233. }
  10234. this._startMonitoringTime = Tools.Now;
  10235. };
  10236. /**
  10237. * Compute the time lapsed since the previous beginMonitoring() call.
  10238. * @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
  10239. */
  10240. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10241. if (newFrame === void 0) { newFrame = true; }
  10242. if (!PerfCounter.Enabled) {
  10243. return;
  10244. }
  10245. if (newFrame) {
  10246. this.fetchNewFrame();
  10247. }
  10248. var currentTime = Tools.Now;
  10249. this._current = currentTime - this._startMonitoringTime;
  10250. if (newFrame) {
  10251. this._fetchResult();
  10252. }
  10253. };
  10254. PerfCounter.prototype._fetchResult = function () {
  10255. this._totalAccumulated += this._current;
  10256. this._lastSecAccumulated += this._current;
  10257. // Min/Max update
  10258. this._min = Math.min(this._min, this._current);
  10259. this._max = Math.max(this._max, this._current);
  10260. this._average = this._totalAccumulated / this._totalValueCount;
  10261. // Reset last sec?
  10262. var now = Tools.Now;
  10263. if ((now - this._lastSecTime) > 1000) {
  10264. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10265. this._lastSecTime = now;
  10266. this._lastSecAccumulated = 0;
  10267. this._lastSecValueCount = 0;
  10268. }
  10269. };
  10270. PerfCounter.Enabled = true;
  10271. return PerfCounter;
  10272. }());
  10273. BABYLON.PerfCounter = PerfCounter;
  10274. /**
  10275. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10276. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10277. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10278. * @param name The name of the class, case should be preserved
  10279. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10280. */
  10281. function className(name, module) {
  10282. return function (target) {
  10283. target["__bjsclassName__"] = name;
  10284. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10285. };
  10286. }
  10287. BABYLON.className = className;
  10288. /**
  10289. * An implementation of a loop for asynchronous functions.
  10290. */
  10291. var AsyncLoop = /** @class */ (function () {
  10292. /**
  10293. * Constroctor.
  10294. * @param iterations the number of iterations.
  10295. * @param _fn the function to run each iteration
  10296. * @param _successCallback the callback that will be called upon succesful execution
  10297. * @param offset starting offset.
  10298. */
  10299. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10300. if (offset === void 0) { offset = 0; }
  10301. this.iterations = iterations;
  10302. this._fn = _fn;
  10303. this._successCallback = _successCallback;
  10304. this.index = offset - 1;
  10305. this._done = false;
  10306. }
  10307. /**
  10308. * Execute the next iteration. Must be called after the last iteration was finished.
  10309. */
  10310. AsyncLoop.prototype.executeNext = function () {
  10311. if (!this._done) {
  10312. if (this.index + 1 < this.iterations) {
  10313. ++this.index;
  10314. this._fn(this);
  10315. }
  10316. else {
  10317. this.breakLoop();
  10318. }
  10319. }
  10320. };
  10321. /**
  10322. * Break the loop and run the success callback.
  10323. */
  10324. AsyncLoop.prototype.breakLoop = function () {
  10325. this._done = true;
  10326. this._successCallback();
  10327. };
  10328. /**
  10329. * Helper function
  10330. */
  10331. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10332. if (offset === void 0) { offset = 0; }
  10333. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10334. loop.executeNext();
  10335. return loop;
  10336. };
  10337. /**
  10338. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10339. * @param iterations total number of iterations
  10340. * @param syncedIterations number of synchronous iterations in each async iteration.
  10341. * @param fn the function to call each iteration.
  10342. * @param callback a success call back that will be called when iterating stops.
  10343. * @param breakFunction a break condition (optional)
  10344. * @param timeout timeout settings for the setTimeout function. default - 0.
  10345. * @constructor
  10346. */
  10347. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10348. if (timeout === void 0) { timeout = 0; }
  10349. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10350. if (breakFunction && breakFunction())
  10351. loop.breakLoop();
  10352. else {
  10353. setTimeout(function () {
  10354. for (var i = 0; i < syncedIterations; ++i) {
  10355. var iteration = (loop.index * syncedIterations) + i;
  10356. if (iteration >= iterations)
  10357. break;
  10358. fn(iteration);
  10359. if (breakFunction && breakFunction()) {
  10360. loop.breakLoop();
  10361. break;
  10362. }
  10363. }
  10364. loop.executeNext();
  10365. }, timeout);
  10366. }
  10367. }, callback);
  10368. };
  10369. return AsyncLoop;
  10370. }());
  10371. BABYLON.AsyncLoop = AsyncLoop;
  10372. })(BABYLON || (BABYLON = {}));
  10373. //# sourceMappingURL=babylon.tools.js.map
  10374. var BABYLON;
  10375. (function (BABYLON) {
  10376. var PromiseStates;
  10377. (function (PromiseStates) {
  10378. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10379. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10380. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10381. })(PromiseStates || (PromiseStates = {}));
  10382. var FulFillmentAgregator = /** @class */ (function () {
  10383. function FulFillmentAgregator() {
  10384. this.count = 0;
  10385. this.target = 0;
  10386. this.results = [];
  10387. }
  10388. return FulFillmentAgregator;
  10389. }());
  10390. var InternalPromise = /** @class */ (function () {
  10391. function InternalPromise(resolver) {
  10392. var _this = this;
  10393. this._state = PromiseStates.Pending;
  10394. this._children = new Array();
  10395. this._rejectWasConsumed = false;
  10396. if (!resolver) {
  10397. return;
  10398. }
  10399. try {
  10400. resolver(function (value) {
  10401. _this._resolve(value);
  10402. }, function (reason) {
  10403. _this._reject(reason);
  10404. });
  10405. }
  10406. catch (e) {
  10407. this._reject(e);
  10408. }
  10409. }
  10410. Object.defineProperty(InternalPromise.prototype, "_result", {
  10411. get: function () {
  10412. return this._resultValue;
  10413. },
  10414. set: function (value) {
  10415. this._resultValue = value;
  10416. if (this._parent && this._parent._result === undefined) {
  10417. this._parent._result = value;
  10418. }
  10419. },
  10420. enumerable: true,
  10421. configurable: true
  10422. });
  10423. InternalPromise.prototype.catch = function (onRejected) {
  10424. return this.then(undefined, onRejected);
  10425. };
  10426. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10427. var _this = this;
  10428. var newPromise = new InternalPromise();
  10429. newPromise._onFulfilled = onFulfilled;
  10430. newPromise._onRejected = onRejected;
  10431. // Composition
  10432. this._children.push(newPromise);
  10433. newPromise._parent = this;
  10434. if (this._state !== PromiseStates.Pending) {
  10435. BABYLON.Tools.SetImmediate(function () {
  10436. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10437. var returnedValue = newPromise._resolve(_this._result);
  10438. if (returnedValue !== undefined && returnedValue !== null) {
  10439. if (returnedValue._state !== undefined) {
  10440. var returnedPromise = returnedValue;
  10441. newPromise._children.push(returnedPromise);
  10442. returnedPromise._parent = newPromise;
  10443. newPromise = returnedPromise;
  10444. }
  10445. else {
  10446. newPromise._result = returnedValue;
  10447. }
  10448. }
  10449. }
  10450. else {
  10451. newPromise._reject(_this._reason);
  10452. }
  10453. });
  10454. }
  10455. return newPromise;
  10456. };
  10457. InternalPromise.prototype._moveChildren = function (children) {
  10458. var _this = this;
  10459. var _a;
  10460. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10461. this._children.forEach(function (child) {
  10462. child._parent = _this;
  10463. });
  10464. if (this._state === PromiseStates.Fulfilled) {
  10465. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10466. var child = _b[_i];
  10467. child._resolve(this._result);
  10468. }
  10469. }
  10470. else if (this._state === PromiseStates.Rejected) {
  10471. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10472. var child = _d[_c];
  10473. child._reject(this._reason);
  10474. }
  10475. }
  10476. };
  10477. InternalPromise.prototype._resolve = function (value) {
  10478. try {
  10479. this._state = PromiseStates.Fulfilled;
  10480. var returnedValue = null;
  10481. if (this._onFulfilled) {
  10482. returnedValue = this._onFulfilled(value);
  10483. }
  10484. if (returnedValue !== undefined && returnedValue !== null) {
  10485. if (returnedValue._state !== undefined) {
  10486. // Transmit children
  10487. var returnedPromise = returnedValue;
  10488. returnedPromise._parent = this;
  10489. returnedPromise._moveChildren(this._children);
  10490. value = returnedPromise._result;
  10491. }
  10492. else {
  10493. value = returnedValue;
  10494. }
  10495. }
  10496. this._result = value;
  10497. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10498. var child = _a[_i];
  10499. child._resolve(value);
  10500. }
  10501. this._children.length = 0;
  10502. delete this._onFulfilled;
  10503. delete this._onRejected;
  10504. }
  10505. catch (e) {
  10506. this._reject(e, true);
  10507. }
  10508. };
  10509. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10510. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10511. this._state = PromiseStates.Rejected;
  10512. this._reason = reason;
  10513. if (this._onRejected && !onLocalThrow) {
  10514. try {
  10515. this._onRejected(reason);
  10516. this._rejectWasConsumed = true;
  10517. }
  10518. catch (e) {
  10519. reason = e;
  10520. }
  10521. }
  10522. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10523. var child = _a[_i];
  10524. if (this._rejectWasConsumed) {
  10525. child._resolve(null);
  10526. }
  10527. else {
  10528. child._reject(reason);
  10529. }
  10530. }
  10531. this._children.length = 0;
  10532. delete this._onFulfilled;
  10533. delete this._onRejected;
  10534. };
  10535. InternalPromise.resolve = function (value) {
  10536. var newPromise = new InternalPromise();
  10537. newPromise._resolve(value);
  10538. return newPromise;
  10539. };
  10540. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10541. promise.then(function (value) {
  10542. agregator.results[index] = value;
  10543. agregator.count++;
  10544. if (agregator.count === agregator.target) {
  10545. agregator.rootPromise._resolve(agregator.results);
  10546. }
  10547. return null;
  10548. }, function (reason) {
  10549. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10550. agregator.rootPromise._reject(reason);
  10551. }
  10552. });
  10553. };
  10554. InternalPromise.all = function (promises) {
  10555. var newPromise = new InternalPromise();
  10556. var agregator = new FulFillmentAgregator();
  10557. agregator.target = promises.length;
  10558. agregator.rootPromise = newPromise;
  10559. if (promises.length) {
  10560. for (var index = 0; index < promises.length; index++) {
  10561. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10562. }
  10563. }
  10564. else {
  10565. newPromise._resolve([]);
  10566. }
  10567. return newPromise;
  10568. };
  10569. InternalPromise.race = function (promises) {
  10570. var newPromise = new InternalPromise();
  10571. if (promises.length) {
  10572. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10573. var promise = promises_1[_i];
  10574. promise.then(function (value) {
  10575. if (newPromise) {
  10576. newPromise._resolve(value);
  10577. newPromise = null;
  10578. }
  10579. return null;
  10580. }, function (reason) {
  10581. if (newPromise) {
  10582. newPromise._reject(reason);
  10583. newPromise = null;
  10584. }
  10585. });
  10586. }
  10587. }
  10588. return newPromise;
  10589. };
  10590. return InternalPromise;
  10591. }());
  10592. /**
  10593. * Helper class that provides a small promise polyfill
  10594. */
  10595. var PromisePolyfill = /** @class */ (function () {
  10596. function PromisePolyfill() {
  10597. }
  10598. /**
  10599. * Static function used to check if the polyfill is required
  10600. * If this is the case then the function will inject the polyfill to window.Promise
  10601. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10602. */
  10603. PromisePolyfill.Apply = function (force) {
  10604. if (force === void 0) { force = false; }
  10605. if (force || typeof Promise === 'undefined') {
  10606. var root = window;
  10607. root.Promise = InternalPromise;
  10608. }
  10609. };
  10610. return PromisePolyfill;
  10611. }());
  10612. BABYLON.PromisePolyfill = PromisePolyfill;
  10613. })(BABYLON || (BABYLON = {}));
  10614. //# sourceMappingURL=babylon.promise.js.map
  10615. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10616. var BABYLON;
  10617. (function (BABYLON) {
  10618. /**
  10619. * Helper class to push actions to a pool of workers.
  10620. */
  10621. var WorkerPool = /** @class */ (function () {
  10622. /**
  10623. * Constructor
  10624. * @param workers Array of workers to use for actions
  10625. */
  10626. function WorkerPool(workers) {
  10627. this._pendingActions = new Array();
  10628. this._workerInfos = workers.map(function (worker) { return ({
  10629. worker: worker,
  10630. active: false
  10631. }); });
  10632. }
  10633. /**
  10634. * Terminates all workers and clears any pending actions.
  10635. */
  10636. WorkerPool.prototype.dispose = function () {
  10637. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10638. var workerInfo = _a[_i];
  10639. workerInfo.worker.terminate();
  10640. }
  10641. delete this._workerInfos;
  10642. delete this._pendingActions;
  10643. };
  10644. /**
  10645. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10646. * pended until a worker has completed its action.
  10647. * @param action The action to perform. Call onComplete when the action is complete.
  10648. */
  10649. WorkerPool.prototype.push = function (action) {
  10650. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10651. var workerInfo = _a[_i];
  10652. if (!workerInfo.active) {
  10653. this._execute(workerInfo, action);
  10654. return;
  10655. }
  10656. }
  10657. this._pendingActions.push(action);
  10658. };
  10659. WorkerPool.prototype._execute = function (workerInfo, action) {
  10660. var _this = this;
  10661. workerInfo.active = true;
  10662. action(workerInfo.worker, function () {
  10663. workerInfo.active = false;
  10664. var nextAction = _this._pendingActions.shift();
  10665. if (nextAction) {
  10666. _this._execute(workerInfo, nextAction);
  10667. }
  10668. });
  10669. };
  10670. return WorkerPool;
  10671. }());
  10672. BABYLON.WorkerPool = WorkerPool;
  10673. })(BABYLON || (BABYLON = {}));
  10674. //# sourceMappingURL=babylon.workerPool.js.map
  10675. var BABYLON;
  10676. (function (BABYLON) {
  10677. /**
  10678. * @hidden
  10679. **/
  10680. var _AlphaState = /** @class */ (function () {
  10681. /**
  10682. * Initializes the state.
  10683. */
  10684. function _AlphaState() {
  10685. this._isAlphaBlendDirty = false;
  10686. this._isBlendFunctionParametersDirty = false;
  10687. this._isBlendEquationParametersDirty = false;
  10688. this._isBlendConstantsDirty = false;
  10689. this._alphaBlend = false;
  10690. this._blendFunctionParameters = new Array(4);
  10691. this._blendEquationParameters = new Array(2);
  10692. this._blendConstants = new Array(4);
  10693. this.reset();
  10694. }
  10695. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10696. get: function () {
  10697. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10698. },
  10699. enumerable: true,
  10700. configurable: true
  10701. });
  10702. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10703. get: function () {
  10704. return this._alphaBlend;
  10705. },
  10706. set: function (value) {
  10707. if (this._alphaBlend === value) {
  10708. return;
  10709. }
  10710. this._alphaBlend = value;
  10711. this._isAlphaBlendDirty = true;
  10712. },
  10713. enumerable: true,
  10714. configurable: true
  10715. });
  10716. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10717. if (this._blendConstants[0] === r &&
  10718. this._blendConstants[1] === g &&
  10719. this._blendConstants[2] === b &&
  10720. this._blendConstants[3] === a) {
  10721. return;
  10722. }
  10723. this._blendConstants[0] = r;
  10724. this._blendConstants[1] = g;
  10725. this._blendConstants[2] = b;
  10726. this._blendConstants[3] = a;
  10727. this._isBlendConstantsDirty = true;
  10728. };
  10729. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10730. if (this._blendFunctionParameters[0] === value0 &&
  10731. this._blendFunctionParameters[1] === value1 &&
  10732. this._blendFunctionParameters[2] === value2 &&
  10733. this._blendFunctionParameters[3] === value3) {
  10734. return;
  10735. }
  10736. this._blendFunctionParameters[0] = value0;
  10737. this._blendFunctionParameters[1] = value1;
  10738. this._blendFunctionParameters[2] = value2;
  10739. this._blendFunctionParameters[3] = value3;
  10740. this._isBlendFunctionParametersDirty = true;
  10741. };
  10742. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10743. if (this._blendEquationParameters[0] === rgb &&
  10744. this._blendEquationParameters[1] === alpha) {
  10745. return;
  10746. }
  10747. this._blendEquationParameters[0] = rgb;
  10748. this._blendEquationParameters[1] = alpha;
  10749. this._isBlendEquationParametersDirty = true;
  10750. };
  10751. _AlphaState.prototype.reset = function () {
  10752. this._alphaBlend = false;
  10753. this._blendFunctionParameters[0] = null;
  10754. this._blendFunctionParameters[1] = null;
  10755. this._blendFunctionParameters[2] = null;
  10756. this._blendFunctionParameters[3] = null;
  10757. this._blendEquationParameters[0] = null;
  10758. this._blendEquationParameters[1] = null;
  10759. this._blendConstants[0] = null;
  10760. this._blendConstants[1] = null;
  10761. this._blendConstants[2] = null;
  10762. this._blendConstants[3] = null;
  10763. this._isAlphaBlendDirty = true;
  10764. this._isBlendFunctionParametersDirty = false;
  10765. this._isBlendEquationParametersDirty = false;
  10766. this._isBlendConstantsDirty = false;
  10767. };
  10768. _AlphaState.prototype.apply = function (gl) {
  10769. if (!this.isDirty) {
  10770. return;
  10771. }
  10772. // Alpha blend
  10773. if (this._isAlphaBlendDirty) {
  10774. if (this._alphaBlend) {
  10775. gl.enable(gl.BLEND);
  10776. }
  10777. else {
  10778. gl.disable(gl.BLEND);
  10779. }
  10780. this._isAlphaBlendDirty = false;
  10781. }
  10782. // Alpha function
  10783. if (this._isBlendFunctionParametersDirty) {
  10784. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10785. this._isBlendFunctionParametersDirty = false;
  10786. }
  10787. // Alpha equation
  10788. if (this._isBlendEquationParametersDirty) {
  10789. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10790. this._isBlendEquationParametersDirty = false;
  10791. }
  10792. // Constants
  10793. if (this._isBlendConstantsDirty) {
  10794. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10795. this._isBlendConstantsDirty = false;
  10796. }
  10797. };
  10798. return _AlphaState;
  10799. }());
  10800. BABYLON._AlphaState = _AlphaState;
  10801. })(BABYLON || (BABYLON = {}));
  10802. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10803. var BABYLON;
  10804. (function (BABYLON) {
  10805. /**
  10806. * @hidden
  10807. **/
  10808. var _DepthCullingState = /** @class */ (function () {
  10809. /**
  10810. * Initializes the state.
  10811. */
  10812. function _DepthCullingState() {
  10813. this._isDepthTestDirty = false;
  10814. this._isDepthMaskDirty = false;
  10815. this._isDepthFuncDirty = false;
  10816. this._isCullFaceDirty = false;
  10817. this._isCullDirty = false;
  10818. this._isZOffsetDirty = false;
  10819. this._isFrontFaceDirty = false;
  10820. this.reset();
  10821. }
  10822. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10823. get: function () {
  10824. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10825. },
  10826. enumerable: true,
  10827. configurable: true
  10828. });
  10829. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10830. get: function () {
  10831. return this._zOffset;
  10832. },
  10833. set: function (value) {
  10834. if (this._zOffset === value) {
  10835. return;
  10836. }
  10837. this._zOffset = value;
  10838. this._isZOffsetDirty = true;
  10839. },
  10840. enumerable: true,
  10841. configurable: true
  10842. });
  10843. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10844. get: function () {
  10845. return this._cullFace;
  10846. },
  10847. set: function (value) {
  10848. if (this._cullFace === value) {
  10849. return;
  10850. }
  10851. this._cullFace = value;
  10852. this._isCullFaceDirty = true;
  10853. },
  10854. enumerable: true,
  10855. configurable: true
  10856. });
  10857. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10858. get: function () {
  10859. return this._cull;
  10860. },
  10861. set: function (value) {
  10862. if (this._cull === value) {
  10863. return;
  10864. }
  10865. this._cull = value;
  10866. this._isCullDirty = true;
  10867. },
  10868. enumerable: true,
  10869. configurable: true
  10870. });
  10871. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10872. get: function () {
  10873. return this._depthFunc;
  10874. },
  10875. set: function (value) {
  10876. if (this._depthFunc === value) {
  10877. return;
  10878. }
  10879. this._depthFunc = value;
  10880. this._isDepthFuncDirty = true;
  10881. },
  10882. enumerable: true,
  10883. configurable: true
  10884. });
  10885. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10886. get: function () {
  10887. return this._depthMask;
  10888. },
  10889. set: function (value) {
  10890. if (this._depthMask === value) {
  10891. return;
  10892. }
  10893. this._depthMask = value;
  10894. this._isDepthMaskDirty = true;
  10895. },
  10896. enumerable: true,
  10897. configurable: true
  10898. });
  10899. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10900. get: function () {
  10901. return this._depthTest;
  10902. },
  10903. set: function (value) {
  10904. if (this._depthTest === value) {
  10905. return;
  10906. }
  10907. this._depthTest = value;
  10908. this._isDepthTestDirty = true;
  10909. },
  10910. enumerable: true,
  10911. configurable: true
  10912. });
  10913. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10914. get: function () {
  10915. return this._frontFace;
  10916. },
  10917. set: function (value) {
  10918. if (this._frontFace === value) {
  10919. return;
  10920. }
  10921. this._frontFace = value;
  10922. this._isFrontFaceDirty = true;
  10923. },
  10924. enumerable: true,
  10925. configurable: true
  10926. });
  10927. _DepthCullingState.prototype.reset = function () {
  10928. this._depthMask = true;
  10929. this._depthTest = true;
  10930. this._depthFunc = null;
  10931. this._cullFace = null;
  10932. this._cull = null;
  10933. this._zOffset = 0;
  10934. this._frontFace = null;
  10935. this._isDepthTestDirty = true;
  10936. this._isDepthMaskDirty = true;
  10937. this._isDepthFuncDirty = false;
  10938. this._isCullFaceDirty = false;
  10939. this._isCullDirty = false;
  10940. this._isZOffsetDirty = false;
  10941. this._isFrontFaceDirty = false;
  10942. };
  10943. _DepthCullingState.prototype.apply = function (gl) {
  10944. if (!this.isDirty) {
  10945. return;
  10946. }
  10947. // Cull
  10948. if (this._isCullDirty) {
  10949. if (this.cull) {
  10950. gl.enable(gl.CULL_FACE);
  10951. }
  10952. else {
  10953. gl.disable(gl.CULL_FACE);
  10954. }
  10955. this._isCullDirty = false;
  10956. }
  10957. // Cull face
  10958. if (this._isCullFaceDirty) {
  10959. gl.cullFace(this.cullFace);
  10960. this._isCullFaceDirty = false;
  10961. }
  10962. // Depth mask
  10963. if (this._isDepthMaskDirty) {
  10964. gl.depthMask(this.depthMask);
  10965. this._isDepthMaskDirty = false;
  10966. }
  10967. // Depth test
  10968. if (this._isDepthTestDirty) {
  10969. if (this.depthTest) {
  10970. gl.enable(gl.DEPTH_TEST);
  10971. }
  10972. else {
  10973. gl.disable(gl.DEPTH_TEST);
  10974. }
  10975. this._isDepthTestDirty = false;
  10976. }
  10977. // Depth func
  10978. if (this._isDepthFuncDirty) {
  10979. gl.depthFunc(this.depthFunc);
  10980. this._isDepthFuncDirty = false;
  10981. }
  10982. // zOffset
  10983. if (this._isZOffsetDirty) {
  10984. if (this.zOffset) {
  10985. gl.enable(gl.POLYGON_OFFSET_FILL);
  10986. gl.polygonOffset(this.zOffset, 0);
  10987. }
  10988. else {
  10989. gl.disable(gl.POLYGON_OFFSET_FILL);
  10990. }
  10991. this._isZOffsetDirty = false;
  10992. }
  10993. // Front face
  10994. if (this._isFrontFaceDirty) {
  10995. gl.frontFace(this.frontFace);
  10996. this._isFrontFaceDirty = false;
  10997. }
  10998. };
  10999. return _DepthCullingState;
  11000. }());
  11001. BABYLON._DepthCullingState = _DepthCullingState;
  11002. })(BABYLON || (BABYLON = {}));
  11003. //# sourceMappingURL=babylon.depthCullingState.js.map
  11004. var BABYLON;
  11005. (function (BABYLON) {
  11006. /**
  11007. * @hidden
  11008. **/
  11009. var _StencilState = /** @class */ (function () {
  11010. function _StencilState() {
  11011. this._isStencilTestDirty = false;
  11012. this._isStencilMaskDirty = false;
  11013. this._isStencilFuncDirty = false;
  11014. this._isStencilOpDirty = false;
  11015. this.reset();
  11016. }
  11017. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11018. get: function () {
  11019. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11020. },
  11021. enumerable: true,
  11022. configurable: true
  11023. });
  11024. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11025. get: function () {
  11026. return this._stencilFunc;
  11027. },
  11028. set: function (value) {
  11029. if (this._stencilFunc === value) {
  11030. return;
  11031. }
  11032. this._stencilFunc = value;
  11033. this._isStencilFuncDirty = true;
  11034. },
  11035. enumerable: true,
  11036. configurable: true
  11037. });
  11038. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11039. get: function () {
  11040. return this._stencilFuncRef;
  11041. },
  11042. set: function (value) {
  11043. if (this._stencilFuncRef === value) {
  11044. return;
  11045. }
  11046. this._stencilFuncRef = value;
  11047. this._isStencilFuncDirty = true;
  11048. },
  11049. enumerable: true,
  11050. configurable: true
  11051. });
  11052. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11053. get: function () {
  11054. return this._stencilFuncMask;
  11055. },
  11056. set: function (value) {
  11057. if (this._stencilFuncMask === value) {
  11058. return;
  11059. }
  11060. this._stencilFuncMask = value;
  11061. this._isStencilFuncDirty = true;
  11062. },
  11063. enumerable: true,
  11064. configurable: true
  11065. });
  11066. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11067. get: function () {
  11068. return this._stencilOpStencilFail;
  11069. },
  11070. set: function (value) {
  11071. if (this._stencilOpStencilFail === value) {
  11072. return;
  11073. }
  11074. this._stencilOpStencilFail = value;
  11075. this._isStencilOpDirty = true;
  11076. },
  11077. enumerable: true,
  11078. configurable: true
  11079. });
  11080. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11081. get: function () {
  11082. return this._stencilOpDepthFail;
  11083. },
  11084. set: function (value) {
  11085. if (this._stencilOpDepthFail === value) {
  11086. return;
  11087. }
  11088. this._stencilOpDepthFail = value;
  11089. this._isStencilOpDirty = true;
  11090. },
  11091. enumerable: true,
  11092. configurable: true
  11093. });
  11094. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11095. get: function () {
  11096. return this._stencilOpStencilDepthPass;
  11097. },
  11098. set: function (value) {
  11099. if (this._stencilOpStencilDepthPass === value) {
  11100. return;
  11101. }
  11102. this._stencilOpStencilDepthPass = value;
  11103. this._isStencilOpDirty = true;
  11104. },
  11105. enumerable: true,
  11106. configurable: true
  11107. });
  11108. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11109. get: function () {
  11110. return this._stencilMask;
  11111. },
  11112. set: function (value) {
  11113. if (this._stencilMask === value) {
  11114. return;
  11115. }
  11116. this._stencilMask = value;
  11117. this._isStencilMaskDirty = true;
  11118. },
  11119. enumerable: true,
  11120. configurable: true
  11121. });
  11122. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11123. get: function () {
  11124. return this._stencilTest;
  11125. },
  11126. set: function (value) {
  11127. if (this._stencilTest === value) {
  11128. return;
  11129. }
  11130. this._stencilTest = value;
  11131. this._isStencilTestDirty = true;
  11132. },
  11133. enumerable: true,
  11134. configurable: true
  11135. });
  11136. _StencilState.prototype.reset = function () {
  11137. this._stencilTest = false;
  11138. this._stencilMask = 0xFF;
  11139. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11140. this._stencilFuncRef = 1;
  11141. this._stencilFuncMask = 0xFF;
  11142. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11143. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11144. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11145. this._isStencilTestDirty = true;
  11146. this._isStencilMaskDirty = true;
  11147. this._isStencilFuncDirty = true;
  11148. this._isStencilOpDirty = true;
  11149. };
  11150. _StencilState.prototype.apply = function (gl) {
  11151. if (!this.isDirty) {
  11152. return;
  11153. }
  11154. // Stencil test
  11155. if (this._isStencilTestDirty) {
  11156. if (this.stencilTest) {
  11157. gl.enable(gl.STENCIL_TEST);
  11158. }
  11159. else {
  11160. gl.disable(gl.STENCIL_TEST);
  11161. }
  11162. this._isStencilTestDirty = false;
  11163. }
  11164. // Stencil mask
  11165. if (this._isStencilMaskDirty) {
  11166. gl.stencilMask(this.stencilMask);
  11167. this._isStencilMaskDirty = false;
  11168. }
  11169. // Stencil func
  11170. if (this._isStencilFuncDirty) {
  11171. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11172. this._isStencilFuncDirty = false;
  11173. }
  11174. // Stencil op
  11175. if (this._isStencilOpDirty) {
  11176. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11177. this._isStencilOpDirty = false;
  11178. }
  11179. };
  11180. return _StencilState;
  11181. }());
  11182. BABYLON._StencilState = _StencilState;
  11183. })(BABYLON || (BABYLON = {}));
  11184. //# sourceMappingURL=babylon.stencilState.js.map
  11185. var __assign = (this && this.__assign) || function () {
  11186. __assign = Object.assign || function(t) {
  11187. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11188. s = arguments[i];
  11189. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11190. t[p] = s[p];
  11191. }
  11192. return t;
  11193. };
  11194. return __assign.apply(this, arguments);
  11195. };
  11196. var BABYLON;
  11197. (function (BABYLON) {
  11198. /**
  11199. * Keeps track of all the buffer info used in engine.
  11200. */
  11201. var BufferPointer = /** @class */ (function () {
  11202. function BufferPointer() {
  11203. }
  11204. return BufferPointer;
  11205. }());
  11206. /**
  11207. * Interface for attribute information associated with buffer instanciation
  11208. */
  11209. var InstancingAttributeInfo = /** @class */ (function () {
  11210. function InstancingAttributeInfo() {
  11211. }
  11212. return InstancingAttributeInfo;
  11213. }());
  11214. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11215. /**
  11216. * Define options used to create a render target texture
  11217. */
  11218. var RenderTargetCreationOptions = /** @class */ (function () {
  11219. function RenderTargetCreationOptions() {
  11220. }
  11221. return RenderTargetCreationOptions;
  11222. }());
  11223. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11224. /**
  11225. * Define options used to create a depth texture
  11226. */
  11227. var DepthTextureCreationOptions = /** @class */ (function () {
  11228. function DepthTextureCreationOptions() {
  11229. }
  11230. return DepthTextureCreationOptions;
  11231. }());
  11232. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11233. /**
  11234. * Class used to describe the capabilities of the engine relatively to the current browser
  11235. */
  11236. var EngineCapabilities = /** @class */ (function () {
  11237. function EngineCapabilities() {
  11238. }
  11239. return EngineCapabilities;
  11240. }());
  11241. BABYLON.EngineCapabilities = EngineCapabilities;
  11242. /**
  11243. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11244. */
  11245. var Engine = /** @class */ (function () {
  11246. /**
  11247. * Creates a new engine
  11248. * @param canvasOrContext defines the canvas or WebGL context to use for rendering. If you provide a WebGL context, Babylon.js will not hook events on the canvas (like pointers, keyboards, etc...) so no event observables will be available. This is mostly used when Babylon.js is used as a plugin on a system which alreay used the WebGL context
  11249. * @param antialias defines enable antialiasing (default: false)
  11250. * @param options defines further options to be sent to the getContext() function
  11251. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11252. */
  11253. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11254. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11255. var _this = this;
  11256. // Public members
  11257. /**
  11258. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11259. */
  11260. this.forcePOTTextures = false;
  11261. /**
  11262. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11263. */
  11264. this.isFullscreen = false;
  11265. /**
  11266. * Gets a boolean indicating if the pointer is currently locked
  11267. */
  11268. this.isPointerLock = false;
  11269. /**
  11270. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11271. */
  11272. this.cullBackFaces = true;
  11273. /**
  11274. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11275. */
  11276. this.renderEvenInBackground = true;
  11277. /**
  11278. * Gets or sets a boolean indicating that cache can be kept between frames
  11279. */
  11280. this.preventCacheWipeBetweenFrames = false;
  11281. /**
  11282. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11283. **/
  11284. this.enableOfflineSupport = false;
  11285. /**
  11286. * 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)
  11287. **/
  11288. this.disableManifestCheck = false;
  11289. /**
  11290. * Gets the list of created scenes
  11291. */
  11292. this.scenes = new Array();
  11293. /**
  11294. * Gets the list of created postprocesses
  11295. */
  11296. this.postProcesses = new Array();
  11297. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  11298. this.validateShaderPrograms = false;
  11299. // Observables
  11300. /**
  11301. * Observable event triggered each time the rendering canvas is resized
  11302. */
  11303. this.onResizeObservable = new BABYLON.Observable();
  11304. /**
  11305. * Observable event triggered each time the canvas loses focus
  11306. */
  11307. this.onCanvasBlurObservable = new BABYLON.Observable();
  11308. /**
  11309. * Observable event triggered each time the canvas gains focus
  11310. */
  11311. this.onCanvasFocusObservable = new BABYLON.Observable();
  11312. /**
  11313. * Observable event triggered each time the canvas receives pointerout event
  11314. */
  11315. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11316. /**
  11317. * Observable event triggered before each texture is initialized
  11318. */
  11319. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11320. //WebVR
  11321. this._vrDisplay = undefined;
  11322. this._vrSupported = false;
  11323. this._vrExclusivePointerMode = false;
  11324. // Uniform buffers list
  11325. /**
  11326. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11327. */
  11328. this.disableUniformBuffers = false;
  11329. /** @hidden */
  11330. this._uniformBuffers = new Array();
  11331. // Observables
  11332. /**
  11333. * Observable raised when the engine begins a new frame
  11334. */
  11335. this.onBeginFrameObservable = new BABYLON.Observable();
  11336. /**
  11337. * Observable raised when the engine ends the current frame
  11338. */
  11339. this.onEndFrameObservable = new BABYLON.Observable();
  11340. /**
  11341. * Observable raised when the engine is about to compile a shader
  11342. */
  11343. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11344. /**
  11345. * Observable raised when the engine has jsut compiled a shader
  11346. */
  11347. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11348. this._windowIsBackground = false;
  11349. this._webGLVersion = 1.0;
  11350. /** @hidden */
  11351. this._badOS = false;
  11352. /** @hidden */
  11353. this._badDesktopOS = false;
  11354. /**
  11355. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11356. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11357. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11358. */
  11359. this.disableTextureBindingOptimization = false;
  11360. /**
  11361. * Observable signaled when VR display mode changes
  11362. */
  11363. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11364. /**
  11365. * Observable signaled when VR request present is complete
  11366. */
  11367. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11368. /**
  11369. * Observable signaled when VR request present starts
  11370. */
  11371. this.onVRRequestPresentStart = new BABYLON.Observable();
  11372. this._colorWrite = true;
  11373. /** @hidden */
  11374. this._drawCalls = new BABYLON.PerfCounter();
  11375. /** @hidden */
  11376. this._textureCollisions = new BABYLON.PerfCounter();
  11377. this._renderingQueueLaunched = false;
  11378. this._activeRenderLoops = new Array();
  11379. // Deterministic lockstepMaxSteps
  11380. this._deterministicLockstep = false;
  11381. this._lockstepMaxSteps = 4;
  11382. // Lost context
  11383. /**
  11384. * Observable signaled when a context lost event is raised
  11385. */
  11386. this.onContextLostObservable = new BABYLON.Observable();
  11387. /**
  11388. * Observable signaled when a context restored event is raised
  11389. */
  11390. this.onContextRestoredObservable = new BABYLON.Observable();
  11391. this._contextWasLost = false;
  11392. this._doNotHandleContextLost = false;
  11393. // FPS
  11394. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11395. this._fps = 60;
  11396. this._deltaTime = 0;
  11397. /**
  11398. * Turn this value on if you want to pause FPS computation when in background
  11399. */
  11400. this.disablePerformanceMonitorInBackground = false;
  11401. // States
  11402. /** @hidden */
  11403. this._depthCullingState = new BABYLON._DepthCullingState();
  11404. /** @hidden */
  11405. this._stencilState = new BABYLON._StencilState();
  11406. /** @hidden */
  11407. this._alphaState = new BABYLON._AlphaState();
  11408. /** @hidden */
  11409. this._alphaMode = Engine.ALPHA_DISABLE;
  11410. // Cache
  11411. this._internalTexturesCache = new Array();
  11412. /** @hidden */
  11413. this._activeChannel = 0;
  11414. this._currentTextureChannel = -1;
  11415. /** @hidden */
  11416. this._boundTexturesCache = {};
  11417. this._compiledEffects = {};
  11418. this._vertexAttribArraysEnabled = [];
  11419. this._uintIndicesCurrentlySet = false;
  11420. this._currentBoundBuffer = new Array();
  11421. /** @hidden */
  11422. this._currentFramebuffer = null;
  11423. this._currentBufferPointers = new Array();
  11424. this._currentInstanceLocations = new Array();
  11425. this._currentInstanceBuffers = new Array();
  11426. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11427. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11428. this._vaoRecordInProgress = false;
  11429. this._mustWipeVertexAttributes = false;
  11430. this._nextFreeTextureSlots = new Array();
  11431. this._maxSimultaneousTextures = 0;
  11432. this._activeRequests = new Array();
  11433. // Hardware supported Compressed Textures
  11434. this._texturesSupported = new Array();
  11435. /**
  11436. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11437. */
  11438. this.premultipliedAlpha = true;
  11439. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11440. this._onVRFullScreenTriggered = function () {
  11441. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11442. //get the old size before we change
  11443. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11444. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11445. //get the width and height, change the render size
  11446. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11447. _this.setHardwareScalingLevel(1);
  11448. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11449. }
  11450. else {
  11451. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11452. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11453. }
  11454. };
  11455. this._unpackFlipYCached = null;
  11456. this._boundUniforms = {};
  11457. // Register promises
  11458. BABYLON.PromisePolyfill.Apply();
  11459. var canvas = null;
  11460. Engine.Instances.push(this);
  11461. if (!canvasOrContext) {
  11462. return;
  11463. }
  11464. options = options || {};
  11465. if (canvasOrContext.getContext) {
  11466. canvas = canvasOrContext;
  11467. this._renderingCanvas = canvas;
  11468. if (antialias != null) {
  11469. options.antialias = antialias;
  11470. }
  11471. if (options.deterministicLockstep === undefined) {
  11472. options.deterministicLockstep = false;
  11473. }
  11474. if (options.lockstepMaxSteps === undefined) {
  11475. options.lockstepMaxSteps = 4;
  11476. }
  11477. if (options.preserveDrawingBuffer === undefined) {
  11478. options.preserveDrawingBuffer = false;
  11479. }
  11480. if (options.audioEngine === undefined) {
  11481. options.audioEngine = true;
  11482. }
  11483. if (options.stencil === undefined) {
  11484. options.stencil = true;
  11485. }
  11486. if (options.premultipliedAlpha === false) {
  11487. this.premultipliedAlpha = false;
  11488. }
  11489. this._deterministicLockstep = options.deterministicLockstep;
  11490. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11491. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11492. // Exceptions
  11493. if (navigator && navigator.userAgent) {
  11494. var ua = navigator.userAgent;
  11495. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11496. var exception = _a[_i];
  11497. var key = exception.key;
  11498. var targets = exception.targets;
  11499. if (ua.indexOf(key) > -1) {
  11500. if (exception.capture && exception.captureConstraint) {
  11501. var capture = exception.capture;
  11502. var constraint = exception.captureConstraint;
  11503. var regex = new RegExp(capture);
  11504. var matches = regex.exec(ua);
  11505. if (matches && matches.length > 0) {
  11506. var capturedValue = parseInt(matches[matches.length - 1]);
  11507. if (capturedValue >= constraint) {
  11508. continue;
  11509. }
  11510. }
  11511. }
  11512. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11513. var target = targets_1[_b];
  11514. switch (target) {
  11515. case "uniformBuffer":
  11516. this.disableUniformBuffers = true;
  11517. break;
  11518. case "textureBindingOptimization":
  11519. this.disableTextureBindingOptimization = true;
  11520. break;
  11521. }
  11522. }
  11523. }
  11524. }
  11525. }
  11526. // GL
  11527. if (!options.disableWebGL2Support) {
  11528. try {
  11529. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11530. if (this._gl) {
  11531. this._webGLVersion = 2.0;
  11532. }
  11533. }
  11534. catch (e) {
  11535. // Do nothing
  11536. }
  11537. }
  11538. if (!this._gl) {
  11539. if (!canvas) {
  11540. throw new Error("The provided canvas is null or undefined.");
  11541. }
  11542. try {
  11543. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11544. }
  11545. catch (e) {
  11546. throw new Error("WebGL not supported");
  11547. }
  11548. }
  11549. if (!this._gl) {
  11550. throw new Error("WebGL not supported");
  11551. }
  11552. this._onCanvasFocus = function () {
  11553. _this.onCanvasFocusObservable.notifyObservers(_this);
  11554. };
  11555. this._onCanvasBlur = function () {
  11556. _this.onCanvasBlurObservable.notifyObservers(_this);
  11557. };
  11558. canvas.addEventListener("focus", this._onCanvasFocus);
  11559. canvas.addEventListener("blur", this._onCanvasBlur);
  11560. this._onBlur = function () {
  11561. if (_this.disablePerformanceMonitorInBackground) {
  11562. _this._performanceMonitor.disable();
  11563. }
  11564. _this._windowIsBackground = true;
  11565. };
  11566. this._onFocus = function () {
  11567. if (_this.disablePerformanceMonitorInBackground) {
  11568. _this._performanceMonitor.enable();
  11569. }
  11570. _this._windowIsBackground = false;
  11571. };
  11572. this._onCanvasPointerOut = function (ev) {
  11573. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11574. };
  11575. window.addEventListener("blur", this._onBlur);
  11576. window.addEventListener("focus", this._onFocus);
  11577. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11578. // Context lost
  11579. if (!this._doNotHandleContextLost) {
  11580. this._onContextLost = function (evt) {
  11581. evt.preventDefault();
  11582. _this._contextWasLost = true;
  11583. BABYLON.Tools.Warn("WebGL context lost.");
  11584. _this.onContextLostObservable.notifyObservers(_this);
  11585. };
  11586. this._onContextRestored = function (evt) {
  11587. // Adding a timeout to avoid race condition at browser level
  11588. setTimeout(function () {
  11589. // Rebuild gl context
  11590. _this._initGLContext();
  11591. // Rebuild effects
  11592. _this._rebuildEffects();
  11593. // Rebuild textures
  11594. _this._rebuildInternalTextures();
  11595. // Rebuild buffers
  11596. _this._rebuildBuffers();
  11597. // Cache
  11598. _this.wipeCaches(true);
  11599. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11600. _this.onContextRestoredObservable.notifyObservers(_this);
  11601. _this._contextWasLost = false;
  11602. }, 0);
  11603. };
  11604. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11605. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11606. }
  11607. }
  11608. else {
  11609. this._gl = canvasOrContext;
  11610. this._renderingCanvas = this._gl.canvas;
  11611. if (this._gl.renderbufferStorageMultisample) {
  11612. this._webGLVersion = 2.0;
  11613. }
  11614. options.stencil = this._gl.getContextAttributes().stencil;
  11615. }
  11616. // Viewport
  11617. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11618. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11619. this.resize();
  11620. this._isStencilEnable = options.stencil ? true : false;
  11621. this._initGLContext();
  11622. if (canvas) {
  11623. // Fullscreen
  11624. this._onFullscreenChange = function () {
  11625. if (document.fullscreen !== undefined) {
  11626. _this.isFullscreen = document.fullscreen;
  11627. }
  11628. else if (document.mozFullScreen !== undefined) {
  11629. _this.isFullscreen = document.mozFullScreen;
  11630. }
  11631. else if (document.webkitIsFullScreen !== undefined) {
  11632. _this.isFullscreen = document.webkitIsFullScreen;
  11633. }
  11634. else if (document.msIsFullScreen !== undefined) {
  11635. _this.isFullscreen = document.msIsFullScreen;
  11636. }
  11637. // Pointer lock
  11638. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11639. canvas.requestPointerLock = canvas.requestPointerLock ||
  11640. canvas.msRequestPointerLock ||
  11641. canvas.mozRequestPointerLock ||
  11642. canvas.webkitRequestPointerLock;
  11643. if (canvas.requestPointerLock) {
  11644. canvas.requestPointerLock();
  11645. }
  11646. }
  11647. };
  11648. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11649. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11650. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11651. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11652. // Pointer lock
  11653. this._onPointerLockChange = function () {
  11654. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11655. document.webkitPointerLockElement === canvas ||
  11656. document.msPointerLockElement === canvas ||
  11657. document.pointerLockElement === canvas);
  11658. };
  11659. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11660. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11661. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11662. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11663. this._onVRDisplayPointerRestricted = function () {
  11664. if (canvas) {
  11665. canvas.requestPointerLock();
  11666. }
  11667. };
  11668. this._onVRDisplayPointerUnrestricted = function () {
  11669. document.exitPointerLock();
  11670. };
  11671. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11672. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11673. }
  11674. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11675. Engine.audioEngine = new BABYLON.AudioEngine();
  11676. }
  11677. // Prepare buffer pointers
  11678. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11679. this._currentBufferPointers[i] = new BufferPointer();
  11680. }
  11681. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11682. // Load WebVR Devices
  11683. if (options.autoEnableWebVR) {
  11684. this.initWebVR();
  11685. }
  11686. // Detect if we are running on a faulty buggy OS.
  11687. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11688. // Detect if we are running on a faulty buggy desktop OS.
  11689. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11690. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11691. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11692. }
  11693. Object.defineProperty(Engine, "LastCreatedEngine", {
  11694. /**
  11695. * Gets the latest created engine
  11696. */
  11697. get: function () {
  11698. if (Engine.Instances.length === 0) {
  11699. return null;
  11700. }
  11701. return Engine.Instances[Engine.Instances.length - 1];
  11702. },
  11703. enumerable: true,
  11704. configurable: true
  11705. });
  11706. Object.defineProperty(Engine, "LastCreatedScene", {
  11707. /**
  11708. * Gets the latest created scene
  11709. */
  11710. get: function () {
  11711. var lastCreatedEngine = Engine.LastCreatedEngine;
  11712. if (!lastCreatedEngine) {
  11713. return null;
  11714. }
  11715. if (lastCreatedEngine.scenes.length === 0) {
  11716. return null;
  11717. }
  11718. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11719. },
  11720. enumerable: true,
  11721. configurable: true
  11722. });
  11723. /**
  11724. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11725. * @param flag defines which part of the materials must be marked as dirty
  11726. * @param predicate defines a predicate used to filter which materials should be affected
  11727. */
  11728. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11729. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11730. var engine = Engine.Instances[engineIndex];
  11731. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11732. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11733. }
  11734. }
  11735. };
  11736. Object.defineProperty(Engine, "Version", {
  11737. /**
  11738. * Returns the current version of the framework
  11739. */
  11740. get: function () {
  11741. return "3.3.0-alpha.15";
  11742. },
  11743. enumerable: true,
  11744. configurable: true
  11745. });
  11746. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11747. /**
  11748. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11749. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11750. */
  11751. get: function () {
  11752. return this._vrExclusivePointerMode;
  11753. },
  11754. enumerable: true,
  11755. configurable: true
  11756. });
  11757. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11758. /**
  11759. * Gets a boolean indicating that the engine supports uniform buffers
  11760. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11761. */
  11762. get: function () {
  11763. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11764. },
  11765. enumerable: true,
  11766. configurable: true
  11767. });
  11768. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11769. /**
  11770. * Gets a boolean indicating that only power of 2 textures are supported
  11771. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11772. */
  11773. get: function () {
  11774. return this._webGLVersion < 2 || this.forcePOTTextures;
  11775. },
  11776. enumerable: true,
  11777. configurable: true
  11778. });
  11779. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  11780. /**
  11781. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  11782. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  11783. */
  11784. get: function () {
  11785. return this._doNotHandleContextLost;
  11786. },
  11787. set: function (value) {
  11788. this._doNotHandleContextLost = value;
  11789. },
  11790. enumerable: true,
  11791. configurable: true
  11792. });
  11793. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11794. /**
  11795. * Gets the performance monitor attached to this engine
  11796. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11797. */
  11798. get: function () {
  11799. return this._performanceMonitor;
  11800. },
  11801. enumerable: true,
  11802. configurable: true
  11803. });
  11804. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11805. /**
  11806. * Gets the list of texture formats supported
  11807. */
  11808. get: function () {
  11809. return this._texturesSupported;
  11810. },
  11811. enumerable: true,
  11812. configurable: true
  11813. });
  11814. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11815. /**
  11816. * Gets the list of texture formats in use
  11817. */
  11818. get: function () {
  11819. return this._textureFormatInUse;
  11820. },
  11821. enumerable: true,
  11822. configurable: true
  11823. });
  11824. Object.defineProperty(Engine.prototype, "currentViewport", {
  11825. /**
  11826. * Gets the current viewport
  11827. */
  11828. get: function () {
  11829. return this._cachedViewport;
  11830. },
  11831. enumerable: true,
  11832. configurable: true
  11833. });
  11834. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11835. /**
  11836. * Gets the default empty texture
  11837. */
  11838. get: function () {
  11839. if (!this._emptyTexture) {
  11840. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11841. }
  11842. return this._emptyTexture;
  11843. },
  11844. enumerable: true,
  11845. configurable: true
  11846. });
  11847. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11848. /**
  11849. * Gets the default empty 3D texture
  11850. */
  11851. get: function () {
  11852. if (!this._emptyTexture3D) {
  11853. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11854. }
  11855. return this._emptyTexture3D;
  11856. },
  11857. enumerable: true,
  11858. configurable: true
  11859. });
  11860. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11861. /**
  11862. * Gets the default empty cube texture
  11863. */
  11864. get: function () {
  11865. if (!this._emptyCubeTexture) {
  11866. var faceData = new Uint8Array(4);
  11867. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11868. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  11869. }
  11870. return this._emptyCubeTexture;
  11871. },
  11872. enumerable: true,
  11873. configurable: true
  11874. });
  11875. Engine.prototype._rebuildInternalTextures = function () {
  11876. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11877. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11878. var internalTexture = currentState_1[_i];
  11879. internalTexture._rebuild();
  11880. }
  11881. };
  11882. Engine.prototype._rebuildEffects = function () {
  11883. for (var key in this._compiledEffects) {
  11884. var effect = this._compiledEffects[key];
  11885. effect._prepareEffect();
  11886. }
  11887. BABYLON.Effect.ResetCache();
  11888. };
  11889. Engine.prototype._rebuildBuffers = function () {
  11890. // Index / Vertex
  11891. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11892. var scene = _a[_i];
  11893. scene.resetCachedMaterial();
  11894. scene._rebuildGeometries();
  11895. scene._rebuildTextures();
  11896. }
  11897. // Uniforms
  11898. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11899. var uniformBuffer = _c[_b];
  11900. uniformBuffer._rebuild();
  11901. }
  11902. };
  11903. Engine.prototype._initGLContext = function () {
  11904. // Caps
  11905. this._caps = new EngineCapabilities();
  11906. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11907. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11908. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11909. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11910. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11911. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11912. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11913. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11914. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11915. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11916. // Infos
  11917. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11918. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11919. if (rendererInfo != null) {
  11920. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11921. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11922. }
  11923. if (!this._glVendor) {
  11924. this._glVendor = "Unknown vendor";
  11925. }
  11926. if (!this._glRenderer) {
  11927. this._glRenderer = "Unknown renderer";
  11928. }
  11929. // Constants
  11930. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11931. if (this._gl.RGBA16F !== 0x881A) {
  11932. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11933. }
  11934. if (this._gl.RGBA32F !== 0x8814) {
  11935. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11936. }
  11937. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11938. this._gl.DEPTH24_STENCIL8 = 35056;
  11939. }
  11940. // Extensions
  11941. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11942. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11943. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11944. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11945. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11946. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11947. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11948. 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');
  11949. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11950. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11951. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11952. this._caps.highPrecisionShaderSupported = true;
  11953. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11954. if (this._caps.timerQuery) {
  11955. if (this._webGLVersion === 1) {
  11956. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11957. }
  11958. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11959. }
  11960. // Checks if some of the format renders first to allow the use of webgl inspector.
  11961. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11962. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11963. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11964. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11965. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11966. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11967. if (this._webGLVersion > 1) {
  11968. this._gl.HALF_FLOAT_OES = 0x140B;
  11969. }
  11970. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11971. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11972. // Draw buffers
  11973. if (this._webGLVersion > 1) {
  11974. this._caps.drawBuffersExtension = true;
  11975. }
  11976. else {
  11977. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11978. if (drawBuffersExtension !== null) {
  11979. this._caps.drawBuffersExtension = true;
  11980. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11981. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11982. for (var i = 0; i < 16; i++) {
  11983. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11984. }
  11985. }
  11986. else {
  11987. this._caps.drawBuffersExtension = false;
  11988. }
  11989. }
  11990. // Depth Texture
  11991. if (this._webGLVersion > 1) {
  11992. this._caps.depthTextureExtension = true;
  11993. }
  11994. else {
  11995. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11996. if (depthTextureExtension != null) {
  11997. this._caps.depthTextureExtension = true;
  11998. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11999. }
  12000. }
  12001. // Vertex array object
  12002. if (this._webGLVersion > 1) {
  12003. this._caps.vertexArrayObject = true;
  12004. }
  12005. else {
  12006. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12007. if (vertexArrayObjectExtension != null) {
  12008. this._caps.vertexArrayObject = true;
  12009. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12010. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12011. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12012. }
  12013. else {
  12014. this._caps.vertexArrayObject = false;
  12015. }
  12016. }
  12017. // Instances count
  12018. if (this._webGLVersion > 1) {
  12019. this._caps.instancedArrays = true;
  12020. }
  12021. else {
  12022. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12023. if (instanceExtension != null) {
  12024. this._caps.instancedArrays = true;
  12025. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12026. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12027. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12028. }
  12029. else {
  12030. this._caps.instancedArrays = false;
  12031. }
  12032. }
  12033. // Intelligently add supported compressed formats in order to check for.
  12034. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12035. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12036. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12037. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12038. if (this._caps.astc)
  12039. this.texturesSupported.push('-astc.ktx');
  12040. if (this._caps.s3tc)
  12041. this.texturesSupported.push('-dxt.ktx');
  12042. if (this._caps.pvrtc)
  12043. this.texturesSupported.push('-pvrtc.ktx');
  12044. if (this._caps.etc2)
  12045. this.texturesSupported.push('-etc2.ktx');
  12046. if (this._caps.etc1)
  12047. this.texturesSupported.push('-etc1.ktx');
  12048. if (this._gl.getShaderPrecisionFormat) {
  12049. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12050. if (highp) {
  12051. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12052. }
  12053. }
  12054. // Depth buffer
  12055. this.setDepthBuffer(true);
  12056. this.setDepthFunctionToLessOrEqual();
  12057. this.setDepthWrite(true);
  12058. // Texture maps
  12059. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12060. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12061. this._nextFreeTextureSlots.push(slot);
  12062. }
  12063. };
  12064. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12065. /**
  12066. * Gets version of the current webGL context
  12067. */
  12068. get: function () {
  12069. return this._webGLVersion;
  12070. },
  12071. enumerable: true,
  12072. configurable: true
  12073. });
  12074. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12075. /**
  12076. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12077. */
  12078. get: function () {
  12079. return this._isStencilEnable;
  12080. },
  12081. enumerable: true,
  12082. configurable: true
  12083. });
  12084. Engine.prototype._prepareWorkingCanvas = function () {
  12085. if (this._workingCanvas) {
  12086. return;
  12087. }
  12088. this._workingCanvas = document.createElement("canvas");
  12089. var context = this._workingCanvas.getContext("2d");
  12090. if (context) {
  12091. this._workingContext = context;
  12092. }
  12093. };
  12094. /**
  12095. * Reset the texture cache to empty state
  12096. */
  12097. Engine.prototype.resetTextureCache = function () {
  12098. for (var key in this._boundTexturesCache) {
  12099. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12100. continue;
  12101. }
  12102. var boundTexture = this._boundTexturesCache[key];
  12103. if (boundTexture) {
  12104. this._removeDesignatedSlot(boundTexture);
  12105. }
  12106. this._boundTexturesCache[key] = null;
  12107. }
  12108. if (!this.disableTextureBindingOptimization) {
  12109. this._nextFreeTextureSlots = [];
  12110. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12111. this._nextFreeTextureSlots.push(slot);
  12112. }
  12113. }
  12114. this._currentTextureChannel = -1;
  12115. };
  12116. /**
  12117. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12118. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12119. * @returns true if engine is in deterministic lock step mode
  12120. */
  12121. Engine.prototype.isDeterministicLockStep = function () {
  12122. return this._deterministicLockstep;
  12123. };
  12124. /**
  12125. * Gets the max steps when engine is running in deterministic lock step
  12126. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12127. * @returns the max steps
  12128. */
  12129. Engine.prototype.getLockstepMaxSteps = function () {
  12130. return this._lockstepMaxSteps;
  12131. };
  12132. /**
  12133. * Gets an object containing information about the current webGL context
  12134. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12135. */
  12136. Engine.prototype.getGlInfo = function () {
  12137. return {
  12138. vendor: this._glVendor,
  12139. renderer: this._glRenderer,
  12140. version: this._glVersion
  12141. };
  12142. };
  12143. /**
  12144. * Gets current aspect ratio
  12145. * @param camera defines the camera to use to get the aspect ratio
  12146. * @param useScreen defines if screen size must be used (or the current render target if any)
  12147. * @returns a number defining the aspect ratio
  12148. */
  12149. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12150. if (useScreen === void 0) { useScreen = false; }
  12151. var viewport = camera.viewport;
  12152. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12153. };
  12154. /**
  12155. * Gets current screen aspect ratio
  12156. * @returns a number defining the aspect ratio
  12157. */
  12158. Engine.prototype.getScreenAspectRatio = function () {
  12159. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12160. };
  12161. /**
  12162. * Gets the current render width
  12163. * @param useScreen defines if screen size must be used (or the current render target if any)
  12164. * @returns a number defining the current render width
  12165. */
  12166. Engine.prototype.getRenderWidth = function (useScreen) {
  12167. if (useScreen === void 0) { useScreen = false; }
  12168. if (!useScreen && this._currentRenderTarget) {
  12169. return this._currentRenderTarget.width;
  12170. }
  12171. return this._gl.drawingBufferWidth;
  12172. };
  12173. /**
  12174. * Gets the current render height
  12175. * @param useScreen defines if screen size must be used (or the current render target if any)
  12176. * @returns a number defining the current render height
  12177. */
  12178. Engine.prototype.getRenderHeight = function (useScreen) {
  12179. if (useScreen === void 0) { useScreen = false; }
  12180. if (!useScreen && this._currentRenderTarget) {
  12181. return this._currentRenderTarget.height;
  12182. }
  12183. return this._gl.drawingBufferHeight;
  12184. };
  12185. /**
  12186. * Gets the HTML canvas attached with the current webGL context
  12187. * @returns a HTML canvas
  12188. */
  12189. Engine.prototype.getRenderingCanvas = function () {
  12190. return this._renderingCanvas;
  12191. };
  12192. /**
  12193. * Gets the client rect of the HTML canvas attached with the current webGL context
  12194. * @returns a client rectanglee
  12195. */
  12196. Engine.prototype.getRenderingCanvasClientRect = function () {
  12197. if (!this._renderingCanvas) {
  12198. return null;
  12199. }
  12200. return this._renderingCanvas.getBoundingClientRect();
  12201. };
  12202. /**
  12203. * Defines the hardware scaling level.
  12204. * By default the hardware scaling level is computed from the window device ratio.
  12205. * 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.
  12206. * @param level defines the level to use
  12207. */
  12208. Engine.prototype.setHardwareScalingLevel = function (level) {
  12209. this._hardwareScalingLevel = level;
  12210. this.resize();
  12211. };
  12212. /**
  12213. * Gets the current hardware scaling level.
  12214. * By default the hardware scaling level is computed from the window device ratio.
  12215. * 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.
  12216. * @returns a number indicating the current hardware scaling level
  12217. */
  12218. Engine.prototype.getHardwareScalingLevel = function () {
  12219. return this._hardwareScalingLevel;
  12220. };
  12221. /**
  12222. * Gets the list of loaded textures
  12223. * @returns an array containing all loaded textures
  12224. */
  12225. Engine.prototype.getLoadedTexturesCache = function () {
  12226. return this._internalTexturesCache;
  12227. };
  12228. /**
  12229. * Gets the object containing all engine capabilities
  12230. * @returns the EngineCapabilities object
  12231. */
  12232. Engine.prototype.getCaps = function () {
  12233. return this._caps;
  12234. };
  12235. Object.defineProperty(Engine.prototype, "drawCalls", {
  12236. /** @hidden */
  12237. get: function () {
  12238. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12239. return 0;
  12240. },
  12241. enumerable: true,
  12242. configurable: true
  12243. });
  12244. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12245. /** @hidden */
  12246. get: function () {
  12247. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12248. return null;
  12249. },
  12250. enumerable: true,
  12251. configurable: true
  12252. });
  12253. /**
  12254. * Gets the current depth function
  12255. * @returns a number defining the depth function
  12256. */
  12257. Engine.prototype.getDepthFunction = function () {
  12258. return this._depthCullingState.depthFunc;
  12259. };
  12260. /**
  12261. * Sets the current depth function
  12262. * @param depthFunc defines the function to use
  12263. */
  12264. Engine.prototype.setDepthFunction = function (depthFunc) {
  12265. this._depthCullingState.depthFunc = depthFunc;
  12266. };
  12267. /**
  12268. * Sets the current depth function to GREATER
  12269. */
  12270. Engine.prototype.setDepthFunctionToGreater = function () {
  12271. this._depthCullingState.depthFunc = this._gl.GREATER;
  12272. };
  12273. /**
  12274. * Sets the current depth function to GEQUAL
  12275. */
  12276. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12277. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12278. };
  12279. /**
  12280. * Sets the current depth function to LESS
  12281. */
  12282. Engine.prototype.setDepthFunctionToLess = function () {
  12283. this._depthCullingState.depthFunc = this._gl.LESS;
  12284. };
  12285. /**
  12286. * Sets the current depth function to LEQUAL
  12287. */
  12288. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12289. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12290. };
  12291. /**
  12292. * Gets a boolean indicating if stencil buffer is enabled
  12293. * @returns the current stencil buffer state
  12294. */
  12295. Engine.prototype.getStencilBuffer = function () {
  12296. return this._stencilState.stencilTest;
  12297. };
  12298. /**
  12299. * Enable or disable the stencil buffer
  12300. * @param enable defines if the stencil buffer must be enabled or disabled
  12301. */
  12302. Engine.prototype.setStencilBuffer = function (enable) {
  12303. this._stencilState.stencilTest = enable;
  12304. };
  12305. /**
  12306. * Gets the current stencil mask
  12307. * @returns a number defining the new stencil mask to use
  12308. */
  12309. Engine.prototype.getStencilMask = function () {
  12310. return this._stencilState.stencilMask;
  12311. };
  12312. /**
  12313. * Sets the current stencil mask
  12314. * @param mask defines the new stencil mask to use
  12315. */
  12316. Engine.prototype.setStencilMask = function (mask) {
  12317. this._stencilState.stencilMask = mask;
  12318. };
  12319. /**
  12320. * Gets the current stencil function
  12321. * @returns a number defining the stencil function to use
  12322. */
  12323. Engine.prototype.getStencilFunction = function () {
  12324. return this._stencilState.stencilFunc;
  12325. };
  12326. /**
  12327. * Gets the current stencil reference value
  12328. * @returns a number defining the stencil reference value to use
  12329. */
  12330. Engine.prototype.getStencilFunctionReference = function () {
  12331. return this._stencilState.stencilFuncRef;
  12332. };
  12333. /**
  12334. * Gets the current stencil mask
  12335. * @returns a number defining the stencil mask to use
  12336. */
  12337. Engine.prototype.getStencilFunctionMask = function () {
  12338. return this._stencilState.stencilFuncMask;
  12339. };
  12340. /**
  12341. * Sets the current stencil function
  12342. * @param stencilFunc defines the new stencil function to use
  12343. */
  12344. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12345. this._stencilState.stencilFunc = stencilFunc;
  12346. };
  12347. /**
  12348. * Sets the current stencil reference
  12349. * @param reference defines the new stencil reference to use
  12350. */
  12351. Engine.prototype.setStencilFunctionReference = function (reference) {
  12352. this._stencilState.stencilFuncRef = reference;
  12353. };
  12354. /**
  12355. * Sets the current stencil mask
  12356. * @param mask defines the new stencil mask to use
  12357. */
  12358. Engine.prototype.setStencilFunctionMask = function (mask) {
  12359. this._stencilState.stencilFuncMask = mask;
  12360. };
  12361. /**
  12362. * Gets the current stencil operation when stencil fails
  12363. * @returns a number defining stencil operation to use when stencil fails
  12364. */
  12365. Engine.prototype.getStencilOperationFail = function () {
  12366. return this._stencilState.stencilOpStencilFail;
  12367. };
  12368. /**
  12369. * Gets the current stencil operation when depth fails
  12370. * @returns a number defining stencil operation to use when depth fails
  12371. */
  12372. Engine.prototype.getStencilOperationDepthFail = function () {
  12373. return this._stencilState.stencilOpDepthFail;
  12374. };
  12375. /**
  12376. * Gets the current stencil operation when stencil passes
  12377. * @returns a number defining stencil operation to use when stencil passes
  12378. */
  12379. Engine.prototype.getStencilOperationPass = function () {
  12380. return this._stencilState.stencilOpStencilDepthPass;
  12381. };
  12382. /**
  12383. * Sets the stencil operation to use when stencil fails
  12384. * @param operation defines the stencil operation to use when stencil fails
  12385. */
  12386. Engine.prototype.setStencilOperationFail = function (operation) {
  12387. this._stencilState.stencilOpStencilFail = operation;
  12388. };
  12389. /**
  12390. * Sets the stencil operation to use when depth fails
  12391. * @param operation defines the stencil operation to use when depth fails
  12392. */
  12393. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12394. this._stencilState.stencilOpDepthFail = operation;
  12395. };
  12396. /**
  12397. * Sets the stencil operation to use when stencil passes
  12398. * @param operation defines the stencil operation to use when stencil passes
  12399. */
  12400. Engine.prototype.setStencilOperationPass = function (operation) {
  12401. this._stencilState.stencilOpStencilDepthPass = operation;
  12402. };
  12403. /**
  12404. * Sets a boolean indicating if the dithering state is enabled or disabled
  12405. * @param value defines the dithering state
  12406. */
  12407. Engine.prototype.setDitheringState = function (value) {
  12408. if (value) {
  12409. this._gl.enable(this._gl.DITHER);
  12410. }
  12411. else {
  12412. this._gl.disable(this._gl.DITHER);
  12413. }
  12414. };
  12415. /**
  12416. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12417. * @param value defines the rasterizer state
  12418. */
  12419. Engine.prototype.setRasterizerState = function (value) {
  12420. if (value) {
  12421. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12422. }
  12423. else {
  12424. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12425. }
  12426. };
  12427. /**
  12428. * stop executing a render loop function and remove it from the execution array
  12429. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12430. */
  12431. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12432. if (!renderFunction) {
  12433. this._activeRenderLoops = [];
  12434. return;
  12435. }
  12436. var index = this._activeRenderLoops.indexOf(renderFunction);
  12437. if (index >= 0) {
  12438. this._activeRenderLoops.splice(index, 1);
  12439. }
  12440. };
  12441. /** @hidden */
  12442. Engine.prototype._renderLoop = function () {
  12443. if (!this._contextWasLost) {
  12444. var shouldRender = true;
  12445. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12446. shouldRender = false;
  12447. }
  12448. if (shouldRender) {
  12449. // Start new frame
  12450. this.beginFrame();
  12451. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12452. var renderFunction = this._activeRenderLoops[index];
  12453. renderFunction();
  12454. }
  12455. // Present
  12456. this.endFrame();
  12457. }
  12458. }
  12459. if (this._activeRenderLoops.length > 0) {
  12460. // Register new frame
  12461. var requester = null;
  12462. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12463. requester = this._vrDisplay;
  12464. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12465. }
  12466. else {
  12467. this._renderingQueueLaunched = false;
  12468. }
  12469. };
  12470. /**
  12471. * Register and execute a render loop. The engine can have more than one render function
  12472. * @param renderFunction defines the function to continuously execute
  12473. */
  12474. Engine.prototype.runRenderLoop = function (renderFunction) {
  12475. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12476. return;
  12477. }
  12478. this._activeRenderLoops.push(renderFunction);
  12479. if (!this._renderingQueueLaunched) {
  12480. this._renderingQueueLaunched = true;
  12481. this._bindedRenderFunction = this._renderLoop.bind(this);
  12482. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12483. }
  12484. };
  12485. /**
  12486. * Toggle full screen mode
  12487. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12488. * @param options defines an option object to be sent to the requestFullscreen function
  12489. */
  12490. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12491. if (this.isFullscreen) {
  12492. BABYLON.Tools.ExitFullscreen();
  12493. }
  12494. else {
  12495. this._pointerLockRequested = requestPointerLock;
  12496. if (this._renderingCanvas) {
  12497. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12498. }
  12499. }
  12500. };
  12501. /**
  12502. * Clear the current render buffer or the current render target (if any is set up)
  12503. * @param color defines the color to use
  12504. * @param backBuffer defines if the back buffer must be cleared
  12505. * @param depth defines if the depth buffer must be cleared
  12506. * @param stencil defines if the stencil buffer must be cleared
  12507. */
  12508. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12509. if (stencil === void 0) { stencil = false; }
  12510. this.applyStates();
  12511. var mode = 0;
  12512. if (backBuffer && color) {
  12513. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12514. mode |= this._gl.COLOR_BUFFER_BIT;
  12515. }
  12516. if (depth) {
  12517. this._gl.clearDepth(1.0);
  12518. mode |= this._gl.DEPTH_BUFFER_BIT;
  12519. }
  12520. if (stencil) {
  12521. this._gl.clearStencil(0);
  12522. mode |= this._gl.STENCIL_BUFFER_BIT;
  12523. }
  12524. this._gl.clear(mode);
  12525. };
  12526. /**
  12527. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12528. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12529. * @param y defines the y-coordinate of the corner of the clear rectangle
  12530. * @param width defines the width of the clear rectangle
  12531. * @param height defines the height of the clear rectangle
  12532. * @param clearColor defines the clear color
  12533. */
  12534. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12535. var gl = this._gl;
  12536. // Save state
  12537. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12538. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12539. // Change state
  12540. gl.enable(gl.SCISSOR_TEST);
  12541. gl.scissor(x, y, width, height);
  12542. // Clear
  12543. this.clear(clearColor, true, true, true);
  12544. // Restore state
  12545. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12546. if (curScissor === true) {
  12547. gl.enable(gl.SCISSOR_TEST);
  12548. }
  12549. else {
  12550. gl.disable(gl.SCISSOR_TEST);
  12551. }
  12552. };
  12553. /** @hidden */
  12554. Engine.prototype._viewport = function (x, y, width, height) {
  12555. if (x !== this._viewportCached.x ||
  12556. y !== this._viewportCached.y ||
  12557. width !== this._viewportCached.z ||
  12558. height !== this._viewportCached.w) {
  12559. this._viewportCached.x = x;
  12560. this._viewportCached.y = y;
  12561. this._viewportCached.z = width;
  12562. this._viewportCached.w = height;
  12563. this._gl.viewport(x, y, width, height);
  12564. }
  12565. };
  12566. /**
  12567. * Set the WebGL's viewport
  12568. * @param viewport defines the viewport element to be used
  12569. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12570. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12571. */
  12572. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12573. var width = requiredWidth || this.getRenderWidth();
  12574. var height = requiredHeight || this.getRenderHeight();
  12575. var x = viewport.x || 0;
  12576. var y = viewport.y || 0;
  12577. this._cachedViewport = viewport;
  12578. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12579. };
  12580. /**
  12581. * Directly set the WebGL Viewport
  12582. * @param x defines the x coordinate of the viewport (in screen space)
  12583. * @param y defines the y coordinate of the viewport (in screen space)
  12584. * @param width defines the width of the viewport (in screen space)
  12585. * @param height defines the height of the viewport (in screen space)
  12586. * @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
  12587. */
  12588. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12589. var currentViewport = this._cachedViewport;
  12590. this._cachedViewport = null;
  12591. this._viewport(x, y, width, height);
  12592. return currentViewport;
  12593. };
  12594. /**
  12595. * Begin a new frame
  12596. */
  12597. Engine.prototype.beginFrame = function () {
  12598. this.onBeginFrameObservable.notifyObservers(this);
  12599. this._measureFps();
  12600. };
  12601. /**
  12602. * Enf the current frame
  12603. */
  12604. Engine.prototype.endFrame = function () {
  12605. // Force a flush in case we are using a bad OS.
  12606. if (this._badOS) {
  12607. this.flushFramebuffer();
  12608. }
  12609. // Submit frame to the vr device, if enabled
  12610. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12611. // TODO: We should only submit the frame if we read frameData successfully.
  12612. this._vrDisplay.submitFrame();
  12613. }
  12614. this.onEndFrameObservable.notifyObservers(this);
  12615. };
  12616. /**
  12617. * Resize the view according to the canvas' size
  12618. */
  12619. Engine.prototype.resize = function () {
  12620. // We're not resizing the size of the canvas while in VR mode & presenting
  12621. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12622. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12623. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12624. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12625. }
  12626. };
  12627. /**
  12628. * Force a specific size of the canvas
  12629. * @param width defines the new canvas' width
  12630. * @param height defines the new canvas' height
  12631. */
  12632. Engine.prototype.setSize = function (width, height) {
  12633. if (!this._renderingCanvas) {
  12634. return;
  12635. }
  12636. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12637. return;
  12638. }
  12639. this._renderingCanvas.width = width;
  12640. this._renderingCanvas.height = height;
  12641. for (var index = 0; index < this.scenes.length; index++) {
  12642. var scene = this.scenes[index];
  12643. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12644. var cam = scene.cameras[camIndex];
  12645. cam._currentRenderId = 0;
  12646. }
  12647. }
  12648. if (this.onResizeObservable.hasObservers) {
  12649. this.onResizeObservable.notifyObservers(this);
  12650. }
  12651. };
  12652. // WebVR functions
  12653. /**
  12654. * Gets a boolean indicating if a webVR device was detected
  12655. * @returns true if a webVR device was detected
  12656. */
  12657. Engine.prototype.isVRDevicePresent = function () {
  12658. return !!this._vrDisplay;
  12659. };
  12660. /**
  12661. * Gets the current webVR device
  12662. * @returns the current webVR device (or null)
  12663. */
  12664. Engine.prototype.getVRDevice = function () {
  12665. return this._vrDisplay;
  12666. };
  12667. /**
  12668. * Initializes a webVR display and starts listening to display change events
  12669. * The onVRDisplayChangedObservable will be notified upon these changes
  12670. * @returns The onVRDisplayChangedObservable
  12671. */
  12672. Engine.prototype.initWebVR = function () {
  12673. this.initWebVRAsync();
  12674. return this.onVRDisplayChangedObservable;
  12675. };
  12676. /**
  12677. * Initializes a webVR display and starts listening to display change events
  12678. * The onVRDisplayChangedObservable will be notified upon these changes
  12679. * @returns A promise containing a VRDisplay and if vr is supported
  12680. */
  12681. Engine.prototype.initWebVRAsync = function () {
  12682. var _this = this;
  12683. var notifyObservers = function () {
  12684. var eventArgs = {
  12685. vrDisplay: _this._vrDisplay,
  12686. vrSupported: _this._vrSupported
  12687. };
  12688. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12689. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12690. };
  12691. if (!this._onVrDisplayConnect) {
  12692. this._onVrDisplayConnect = function (event) {
  12693. _this._vrDisplay = event.display;
  12694. notifyObservers();
  12695. };
  12696. this._onVrDisplayDisconnect = function () {
  12697. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12698. _this._vrDisplay = undefined;
  12699. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12700. notifyObservers();
  12701. };
  12702. this._onVrDisplayPresentChange = function () {
  12703. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12704. };
  12705. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12706. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12707. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12708. }
  12709. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12710. this._webVRInitPromise.then(notifyObservers);
  12711. return this._webVRInitPromise;
  12712. };
  12713. /**
  12714. * Call this function to switch to webVR mode
  12715. * Will do nothing if webVR is not supported or if there is no webVR device
  12716. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12717. */
  12718. Engine.prototype.enableVR = function () {
  12719. var _this = this;
  12720. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12721. var onResolved = function () {
  12722. _this.onVRRequestPresentComplete.notifyObservers(true);
  12723. _this._onVRFullScreenTriggered();
  12724. };
  12725. var onRejected = function () {
  12726. _this.onVRRequestPresentComplete.notifyObservers(false);
  12727. };
  12728. this.onVRRequestPresentStart.notifyObservers(this);
  12729. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12730. }
  12731. };
  12732. /**
  12733. * Call this function to leave webVR mode
  12734. * Will do nothing if webVR is not supported or if there is no webVR device
  12735. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12736. */
  12737. Engine.prototype.disableVR = function () {
  12738. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12739. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12740. }
  12741. };
  12742. Engine.prototype._getVRDisplaysAsync = function () {
  12743. var _this = this;
  12744. return new Promise(function (res, rej) {
  12745. if (navigator.getVRDisplays) {
  12746. navigator.getVRDisplays().then(function (devices) {
  12747. _this._vrSupported = true;
  12748. // note that devices may actually be an empty array. This is fine;
  12749. // we expect this._vrDisplay to be undefined in this case.
  12750. _this._vrDisplay = devices[0];
  12751. res({
  12752. vrDisplay: _this._vrDisplay,
  12753. vrSupported: _this._vrSupported
  12754. });
  12755. });
  12756. }
  12757. else {
  12758. _this._vrDisplay = undefined;
  12759. _this._vrSupported = false;
  12760. res({
  12761. vrDisplay: _this._vrDisplay,
  12762. vrSupported: _this._vrSupported
  12763. });
  12764. }
  12765. });
  12766. };
  12767. /**
  12768. * Binds the frame buffer to the specified texture.
  12769. * @param texture The texture to render to or null for the default canvas
  12770. * @param faceIndex The face of the texture to render to in case of cube texture
  12771. * @param requiredWidth The width of the target to render to
  12772. * @param requiredHeight The height of the target to render to
  12773. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12774. * @param depthStencilTexture The depth stencil texture to use to render
  12775. * @param lodLevel defines le lod level to bind to the frame buffer
  12776. */
  12777. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  12778. if (lodLevel === void 0) { lodLevel = 0; }
  12779. if (this._currentRenderTarget) {
  12780. this.unBindFramebuffer(this._currentRenderTarget);
  12781. }
  12782. this._currentRenderTarget = texture;
  12783. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12784. var gl = this._gl;
  12785. if (texture.isCube) {
  12786. if (faceIndex === undefined) {
  12787. faceIndex = 0;
  12788. }
  12789. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  12790. if (depthStencilTexture) {
  12791. if (depthStencilTexture._generateStencilBuffer) {
  12792. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12793. }
  12794. else {
  12795. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  12796. }
  12797. }
  12798. }
  12799. if (this._cachedViewport && !forceFullscreenViewport) {
  12800. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12801. }
  12802. else {
  12803. if (!requiredWidth) {
  12804. requiredWidth = texture.width;
  12805. if (lodLevel) {
  12806. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  12807. }
  12808. }
  12809. if (!requiredHeight) {
  12810. requiredHeight = texture.height;
  12811. if (lodLevel) {
  12812. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  12813. }
  12814. }
  12815. this._viewport(0, 0, requiredWidth, requiredHeight);
  12816. }
  12817. this.wipeCaches();
  12818. };
  12819. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12820. if (this._currentFramebuffer !== framebuffer) {
  12821. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12822. this._currentFramebuffer = framebuffer;
  12823. }
  12824. };
  12825. /**
  12826. * Unbind the current render target texture from the webGL context
  12827. * @param texture defines the render target texture to unbind
  12828. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12829. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12830. */
  12831. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12832. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12833. this._currentRenderTarget = null;
  12834. // If MSAA, we need to bitblt back to main texture
  12835. var gl = this._gl;
  12836. if (texture._MSAAFramebuffer) {
  12837. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12838. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12839. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12840. }
  12841. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12842. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12843. gl.generateMipmap(gl.TEXTURE_2D);
  12844. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12845. }
  12846. if (onBeforeUnbind) {
  12847. if (texture._MSAAFramebuffer) {
  12848. // Bind the correct framebuffer
  12849. this.bindUnboundFramebuffer(texture._framebuffer);
  12850. }
  12851. onBeforeUnbind();
  12852. }
  12853. this.bindUnboundFramebuffer(null);
  12854. };
  12855. /**
  12856. * Unbind a list of render target textures from the webGL context
  12857. * This is used only when drawBuffer extension or webGL2 are active
  12858. * @param textures defines the render target textures to unbind
  12859. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12860. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12861. */
  12862. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12863. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12864. this._currentRenderTarget = null;
  12865. // If MSAA, we need to bitblt back to main texture
  12866. var gl = this._gl;
  12867. if (textures[0]._MSAAFramebuffer) {
  12868. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12869. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12870. var attachments = textures[0]._attachments;
  12871. if (!attachments) {
  12872. attachments = new Array(textures.length);
  12873. textures[0]._attachments = attachments;
  12874. }
  12875. for (var i = 0; i < textures.length; i++) {
  12876. var texture = textures[i];
  12877. for (var j = 0; j < attachments.length; j++) {
  12878. attachments[j] = gl.NONE;
  12879. }
  12880. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12881. gl.readBuffer(attachments[i]);
  12882. gl.drawBuffers(attachments);
  12883. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12884. }
  12885. for (var i = 0; i < attachments.length; i++) {
  12886. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12887. }
  12888. gl.drawBuffers(attachments);
  12889. }
  12890. for (var i = 0; i < textures.length; i++) {
  12891. var texture = textures[i];
  12892. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12893. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12894. gl.generateMipmap(gl.TEXTURE_2D);
  12895. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12896. }
  12897. }
  12898. if (onBeforeUnbind) {
  12899. if (textures[0]._MSAAFramebuffer) {
  12900. // Bind the correct framebuffer
  12901. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12902. }
  12903. onBeforeUnbind();
  12904. }
  12905. this.bindUnboundFramebuffer(null);
  12906. };
  12907. /**
  12908. * Force the mipmap generation for the given render target texture
  12909. * @param texture defines the render target texture to use
  12910. */
  12911. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12912. if (texture.generateMipMaps) {
  12913. var gl = this._gl;
  12914. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12915. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12916. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12917. }
  12918. };
  12919. /**
  12920. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  12921. */
  12922. Engine.prototype.flushFramebuffer = function () {
  12923. this._gl.flush();
  12924. };
  12925. /**
  12926. * Unbind the current render target and bind the default framebuffer
  12927. */
  12928. Engine.prototype.restoreDefaultFramebuffer = function () {
  12929. if (this._currentRenderTarget) {
  12930. this.unBindFramebuffer(this._currentRenderTarget);
  12931. }
  12932. else {
  12933. this.bindUnboundFramebuffer(null);
  12934. }
  12935. if (this._cachedViewport) {
  12936. this.setViewport(this._cachedViewport);
  12937. }
  12938. this.wipeCaches();
  12939. };
  12940. // UBOs
  12941. /**
  12942. * Create an uniform buffer
  12943. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12944. * @param elements defines the content of the uniform buffer
  12945. * @returns the webGL uniform buffer
  12946. */
  12947. Engine.prototype.createUniformBuffer = function (elements) {
  12948. var ubo = this._gl.createBuffer();
  12949. if (!ubo) {
  12950. throw new Error("Unable to create uniform buffer");
  12951. }
  12952. this.bindUniformBuffer(ubo);
  12953. if (elements instanceof Float32Array) {
  12954. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12955. }
  12956. else {
  12957. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12958. }
  12959. this.bindUniformBuffer(null);
  12960. ubo.references = 1;
  12961. return ubo;
  12962. };
  12963. /**
  12964. * Create a dynamic uniform buffer
  12965. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12966. * @param elements defines the content of the uniform buffer
  12967. * @returns the webGL uniform buffer
  12968. */
  12969. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12970. var ubo = this._gl.createBuffer();
  12971. if (!ubo) {
  12972. throw new Error("Unable to create dynamic uniform buffer");
  12973. }
  12974. this.bindUniformBuffer(ubo);
  12975. if (elements instanceof Float32Array) {
  12976. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12977. }
  12978. else {
  12979. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12980. }
  12981. this.bindUniformBuffer(null);
  12982. ubo.references = 1;
  12983. return ubo;
  12984. };
  12985. /**
  12986. * Update an existing uniform buffer
  12987. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12988. * @param uniformBuffer defines the target uniform buffer
  12989. * @param elements defines the content to update
  12990. * @param offset defines the offset in the uniform buffer where update should start
  12991. * @param count defines the size of the data to update
  12992. */
  12993. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12994. this.bindUniformBuffer(uniformBuffer);
  12995. if (offset === undefined) {
  12996. offset = 0;
  12997. }
  12998. if (count === undefined) {
  12999. if (elements instanceof Float32Array) {
  13000. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13001. }
  13002. else {
  13003. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13004. }
  13005. }
  13006. else {
  13007. if (elements instanceof Float32Array) {
  13008. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13009. }
  13010. else {
  13011. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13012. }
  13013. }
  13014. this.bindUniformBuffer(null);
  13015. };
  13016. // VBOs
  13017. Engine.prototype._resetVertexBufferBinding = function () {
  13018. this.bindArrayBuffer(null);
  13019. this._cachedVertexBuffers = null;
  13020. };
  13021. /**
  13022. * Creates a vertex buffer
  13023. * @param data the data for the vertex buffer
  13024. * @returns the new WebGL static buffer
  13025. */
  13026. Engine.prototype.createVertexBuffer = function (data) {
  13027. var vbo = this._gl.createBuffer();
  13028. if (!vbo) {
  13029. throw new Error("Unable to create vertex buffer");
  13030. }
  13031. this.bindArrayBuffer(vbo);
  13032. if (data instanceof Array) {
  13033. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13034. }
  13035. else {
  13036. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13037. }
  13038. this._resetVertexBufferBinding();
  13039. vbo.references = 1;
  13040. return vbo;
  13041. };
  13042. /**
  13043. * Creates a dynamic vertex buffer
  13044. * @param data the data for the dynamic vertex buffer
  13045. * @returns the new WebGL dynamic buffer
  13046. */
  13047. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13048. var vbo = this._gl.createBuffer();
  13049. if (!vbo) {
  13050. throw new Error("Unable to create dynamic vertex buffer");
  13051. }
  13052. this.bindArrayBuffer(vbo);
  13053. if (data instanceof Array) {
  13054. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13055. }
  13056. else {
  13057. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13058. }
  13059. this._resetVertexBufferBinding();
  13060. vbo.references = 1;
  13061. return vbo;
  13062. };
  13063. /**
  13064. * Update a dynamic index buffer
  13065. * @param indexBuffer defines the target index buffer
  13066. * @param indices defines the data to update
  13067. * @param offset defines the offset in the target index buffer where update should start
  13068. */
  13069. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13070. if (offset === void 0) { offset = 0; }
  13071. // Force cache update
  13072. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13073. this.bindIndexBuffer(indexBuffer);
  13074. var arrayBuffer;
  13075. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13076. arrayBuffer = indices;
  13077. }
  13078. else {
  13079. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13080. }
  13081. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13082. this._resetIndexBufferBinding();
  13083. };
  13084. /**
  13085. * Updates a dynamic vertex buffer.
  13086. * @param vertexBuffer the vertex buffer to update
  13087. * @param data the data used to update the vertex buffer
  13088. * @param byteOffset the byte offset of the data
  13089. * @param byteLength the byte length of the data
  13090. */
  13091. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13092. this.bindArrayBuffer(vertexBuffer);
  13093. if (byteOffset === undefined) {
  13094. byteOffset = 0;
  13095. }
  13096. if (byteLength === undefined) {
  13097. if (data instanceof Array) {
  13098. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13099. }
  13100. else {
  13101. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13102. }
  13103. }
  13104. else {
  13105. if (data instanceof Array) {
  13106. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13107. }
  13108. else {
  13109. if (data instanceof ArrayBuffer) {
  13110. data = new Uint8Array(data, byteOffset, byteLength);
  13111. }
  13112. else {
  13113. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13114. }
  13115. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13116. }
  13117. }
  13118. this._resetVertexBufferBinding();
  13119. };
  13120. Engine.prototype._resetIndexBufferBinding = function () {
  13121. this.bindIndexBuffer(null);
  13122. this._cachedIndexBuffer = null;
  13123. };
  13124. /**
  13125. * Creates a new index buffer
  13126. * @param indices defines the content of the index buffer
  13127. * @param updatable defines if the index buffer must be updatable
  13128. * @returns a new webGL buffer
  13129. */
  13130. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13131. var vbo = this._gl.createBuffer();
  13132. if (!vbo) {
  13133. throw new Error("Unable to create index buffer");
  13134. }
  13135. this.bindIndexBuffer(vbo);
  13136. // Check for 32 bits indices
  13137. var arrayBuffer;
  13138. var need32Bits = false;
  13139. if (indices instanceof Uint16Array) {
  13140. arrayBuffer = indices;
  13141. }
  13142. else {
  13143. //check 32 bit support
  13144. if (this._caps.uintIndices) {
  13145. if (indices instanceof Uint32Array) {
  13146. arrayBuffer = indices;
  13147. need32Bits = true;
  13148. }
  13149. else {
  13150. //number[] or Int32Array, check if 32 bit is necessary
  13151. for (var index = 0; index < indices.length; index++) {
  13152. if (indices[index] > 65535) {
  13153. need32Bits = true;
  13154. break;
  13155. }
  13156. }
  13157. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13158. }
  13159. }
  13160. else {
  13161. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13162. arrayBuffer = new Uint16Array(indices);
  13163. }
  13164. }
  13165. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13166. this._resetIndexBufferBinding();
  13167. vbo.references = 1;
  13168. vbo.is32Bits = need32Bits;
  13169. return vbo;
  13170. };
  13171. /**
  13172. * Bind a webGL buffer to the webGL context
  13173. * @param buffer defines the buffer to bind
  13174. */
  13175. Engine.prototype.bindArrayBuffer = function (buffer) {
  13176. if (!this._vaoRecordInProgress) {
  13177. this._unbindVertexArrayObject();
  13178. }
  13179. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13180. };
  13181. /**
  13182. * Bind an uniform buffer to the current webGL context
  13183. * @param buffer defines the buffer to bind
  13184. */
  13185. Engine.prototype.bindUniformBuffer = function (buffer) {
  13186. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13187. };
  13188. /**
  13189. * Bind a buffer to the current webGL context at a given location
  13190. * @param buffer defines the buffer to bind
  13191. * @param location defines the index where to bind the buffer
  13192. */
  13193. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13194. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13195. };
  13196. /**
  13197. * Bind a specific block at a given index in a specific shader program
  13198. * @param shaderProgram defines the shader program
  13199. * @param blockName defines the block name
  13200. * @param index defines the index where to bind the block
  13201. */
  13202. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13203. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13204. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13205. };
  13206. ;
  13207. Engine.prototype.bindIndexBuffer = function (buffer) {
  13208. if (!this._vaoRecordInProgress) {
  13209. this._unbindVertexArrayObject();
  13210. }
  13211. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13212. };
  13213. Engine.prototype.bindBuffer = function (buffer, target) {
  13214. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13215. this._gl.bindBuffer(target, buffer);
  13216. this._currentBoundBuffer[target] = buffer;
  13217. }
  13218. };
  13219. /**
  13220. * update the bound buffer with the given data
  13221. * @param data defines the data to update
  13222. */
  13223. Engine.prototype.updateArrayBuffer = function (data) {
  13224. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13225. };
  13226. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13227. var pointer = this._currentBufferPointers[indx];
  13228. var changed = false;
  13229. if (!pointer.active) {
  13230. changed = true;
  13231. pointer.active = true;
  13232. pointer.index = indx;
  13233. pointer.size = size;
  13234. pointer.type = type;
  13235. pointer.normalized = normalized;
  13236. pointer.stride = stride;
  13237. pointer.offset = offset;
  13238. pointer.buffer = buffer;
  13239. }
  13240. else {
  13241. if (pointer.buffer !== buffer) {
  13242. pointer.buffer = buffer;
  13243. changed = true;
  13244. }
  13245. if (pointer.size !== size) {
  13246. pointer.size = size;
  13247. changed = true;
  13248. }
  13249. if (pointer.type !== type) {
  13250. pointer.type = type;
  13251. changed = true;
  13252. }
  13253. if (pointer.normalized !== normalized) {
  13254. pointer.normalized = normalized;
  13255. changed = true;
  13256. }
  13257. if (pointer.stride !== stride) {
  13258. pointer.stride = stride;
  13259. changed = true;
  13260. }
  13261. if (pointer.offset !== offset) {
  13262. pointer.offset = offset;
  13263. changed = true;
  13264. }
  13265. }
  13266. if (changed || this._vaoRecordInProgress) {
  13267. this.bindArrayBuffer(buffer);
  13268. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13269. }
  13270. };
  13271. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13272. if (indexBuffer == null) {
  13273. return;
  13274. }
  13275. if (this._cachedIndexBuffer !== indexBuffer) {
  13276. this._cachedIndexBuffer = indexBuffer;
  13277. this.bindIndexBuffer(indexBuffer);
  13278. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13279. }
  13280. };
  13281. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13282. var attributes = effect.getAttributesNames();
  13283. if (!this._vaoRecordInProgress) {
  13284. this._unbindVertexArrayObject();
  13285. }
  13286. this.unbindAllAttributes();
  13287. for (var index = 0; index < attributes.length; index++) {
  13288. var order = effect.getAttributeLocation(index);
  13289. if (order >= 0) {
  13290. var vertexBuffer = vertexBuffers[attributes[index]];
  13291. if (!vertexBuffer) {
  13292. continue;
  13293. }
  13294. this._gl.enableVertexAttribArray(order);
  13295. if (!this._vaoRecordInProgress) {
  13296. this._vertexAttribArraysEnabled[order] = true;
  13297. }
  13298. var buffer = vertexBuffer.getBuffer();
  13299. if (buffer) {
  13300. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13301. if (vertexBuffer.getIsInstanced()) {
  13302. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13303. if (!this._vaoRecordInProgress) {
  13304. this._currentInstanceLocations.push(order);
  13305. this._currentInstanceBuffers.push(buffer);
  13306. }
  13307. }
  13308. }
  13309. }
  13310. }
  13311. };
  13312. /**
  13313. * Records a vertex array object
  13314. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13315. * @param vertexBuffers defines the list of vertex buffers to store
  13316. * @param indexBuffer defines the index buffer to store
  13317. * @param effect defines the effect to store
  13318. * @returns the new vertex array object
  13319. */
  13320. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13321. var vao = this._gl.createVertexArray();
  13322. this._vaoRecordInProgress = true;
  13323. this._gl.bindVertexArray(vao);
  13324. this._mustWipeVertexAttributes = true;
  13325. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13326. this.bindIndexBuffer(indexBuffer);
  13327. this._vaoRecordInProgress = false;
  13328. this._gl.bindVertexArray(null);
  13329. return vao;
  13330. };
  13331. /**
  13332. * Bind a specific vertex array object
  13333. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13334. * @param vertexArrayObject defines the vertex array object to bind
  13335. * @param indexBuffer defines the index buffer to bind
  13336. */
  13337. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13338. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13339. this._cachedVertexArrayObject = vertexArrayObject;
  13340. this._gl.bindVertexArray(vertexArrayObject);
  13341. this._cachedVertexBuffers = null;
  13342. this._cachedIndexBuffer = null;
  13343. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13344. this._mustWipeVertexAttributes = true;
  13345. }
  13346. };
  13347. /**
  13348. * Bind webGl buffers directly to the webGL context
  13349. * @param vertexBuffer defines the vertex buffer to bind
  13350. * @param indexBuffer defines the index buffer to bind
  13351. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13352. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13353. * @param effect defines the effect associated with the vertex buffer
  13354. */
  13355. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13356. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13357. this._cachedVertexBuffers = vertexBuffer;
  13358. this._cachedEffectForVertexBuffers = effect;
  13359. var attributesCount = effect.getAttributesCount();
  13360. this._unbindVertexArrayObject();
  13361. this.unbindAllAttributes();
  13362. var offset = 0;
  13363. for (var index = 0; index < attributesCount; index++) {
  13364. if (index < vertexDeclaration.length) {
  13365. var order = effect.getAttributeLocation(index);
  13366. if (order >= 0) {
  13367. this._gl.enableVertexAttribArray(order);
  13368. this._vertexAttribArraysEnabled[order] = true;
  13369. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13370. }
  13371. offset += vertexDeclaration[index] * 4;
  13372. }
  13373. }
  13374. }
  13375. this._bindIndexBufferWithCache(indexBuffer);
  13376. };
  13377. Engine.prototype._unbindVertexArrayObject = function () {
  13378. if (!this._cachedVertexArrayObject) {
  13379. return;
  13380. }
  13381. this._cachedVertexArrayObject = null;
  13382. this._gl.bindVertexArray(null);
  13383. };
  13384. /**
  13385. * Bind a list of vertex buffers to the webGL context
  13386. * @param vertexBuffers defines the list of vertex buffers to bind
  13387. * @param indexBuffer defines the index buffer to bind
  13388. * @param effect defines the effect associated with the vertex buffers
  13389. */
  13390. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13391. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13392. this._cachedVertexBuffers = vertexBuffers;
  13393. this._cachedEffectForVertexBuffers = effect;
  13394. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13395. }
  13396. this._bindIndexBufferWithCache(indexBuffer);
  13397. };
  13398. /**
  13399. * Unbind all instance attributes
  13400. */
  13401. Engine.prototype.unbindInstanceAttributes = function () {
  13402. var boundBuffer;
  13403. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13404. var instancesBuffer = this._currentInstanceBuffers[i];
  13405. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13406. boundBuffer = instancesBuffer;
  13407. this.bindArrayBuffer(instancesBuffer);
  13408. }
  13409. var offsetLocation = this._currentInstanceLocations[i];
  13410. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13411. }
  13412. this._currentInstanceBuffers.length = 0;
  13413. this._currentInstanceLocations.length = 0;
  13414. };
  13415. /**
  13416. * Release and free the memory of a vertex array object
  13417. * @param vao defines the vertex array object to delete
  13418. */
  13419. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13420. this._gl.deleteVertexArray(vao);
  13421. };
  13422. /** @hidden */
  13423. Engine.prototype._releaseBuffer = function (buffer) {
  13424. buffer.references--;
  13425. if (buffer.references === 0) {
  13426. this._gl.deleteBuffer(buffer);
  13427. return true;
  13428. }
  13429. return false;
  13430. };
  13431. /**
  13432. * Creates a webGL buffer to use with instanciation
  13433. * @param capacity defines the size of the buffer
  13434. * @returns the webGL buffer
  13435. */
  13436. Engine.prototype.createInstancesBuffer = function (capacity) {
  13437. var buffer = this._gl.createBuffer();
  13438. if (!buffer) {
  13439. throw new Error("Unable to create instance buffer");
  13440. }
  13441. buffer.capacity = capacity;
  13442. this.bindArrayBuffer(buffer);
  13443. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13444. return buffer;
  13445. };
  13446. /**
  13447. * Delete a webGL buffer used with instanciation
  13448. * @param buffer defines the webGL buffer to delete
  13449. */
  13450. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13451. this._gl.deleteBuffer(buffer);
  13452. };
  13453. /**
  13454. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13455. * @param instancesBuffer defines the webGL buffer to update and bind
  13456. * @param data defines the data to store in the buffer
  13457. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13458. */
  13459. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13460. this.bindArrayBuffer(instancesBuffer);
  13461. if (data) {
  13462. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13463. }
  13464. if (offsetLocations[0].index !== undefined) {
  13465. var stride = 0;
  13466. for (var i = 0; i < offsetLocations.length; i++) {
  13467. var ai = offsetLocations[i];
  13468. stride += ai.attributeSize * 4;
  13469. }
  13470. for (var i = 0; i < offsetLocations.length; i++) {
  13471. var ai = offsetLocations[i];
  13472. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13473. this._gl.enableVertexAttribArray(ai.index);
  13474. this._vertexAttribArraysEnabled[ai.index] = true;
  13475. }
  13476. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13477. this._gl.vertexAttribDivisor(ai.index, 1);
  13478. this._currentInstanceLocations.push(ai.index);
  13479. this._currentInstanceBuffers.push(instancesBuffer);
  13480. }
  13481. }
  13482. else {
  13483. for (var index = 0; index < 4; index++) {
  13484. var offsetLocation = offsetLocations[index];
  13485. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13486. this._gl.enableVertexAttribArray(offsetLocation);
  13487. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13488. }
  13489. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13490. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13491. this._currentInstanceLocations.push(offsetLocation);
  13492. this._currentInstanceBuffers.push(instancesBuffer);
  13493. }
  13494. }
  13495. };
  13496. /**
  13497. * Apply all cached states (depth, culling, stencil and alpha)
  13498. */
  13499. Engine.prototype.applyStates = function () {
  13500. this._depthCullingState.apply(this._gl);
  13501. this._stencilState.apply(this._gl);
  13502. this._alphaState.apply(this._gl);
  13503. };
  13504. /**
  13505. * Send a draw order
  13506. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13507. * @param indexStart defines the starting index
  13508. * @param indexCount defines the number of index to draw
  13509. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13510. */
  13511. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13512. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13513. };
  13514. /**
  13515. * Draw a list of points
  13516. * @param verticesStart defines the index of first vertex to draw
  13517. * @param verticesCount defines the count of vertices to draw
  13518. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13519. */
  13520. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13521. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13522. };
  13523. /**
  13524. * Draw a list of unindexed primitives
  13525. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13526. * @param verticesStart defines the index of first vertex to draw
  13527. * @param verticesCount defines the count of vertices to draw
  13528. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13529. */
  13530. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13531. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13532. };
  13533. /**
  13534. * Draw a list of indexed primitives
  13535. * @param fillMode defines the primitive to use
  13536. * @param indexStart defines the starting index
  13537. * @param indexCount defines the number of index to draw
  13538. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13539. */
  13540. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13541. // Apply states
  13542. this.applyStates();
  13543. this._drawCalls.addCount(1, false);
  13544. // Render
  13545. var drawMode = this._drawMode(fillMode);
  13546. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13547. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13548. if (instancesCount) {
  13549. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13550. }
  13551. else {
  13552. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13553. }
  13554. };
  13555. /**
  13556. * Draw a list of unindexed primitives
  13557. * @param fillMode defines the primitive to use
  13558. * @param verticesStart defines the index of first vertex to draw
  13559. * @param verticesCount defines the count of vertices to draw
  13560. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13561. */
  13562. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13563. // Apply states
  13564. this.applyStates();
  13565. this._drawCalls.addCount(1, false);
  13566. var drawMode = this._drawMode(fillMode);
  13567. if (instancesCount) {
  13568. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13569. }
  13570. else {
  13571. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13572. }
  13573. };
  13574. Engine.prototype._drawMode = function (fillMode) {
  13575. switch (fillMode) {
  13576. // Triangle views
  13577. case BABYLON.Material.TriangleFillMode:
  13578. return this._gl.TRIANGLES;
  13579. case BABYLON.Material.PointFillMode:
  13580. return this._gl.POINTS;
  13581. case BABYLON.Material.WireFrameFillMode:
  13582. return this._gl.LINES;
  13583. // Draw modes
  13584. case BABYLON.Material.PointListDrawMode:
  13585. return this._gl.POINTS;
  13586. case BABYLON.Material.LineListDrawMode:
  13587. return this._gl.LINES;
  13588. case BABYLON.Material.LineLoopDrawMode:
  13589. return this._gl.LINE_LOOP;
  13590. case BABYLON.Material.LineStripDrawMode:
  13591. return this._gl.LINE_STRIP;
  13592. case BABYLON.Material.TriangleStripDrawMode:
  13593. return this._gl.TRIANGLE_STRIP;
  13594. case BABYLON.Material.TriangleFanDrawMode:
  13595. return this._gl.TRIANGLE_FAN;
  13596. default:
  13597. return this._gl.TRIANGLES;
  13598. }
  13599. };
  13600. // Shaders
  13601. /** @hidden */
  13602. Engine.prototype._releaseEffect = function (effect) {
  13603. if (this._compiledEffects[effect._key]) {
  13604. delete this._compiledEffects[effect._key];
  13605. this._deleteProgram(effect.getProgram());
  13606. }
  13607. };
  13608. /** @hidden */
  13609. Engine.prototype._deleteProgram = function (program) {
  13610. if (program) {
  13611. program.__SPECTOR_rebuildProgram = null;
  13612. if (program.transformFeedback) {
  13613. this.deleteTransformFeedback(program.transformFeedback);
  13614. program.transformFeedback = null;
  13615. }
  13616. this._gl.deleteProgram(program);
  13617. }
  13618. };
  13619. /**
  13620. * Create a new effect (used to store vertex/fragment shaders)
  13621. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13622. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13623. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13624. * @param samplers defines an array of string used to represent textures
  13625. * @param defines defines the string containing the defines to use to compile the shaders
  13626. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13627. * @param onCompiled defines a function to call when the effect creation is successful
  13628. * @param onError defines a function to call when the effect creation has failed
  13629. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13630. * @returns the new Effect
  13631. */
  13632. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13633. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13634. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13635. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13636. if (this._compiledEffects[name]) {
  13637. var compiledEffect = this._compiledEffects[name];
  13638. if (onCompiled && compiledEffect.isReady()) {
  13639. onCompiled(compiledEffect);
  13640. }
  13641. return compiledEffect;
  13642. }
  13643. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13644. effect._key = name;
  13645. this._compiledEffects[name] = effect;
  13646. return effect;
  13647. };
  13648. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  13649. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  13650. };
  13651. ;
  13652. Engine.prototype._compileRawShader = function (source, type) {
  13653. var gl = this._gl;
  13654. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  13655. gl.shaderSource(shader, source);
  13656. gl.compileShader(shader);
  13657. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  13658. var log = gl.getShaderInfoLog(shader);
  13659. if (log) {
  13660. throw new Error(log);
  13661. }
  13662. }
  13663. if (!shader) {
  13664. throw new Error("Something went wrong while compile the shader.");
  13665. }
  13666. return shader;
  13667. };
  13668. ;
  13669. /**
  13670. * Directly creates a webGL program
  13671. * @param vertexCode defines the vertex shader code to use
  13672. * @param fragmentCode defines the fragment shader code to use
  13673. * @param context defines the webGL context to use (if not set, the current one will be used)
  13674. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13675. * @returns the new webGL program
  13676. */
  13677. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13678. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13679. context = context || this._gl;
  13680. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  13681. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  13682. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13683. };
  13684. /**
  13685. * Creates a webGL program
  13686. * @param vertexCode defines the vertex shader code to use
  13687. * @param fragmentCode defines the fragment shader code to use
  13688. * @param defines defines the string containing the defines to use to compile the shaders
  13689. * @param context defines the webGL context to use (if not set, the current one will be used)
  13690. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13691. * @returns the new webGL program
  13692. */
  13693. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13694. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13695. context = context || this._gl;
  13696. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13697. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13698. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  13699. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  13700. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13701. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13702. return program;
  13703. };
  13704. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13705. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13706. var shaderProgram = context.createProgram();
  13707. if (!shaderProgram) {
  13708. throw new Error("Unable to create program");
  13709. }
  13710. context.attachShader(shaderProgram, vertexShader);
  13711. context.attachShader(shaderProgram, fragmentShader);
  13712. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13713. var transformFeedback = this.createTransformFeedback();
  13714. this.bindTransformFeedback(transformFeedback);
  13715. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13716. shaderProgram.transformFeedback = transformFeedback;
  13717. }
  13718. context.linkProgram(shaderProgram);
  13719. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13720. this.bindTransformFeedback(null);
  13721. }
  13722. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13723. if (!linked) {
  13724. var error = context.getProgramInfoLog(shaderProgram);
  13725. if (error) {
  13726. throw new Error(error);
  13727. }
  13728. }
  13729. if (this.validateShaderPrograms) {
  13730. context.validateProgram(shaderProgram);
  13731. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  13732. if (!validated) {
  13733. var error = context.getProgramInfoLog(shaderProgram);
  13734. if (error) {
  13735. throw new Error(error);
  13736. }
  13737. }
  13738. }
  13739. context.deleteShader(vertexShader);
  13740. context.deleteShader(fragmentShader);
  13741. return shaderProgram;
  13742. };
  13743. /**
  13744. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13745. * @param shaderProgram defines the webGL program to use
  13746. * @param uniformsNames defines the list of uniform names
  13747. * @returns an array of webGL uniform locations
  13748. */
  13749. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13750. var results = new Array();
  13751. for (var index = 0; index < uniformsNames.length; index++) {
  13752. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13753. }
  13754. return results;
  13755. };
  13756. /**
  13757. * Gets the lsit of active attributes for a given webGL program
  13758. * @param shaderProgram defines the webGL program to use
  13759. * @param attributesNames defines the list of attribute names to get
  13760. * @returns an array of indices indicating the offset of each attribute
  13761. */
  13762. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13763. var results = [];
  13764. for (var index = 0; index < attributesNames.length; index++) {
  13765. try {
  13766. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13767. }
  13768. catch (e) {
  13769. results.push(-1);
  13770. }
  13771. }
  13772. return results;
  13773. };
  13774. /**
  13775. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13776. * @param effect defines the effect to activate
  13777. */
  13778. Engine.prototype.enableEffect = function (effect) {
  13779. if (!effect || effect === this._currentEffect) {
  13780. return;
  13781. }
  13782. // Use program
  13783. this.bindSamplers(effect);
  13784. this._currentEffect = effect;
  13785. if (effect.onBind) {
  13786. effect.onBind(effect);
  13787. }
  13788. if (effect._onBindObservable) {
  13789. effect._onBindObservable.notifyObservers(effect);
  13790. }
  13791. };
  13792. /**
  13793. * Set the value of an uniform to an array of int32
  13794. * @param uniform defines the webGL uniform location where to store the value
  13795. * @param array defines the array of int32 to store
  13796. */
  13797. Engine.prototype.setIntArray = function (uniform, array) {
  13798. if (!uniform)
  13799. return;
  13800. this._gl.uniform1iv(uniform, array);
  13801. };
  13802. /**
  13803. * Set the value of an uniform to an array of int32 (stored as vec2)
  13804. * @param uniform defines the webGL uniform location where to store the value
  13805. * @param array defines the array of int32 to store
  13806. */
  13807. Engine.prototype.setIntArray2 = function (uniform, array) {
  13808. if (!uniform || array.length % 2 !== 0)
  13809. return;
  13810. this._gl.uniform2iv(uniform, array);
  13811. };
  13812. /**
  13813. * Set the value of an uniform to an array of int32 (stored as vec3)
  13814. * @param uniform defines the webGL uniform location where to store the value
  13815. * @param array defines the array of int32 to store
  13816. */
  13817. Engine.prototype.setIntArray3 = function (uniform, array) {
  13818. if (!uniform || array.length % 3 !== 0)
  13819. return;
  13820. this._gl.uniform3iv(uniform, array);
  13821. };
  13822. /**
  13823. * Set the value of an uniform to an array of int32 (stored as vec4)
  13824. * @param uniform defines the webGL uniform location where to store the value
  13825. * @param array defines the array of int32 to store
  13826. */
  13827. Engine.prototype.setIntArray4 = function (uniform, array) {
  13828. if (!uniform || array.length % 4 !== 0)
  13829. return;
  13830. this._gl.uniform4iv(uniform, array);
  13831. };
  13832. /**
  13833. * Set the value of an uniform to an array of float32
  13834. * @param uniform defines the webGL uniform location where to store the value
  13835. * @param array defines the array of float32 to store
  13836. */
  13837. Engine.prototype.setFloatArray = function (uniform, array) {
  13838. if (!uniform)
  13839. return;
  13840. this._gl.uniform1fv(uniform, array);
  13841. };
  13842. /**
  13843. * Set the value of an uniform to an array of float32 (stored as vec2)
  13844. * @param uniform defines the webGL uniform location where to store the value
  13845. * @param array defines the array of float32 to store
  13846. */
  13847. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13848. if (!uniform || array.length % 2 !== 0)
  13849. return;
  13850. this._gl.uniform2fv(uniform, array);
  13851. };
  13852. /**
  13853. * Set the value of an uniform to an array of float32 (stored as vec3)
  13854. * @param uniform defines the webGL uniform location where to store the value
  13855. * @param array defines the array of float32 to store
  13856. */
  13857. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13858. if (!uniform || array.length % 3 !== 0)
  13859. return;
  13860. this._gl.uniform3fv(uniform, array);
  13861. };
  13862. /**
  13863. * Set the value of an uniform to an array of float32 (stored as vec4)
  13864. * @param uniform defines the webGL uniform location where to store the value
  13865. * @param array defines the array of float32 to store
  13866. */
  13867. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13868. if (!uniform || array.length % 4 !== 0)
  13869. return;
  13870. this._gl.uniform4fv(uniform, array);
  13871. };
  13872. /**
  13873. * Set the value of an uniform to an array of number
  13874. * @param uniform defines the webGL uniform location where to store the value
  13875. * @param array defines the array of number to store
  13876. */
  13877. Engine.prototype.setArray = function (uniform, array) {
  13878. if (!uniform)
  13879. return;
  13880. this._gl.uniform1fv(uniform, array);
  13881. };
  13882. /**
  13883. * Set the value of an uniform to an array of number (stored as vec2)
  13884. * @param uniform defines the webGL uniform location where to store the value
  13885. * @param array defines the array of number to store
  13886. */
  13887. Engine.prototype.setArray2 = function (uniform, array) {
  13888. if (!uniform || array.length % 2 !== 0)
  13889. return;
  13890. this._gl.uniform2fv(uniform, array);
  13891. };
  13892. /**
  13893. * Set the value of an uniform to an array of number (stored as vec3)
  13894. * @param uniform defines the webGL uniform location where to store the value
  13895. * @param array defines the array of number to store
  13896. */
  13897. Engine.prototype.setArray3 = function (uniform, array) {
  13898. if (!uniform || array.length % 3 !== 0)
  13899. return;
  13900. this._gl.uniform3fv(uniform, array);
  13901. };
  13902. /**
  13903. * Set the value of an uniform to an array of number (stored as vec4)
  13904. * @param uniform defines the webGL uniform location where to store the value
  13905. * @param array defines the array of number to store
  13906. */
  13907. Engine.prototype.setArray4 = function (uniform, array) {
  13908. if (!uniform || array.length % 4 !== 0)
  13909. return;
  13910. this._gl.uniform4fv(uniform, array);
  13911. };
  13912. /**
  13913. * Set the value of an uniform to an array of float32 (stored as matrices)
  13914. * @param uniform defines the webGL uniform location where to store the value
  13915. * @param matrices defines the array of float32 to store
  13916. */
  13917. Engine.prototype.setMatrices = function (uniform, matrices) {
  13918. if (!uniform)
  13919. return;
  13920. this._gl.uniformMatrix4fv(uniform, false, matrices);
  13921. };
  13922. /**
  13923. * Set the value of an uniform to a matrix
  13924. * @param uniform defines the webGL uniform location where to store the value
  13925. * @param matrix defines the matrix to store
  13926. */
  13927. Engine.prototype.setMatrix = function (uniform, matrix) {
  13928. if (!uniform)
  13929. return;
  13930. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  13931. };
  13932. /**
  13933. * Set the value of an uniform to a matrix (3x3)
  13934. * @param uniform defines the webGL uniform location where to store the value
  13935. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  13936. */
  13937. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  13938. if (!uniform)
  13939. return;
  13940. this._gl.uniformMatrix3fv(uniform, false, matrix);
  13941. };
  13942. /**
  13943. * Set the value of an uniform to a matrix (2x2)
  13944. * @param uniform defines the webGL uniform location where to store the value
  13945. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  13946. */
  13947. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  13948. if (!uniform)
  13949. return;
  13950. this._gl.uniformMatrix2fv(uniform, false, matrix);
  13951. };
  13952. /**
  13953. * Set the value of an uniform to a number (int)
  13954. * @param uniform defines the webGL uniform location where to store the value
  13955. * @param value defines the int number to store
  13956. */
  13957. Engine.prototype.setInt = function (uniform, value) {
  13958. if (!uniform)
  13959. return;
  13960. this._gl.uniform1i(uniform, value);
  13961. };
  13962. /**
  13963. * Set the value of an uniform to a number (float)
  13964. * @param uniform defines the webGL uniform location where to store the value
  13965. * @param value defines the float number to store
  13966. */
  13967. Engine.prototype.setFloat = function (uniform, value) {
  13968. if (!uniform)
  13969. return;
  13970. this._gl.uniform1f(uniform, value);
  13971. };
  13972. /**
  13973. * Set the value of an uniform to a vec2
  13974. * @param uniform defines the webGL uniform location where to store the value
  13975. * @param x defines the 1st component of the value
  13976. * @param y defines the 2nd component of the value
  13977. */
  13978. Engine.prototype.setFloat2 = function (uniform, x, y) {
  13979. if (!uniform)
  13980. return;
  13981. this._gl.uniform2f(uniform, x, y);
  13982. };
  13983. /**
  13984. * Set the value of an uniform to a vec3
  13985. * @param uniform defines the webGL uniform location where to store the value
  13986. * @param x defines the 1st component of the value
  13987. * @param y defines the 2nd component of the value
  13988. * @param z defines the 3rd component of the value
  13989. */
  13990. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  13991. if (!uniform)
  13992. return;
  13993. this._gl.uniform3f(uniform, x, y, z);
  13994. };
  13995. /**
  13996. * Set the value of an uniform to a boolean
  13997. * @param uniform defines the webGL uniform location where to store the value
  13998. * @param bool defines the boolean to store
  13999. */
  14000. Engine.prototype.setBool = function (uniform, bool) {
  14001. if (!uniform)
  14002. return;
  14003. this._gl.uniform1i(uniform, bool);
  14004. };
  14005. /**
  14006. * Set the value of an uniform to a vec4
  14007. * @param uniform defines the webGL uniform location where to store the value
  14008. * @param x defines the 1st component of the value
  14009. * @param y defines the 2nd component of the value
  14010. * @param z defines the 3rd component of the value
  14011. * @param w defines the 4th component of the value
  14012. */
  14013. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14014. if (!uniform)
  14015. return;
  14016. this._gl.uniform4f(uniform, x, y, z, w);
  14017. };
  14018. /**
  14019. * Set the value of an uniform to a Color3
  14020. * @param uniform defines the webGL uniform location where to store the value
  14021. * @param color3 defines the color to store
  14022. */
  14023. Engine.prototype.setColor3 = function (uniform, color3) {
  14024. if (!uniform)
  14025. return;
  14026. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14027. };
  14028. /**
  14029. * Set the value of an uniform to a Color3 and an alpha value
  14030. * @param uniform defines the webGL uniform location where to store the value
  14031. * @param color3 defines the color to store
  14032. * @param alpha defines the alpha component to store
  14033. */
  14034. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14035. if (!uniform)
  14036. return;
  14037. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14038. };
  14039. /**
  14040. * Sets a Color4 on a uniform variable
  14041. * @param uniform defines the uniform location
  14042. * @param color4 defines the value to be set
  14043. */
  14044. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14045. if (!uniform)
  14046. return;
  14047. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14048. };
  14049. // States
  14050. /**
  14051. * Set various states to the webGL context
  14052. * @param culling defines backface culling state
  14053. * @param zOffset defines the value to apply to zOffset (0 by default)
  14054. * @param force defines if states must be applied even if cache is up to date
  14055. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14056. */
  14057. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14058. if (zOffset === void 0) { zOffset = 0; }
  14059. if (reverseSide === void 0) { reverseSide = false; }
  14060. // Culling
  14061. if (this._depthCullingState.cull !== culling || force) {
  14062. this._depthCullingState.cull = culling;
  14063. }
  14064. // Cull face
  14065. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14066. if (this._depthCullingState.cullFace !== cullFace || force) {
  14067. this._depthCullingState.cullFace = cullFace;
  14068. }
  14069. // Z offset
  14070. this.setZOffset(zOffset);
  14071. // Front face
  14072. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14073. if (this._depthCullingState.frontFace !== frontFace || force) {
  14074. this._depthCullingState.frontFace = frontFace;
  14075. }
  14076. };
  14077. /**
  14078. * Set the z offset to apply to current rendering
  14079. * @param value defines the offset to apply
  14080. */
  14081. Engine.prototype.setZOffset = function (value) {
  14082. this._depthCullingState.zOffset = value;
  14083. };
  14084. /**
  14085. * Gets the current value of the zOffset
  14086. * @returns the current zOffset state
  14087. */
  14088. Engine.prototype.getZOffset = function () {
  14089. return this._depthCullingState.zOffset;
  14090. };
  14091. /**
  14092. * Enable or disable depth buffering
  14093. * @param enable defines the state to set
  14094. */
  14095. Engine.prototype.setDepthBuffer = function (enable) {
  14096. this._depthCullingState.depthTest = enable;
  14097. };
  14098. /**
  14099. * Gets a boolean indicating if depth writing is enabled
  14100. * @returns the current depth writing state
  14101. */
  14102. Engine.prototype.getDepthWrite = function () {
  14103. return this._depthCullingState.depthMask;
  14104. };
  14105. /**
  14106. * Enable or disable depth writing
  14107. * @param enable defines the state to set
  14108. */
  14109. Engine.prototype.setDepthWrite = function (enable) {
  14110. this._depthCullingState.depthMask = enable;
  14111. };
  14112. /**
  14113. * Enable or disable color writing
  14114. * @param enable defines the state to set
  14115. */
  14116. Engine.prototype.setColorWrite = function (enable) {
  14117. this._gl.colorMask(enable, enable, enable, enable);
  14118. this._colorWrite = enable;
  14119. };
  14120. /**
  14121. * Gets a boolean indicating if color writing is enabled
  14122. * @returns the current color writing state
  14123. */
  14124. Engine.prototype.getColorWrite = function () {
  14125. return this._colorWrite;
  14126. };
  14127. /**
  14128. * Sets alpha constants used by some alpha blending modes
  14129. * @param r defines the red component
  14130. * @param g defines the green component
  14131. * @param b defines the blue component
  14132. * @param a defines the alpha component
  14133. */
  14134. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14135. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14136. };
  14137. /**
  14138. * Sets the current alpha mode
  14139. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14140. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14141. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14142. */
  14143. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14144. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14145. if (this._alphaMode === mode) {
  14146. return;
  14147. }
  14148. switch (mode) {
  14149. case Engine.ALPHA_DISABLE:
  14150. this._alphaState.alphaBlend = false;
  14151. break;
  14152. case Engine.ALPHA_PREMULTIPLIED:
  14153. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14154. this._alphaState.alphaBlend = true;
  14155. break;
  14156. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14157. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14158. this._alphaState.alphaBlend = true;
  14159. break;
  14160. case Engine.ALPHA_COMBINE:
  14161. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14162. this._alphaState.alphaBlend = true;
  14163. break;
  14164. case Engine.ALPHA_ONEONE:
  14165. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14166. this._alphaState.alphaBlend = true;
  14167. break;
  14168. case Engine.ALPHA_ADD:
  14169. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14170. this._alphaState.alphaBlend = true;
  14171. break;
  14172. case Engine.ALPHA_SUBTRACT:
  14173. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14174. this._alphaState.alphaBlend = true;
  14175. break;
  14176. case Engine.ALPHA_MULTIPLY:
  14177. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14178. this._alphaState.alphaBlend = true;
  14179. break;
  14180. case Engine.ALPHA_MAXIMIZED:
  14181. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14182. this._alphaState.alphaBlend = true;
  14183. break;
  14184. case Engine.ALPHA_INTERPOLATE:
  14185. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14186. this._alphaState.alphaBlend = true;
  14187. break;
  14188. case Engine.ALPHA_SCREENMODE:
  14189. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14190. this._alphaState.alphaBlend = true;
  14191. break;
  14192. }
  14193. if (!noDepthWriteChange) {
  14194. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14195. }
  14196. this._alphaMode = mode;
  14197. };
  14198. /**
  14199. * Gets the current alpha mode
  14200. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14201. * @returns the current alpha mode
  14202. */
  14203. Engine.prototype.getAlphaMode = function () {
  14204. return this._alphaMode;
  14205. };
  14206. // Textures
  14207. /**
  14208. * Clears the list of texture accessible through engine.
  14209. * This can help preventing texture load conflict due to name collision.
  14210. */
  14211. Engine.prototype.clearInternalTexturesCache = function () {
  14212. this._internalTexturesCache = [];
  14213. };
  14214. /**
  14215. * Force the entire cache to be cleared
  14216. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14217. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14218. */
  14219. Engine.prototype.wipeCaches = function (bruteForce) {
  14220. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14221. return;
  14222. }
  14223. this._currentEffect = null;
  14224. this._unpackFlipYCached = null;
  14225. this._viewportCached.x = 0;
  14226. this._viewportCached.y = 0;
  14227. this._viewportCached.z = 0;
  14228. this._viewportCached.w = 0;
  14229. if (bruteForce) {
  14230. this.resetTextureCache();
  14231. this._currentProgram = null;
  14232. this._stencilState.reset();
  14233. this._depthCullingState.reset();
  14234. this.setDepthFunctionToLessOrEqual();
  14235. this._alphaState.reset();
  14236. }
  14237. this._resetVertexBufferBinding();
  14238. this._cachedIndexBuffer = null;
  14239. this._cachedEffectForVertexBuffers = null;
  14240. this._unbindVertexArrayObject();
  14241. this.bindIndexBuffer(null);
  14242. };
  14243. /**
  14244. * Set the compressed texture format to use, based on the formats you have, and the formats
  14245. * supported by the hardware / browser.
  14246. *
  14247. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14248. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14249. * to API arguments needed to compressed textures. This puts the burden on the container
  14250. * generator to house the arcane code for determining these for current & future formats.
  14251. *
  14252. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14253. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14254. *
  14255. * Note: The result of this call is not taken into account when a texture is base64.
  14256. *
  14257. * @param formatsAvailable defines the list of those format families you have created
  14258. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14259. *
  14260. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14261. * @returns The extension selected.
  14262. */
  14263. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14264. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14265. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14266. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14267. return this._textureFormatInUse = this._texturesSupported[i];
  14268. }
  14269. }
  14270. }
  14271. // actively set format to nothing, to allow this to be called more than once
  14272. // and possibly fail the 2nd time
  14273. this._textureFormatInUse = null;
  14274. return null;
  14275. };
  14276. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  14277. var gl = this._gl;
  14278. var magFilter = gl.NEAREST;
  14279. var minFilter = gl.NEAREST;
  14280. switch (samplingMode) {
  14281. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  14282. magFilter = gl.LINEAR;
  14283. if (generateMipMaps) {
  14284. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14285. }
  14286. else {
  14287. minFilter = gl.LINEAR;
  14288. }
  14289. break;
  14290. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  14291. magFilter = gl.LINEAR;
  14292. if (generateMipMaps) {
  14293. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14294. }
  14295. else {
  14296. minFilter = gl.LINEAR;
  14297. }
  14298. break;
  14299. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  14300. magFilter = gl.NEAREST;
  14301. if (generateMipMaps) {
  14302. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14303. }
  14304. else {
  14305. minFilter = gl.NEAREST;
  14306. }
  14307. break;
  14308. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  14309. magFilter = gl.NEAREST;
  14310. if (generateMipMaps) {
  14311. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14312. }
  14313. else {
  14314. minFilter = gl.NEAREST;
  14315. }
  14316. break;
  14317. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  14318. magFilter = gl.NEAREST;
  14319. if (generateMipMaps) {
  14320. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  14321. }
  14322. else {
  14323. minFilter = gl.LINEAR;
  14324. }
  14325. break;
  14326. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  14327. magFilter = gl.NEAREST;
  14328. if (generateMipMaps) {
  14329. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  14330. }
  14331. else {
  14332. minFilter = gl.LINEAR;
  14333. }
  14334. break;
  14335. case Engine.TEXTURE_NEAREST_LINEAR:
  14336. magFilter = gl.NEAREST;
  14337. minFilter = gl.LINEAR;
  14338. break;
  14339. case Engine.TEXTURE_NEAREST_NEAREST:
  14340. magFilter = gl.NEAREST;
  14341. minFilter = gl.NEAREST;
  14342. break;
  14343. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  14344. magFilter = gl.LINEAR;
  14345. if (generateMipMaps) {
  14346. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  14347. }
  14348. else {
  14349. minFilter = gl.NEAREST;
  14350. }
  14351. break;
  14352. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  14353. magFilter = gl.LINEAR;
  14354. if (generateMipMaps) {
  14355. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  14356. }
  14357. else {
  14358. minFilter = gl.NEAREST;
  14359. }
  14360. break;
  14361. case Engine.TEXTURE_LINEAR_LINEAR:
  14362. magFilter = gl.LINEAR;
  14363. minFilter = gl.LINEAR;
  14364. break;
  14365. case Engine.TEXTURE_LINEAR_NEAREST:
  14366. magFilter = gl.LINEAR;
  14367. minFilter = gl.NEAREST;
  14368. break;
  14369. }
  14370. return {
  14371. min: minFilter,
  14372. mag: magFilter
  14373. };
  14374. };
  14375. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  14376. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14377. var img;
  14378. var onload = function () {
  14379. loadedImages[index] = img;
  14380. loadedImages._internalCount++;
  14381. if (scene) {
  14382. scene._removePendingData(img);
  14383. }
  14384. if (loadedImages._internalCount === 6) {
  14385. onfinish(loadedImages);
  14386. }
  14387. };
  14388. var onerror = function (message, exception) {
  14389. if (scene) {
  14390. scene._removePendingData(img);
  14391. }
  14392. if (onErrorCallBack) {
  14393. onErrorCallBack(message, exception);
  14394. }
  14395. };
  14396. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14397. if (scene) {
  14398. scene._addPendingData(img);
  14399. }
  14400. };
  14401. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  14402. if (onError === void 0) { onError = null; }
  14403. var loadedImages = [];
  14404. loadedImages._internalCount = 0;
  14405. for (var index = 0; index < 6; index++) {
  14406. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  14407. }
  14408. };
  14409. ;
  14410. /** @hidden */
  14411. Engine.prototype._createTexture = function () {
  14412. var texture = this._gl.createTexture();
  14413. if (!texture) {
  14414. throw new Error("Unable to create texture");
  14415. }
  14416. return texture;
  14417. };
  14418. /**
  14419. * Usually called from BABYLON.Texture.ts.
  14420. * Passed information to create a WebGLTexture
  14421. * @param urlArg defines a value which contains one of the following:
  14422. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14423. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14424. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14425. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14426. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14427. * @param scene needed for loading to the correct scene
  14428. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14429. * @param onLoad optional callback to be called upon successful completion
  14430. * @param onError optional callback to be called upon failure
  14431. * @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
  14432. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14433. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14434. * @param forcedExtension defines the extension to use to pick the right loader
  14435. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14436. */
  14437. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  14438. var _this = this;
  14439. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  14440. if (onLoad === void 0) { onLoad = null; }
  14441. if (onError === void 0) { onError = null; }
  14442. if (buffer === void 0) { buffer = null; }
  14443. if (fallback === void 0) { fallback = null; }
  14444. if (format === void 0) { format = null; }
  14445. if (forcedExtension === void 0) { forcedExtension = null; }
  14446. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14447. var fromData = url.substr(0, 5) === "data:";
  14448. var fromBlob = url.substr(0, 5) === "blob:";
  14449. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14450. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14451. // establish the file extension, if possible
  14452. var lastDot = url.lastIndexOf('.');
  14453. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  14454. var loader = null;
  14455. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  14456. var availableLoader = _a[_i];
  14457. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  14458. loader = availableLoader;
  14459. break;
  14460. }
  14461. }
  14462. if (loader) {
  14463. url = loader.transformUrl(url, this._textureFormatInUse);
  14464. }
  14465. if (scene) {
  14466. scene._addPendingData(texture);
  14467. }
  14468. texture.url = url;
  14469. texture.generateMipMaps = !noMipmap;
  14470. texture.samplingMode = samplingMode;
  14471. texture.invertY = invertY;
  14472. if (!this._doNotHandleContextLost) {
  14473. // Keep a link to the buffer only if we plan to handle context lost
  14474. texture._buffer = buffer;
  14475. }
  14476. var onLoadObserver = null;
  14477. if (onLoad && !fallback) {
  14478. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14479. }
  14480. if (!fallback)
  14481. this._internalTexturesCache.push(texture);
  14482. var onInternalError = function (message, exception) {
  14483. if (scene) {
  14484. scene._removePendingData(texture);
  14485. }
  14486. var customFallback = false;
  14487. if (loader) {
  14488. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  14489. if (fallbackUrl) {
  14490. // Add Back
  14491. customFallback = true;
  14492. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14493. }
  14494. }
  14495. if (!customFallback) {
  14496. if (onLoadObserver) {
  14497. texture.onLoadedObservable.remove(onLoadObserver);
  14498. }
  14499. if (BABYLON.Tools.UseFallbackTexture) {
  14500. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14501. }
  14502. }
  14503. if (onError) {
  14504. onError(message || "Unknown error", exception);
  14505. }
  14506. };
  14507. // processing for non-image formats
  14508. if (loader) {
  14509. var callback = function (data) {
  14510. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  14511. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  14512. done();
  14513. return false;
  14514. }, samplingMode);
  14515. });
  14516. };
  14517. if (!buffer) {
  14518. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14519. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  14520. });
  14521. }
  14522. else {
  14523. callback(buffer);
  14524. }
  14525. }
  14526. else {
  14527. var onload = function (img) {
  14528. if (fromBlob && !_this._doNotHandleContextLost) {
  14529. // We need to store the image if we need to rebuild the texture
  14530. // in case of a webgl context lost
  14531. texture._buffer = img;
  14532. }
  14533. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14534. var gl = _this._gl;
  14535. var isPot = (img.width === potWidth && img.height === potHeight);
  14536. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14537. if (isPot) {
  14538. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14539. return false;
  14540. }
  14541. var maxTextureSize = _this._caps.maxTextureSize;
  14542. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14543. _this._prepareWorkingCanvas();
  14544. if (!_this._workingCanvas || !_this._workingContext) {
  14545. return false;
  14546. }
  14547. _this._workingCanvas.width = potWidth;
  14548. _this._workingCanvas.height = potHeight;
  14549. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14550. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14551. texture.width = potWidth;
  14552. texture.height = potHeight;
  14553. return false;
  14554. }
  14555. else {
  14556. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14557. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14558. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14559. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14560. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14561. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14562. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14563. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14564. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14565. _this._releaseTexture(source_1);
  14566. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14567. continuationCallback();
  14568. });
  14569. }
  14570. return true;
  14571. }, samplingMode);
  14572. };
  14573. if (!fromData || isBase64) {
  14574. if (buffer instanceof HTMLImageElement) {
  14575. onload(buffer);
  14576. }
  14577. else {
  14578. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  14579. }
  14580. }
  14581. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14582. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  14583. }
  14584. else {
  14585. onload(buffer);
  14586. }
  14587. }
  14588. return texture;
  14589. };
  14590. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14591. var _this = this;
  14592. var rtt = this.createRenderTargetTexture({
  14593. width: destination.width,
  14594. height: destination.height,
  14595. }, {
  14596. generateMipMaps: false,
  14597. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14598. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  14599. generateDepthBuffer: false,
  14600. generateStencilBuffer: false
  14601. });
  14602. if (!this._rescalePostProcess) {
  14603. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14604. }
  14605. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14606. _this._rescalePostProcess.onApply = function (effect) {
  14607. effect._bindTexture("textureSampler", source);
  14608. };
  14609. var hostingScene = scene;
  14610. if (!hostingScene) {
  14611. hostingScene = _this.scenes[_this.scenes.length - 1];
  14612. }
  14613. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14614. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14615. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14616. _this.unBindFramebuffer(rtt);
  14617. _this._releaseTexture(rtt);
  14618. if (onComplete) {
  14619. onComplete();
  14620. }
  14621. });
  14622. };
  14623. /**
  14624. * Update a raw texture
  14625. * @param texture defines the texture to update
  14626. * @param data defines the data to store in the texture
  14627. * @param format defines the format of the data
  14628. * @param invertY defines if data must be stored with Y axis inverted
  14629. * @param compression defines the compression used (null by default)
  14630. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14631. */
  14632. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14633. if (compression === void 0) { compression = null; }
  14634. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14635. if (!texture) {
  14636. return;
  14637. }
  14638. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14639. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14640. // babylon's internalFormat but gl's texImage2D format
  14641. var internalFormat = this._getInternalFormat(format);
  14642. var textureType = this._getWebGLTextureType(type);
  14643. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14644. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14645. if (!this._doNotHandleContextLost) {
  14646. texture._bufferView = data;
  14647. texture.format = format;
  14648. texture.type = type;
  14649. texture.invertY = invertY;
  14650. texture._compression = compression;
  14651. }
  14652. if (texture.width % 4 !== 0) {
  14653. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14654. }
  14655. if (compression && data) {
  14656. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14657. }
  14658. else {
  14659. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14660. }
  14661. if (texture.generateMipMaps) {
  14662. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14663. }
  14664. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14665. // this.resetTextureCache();
  14666. texture.isReady = true;
  14667. };
  14668. /**
  14669. * Creates a raw texture
  14670. * @param data defines the data to store in the texture
  14671. * @param width defines the width of the texture
  14672. * @param height defines the height of the texture
  14673. * @param format defines the format of the data
  14674. * @param generateMipMaps defines if the engine should generate the mip levels
  14675. * @param invertY defines if data must be stored with Y axis inverted
  14676. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14677. * @param compression defines the compression used (null by default)
  14678. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14679. * @returns the raw texture inside an InternalTexture
  14680. */
  14681. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14682. if (compression === void 0) { compression = null; }
  14683. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14684. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14685. texture.baseWidth = width;
  14686. texture.baseHeight = height;
  14687. texture.width = width;
  14688. texture.height = height;
  14689. texture.format = format;
  14690. texture.generateMipMaps = generateMipMaps;
  14691. texture.samplingMode = samplingMode;
  14692. texture.invertY = invertY;
  14693. texture._compression = compression;
  14694. texture.type = type;
  14695. if (!this._doNotHandleContextLost) {
  14696. texture._bufferView = data;
  14697. }
  14698. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14699. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14700. // Filters
  14701. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  14702. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14703. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14704. if (generateMipMaps) {
  14705. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14706. }
  14707. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14708. this._internalTexturesCache.push(texture);
  14709. return texture;
  14710. };
  14711. /** @hidden */
  14712. Engine.prototype._unpackFlipY = function (value) {
  14713. if (this._unpackFlipYCached !== value) {
  14714. this._unpackFlipYCached = value;
  14715. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14716. }
  14717. };
  14718. /** @hidden */
  14719. Engine.prototype._getUnpackAlignement = function () {
  14720. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  14721. };
  14722. /**
  14723. * Creates a dynamic texture
  14724. * @param width defines the width of the texture
  14725. * @param height defines the height of the texture
  14726. * @param generateMipMaps defines if the engine should generate the mip levels
  14727. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14728. * @returns the dynamic texture inside an InternalTexture
  14729. */
  14730. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14731. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14732. texture.baseWidth = width;
  14733. texture.baseHeight = height;
  14734. if (generateMipMaps) {
  14735. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14736. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14737. }
  14738. // this.resetTextureCache();
  14739. texture.width = width;
  14740. texture.height = height;
  14741. texture.isReady = false;
  14742. texture.generateMipMaps = generateMipMaps;
  14743. texture.samplingMode = samplingMode;
  14744. this.updateTextureSamplingMode(samplingMode, texture);
  14745. this._internalTexturesCache.push(texture);
  14746. return texture;
  14747. };
  14748. /**
  14749. * Update the sampling mode of a given texture
  14750. * @param samplingMode defines the required sampling mode
  14751. * @param texture defines the texture to update
  14752. */
  14753. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14754. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  14755. if (texture.isCube) {
  14756. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14757. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14758. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14759. }
  14760. else if (texture.is3D) {
  14761. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14762. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14763. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14764. }
  14765. else {
  14766. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14767. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14768. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14769. }
  14770. texture.samplingMode = samplingMode;
  14771. };
  14772. /**
  14773. * Update the content of a dynamic texture
  14774. * @param texture defines the texture to update
  14775. * @param canvas defines the canvas containing the source
  14776. * @param invertY defines if data must be stored with Y axis inverted
  14777. * @param premulAlpha defines if alpha is stored as premultiplied
  14778. * @param format defines the format of the data
  14779. */
  14780. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14781. if (premulAlpha === void 0) { premulAlpha = false; }
  14782. if (!texture) {
  14783. return;
  14784. }
  14785. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14786. this._unpackFlipY(invertY);
  14787. if (premulAlpha) {
  14788. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14789. }
  14790. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14791. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14792. if (texture.generateMipMaps) {
  14793. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14794. }
  14795. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14796. if (premulAlpha) {
  14797. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14798. }
  14799. texture.isReady = true;
  14800. };
  14801. /**
  14802. * Update a video texture
  14803. * @param texture defines the texture to update
  14804. * @param video defines the video element to use
  14805. * @param invertY defines if data must be stored with Y axis inverted
  14806. */
  14807. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14808. if (!texture || texture._isDisabled) {
  14809. return;
  14810. }
  14811. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14812. this._unpackFlipY(!invertY); // Video are upside down by default
  14813. try {
  14814. // Testing video texture support
  14815. if (this._videoTextureSupported === undefined) {
  14816. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14817. if (this._gl.getError() !== 0) {
  14818. this._videoTextureSupported = false;
  14819. }
  14820. else {
  14821. this._videoTextureSupported = true;
  14822. }
  14823. }
  14824. // Copy video through the current working canvas if video texture is not supported
  14825. if (!this._videoTextureSupported) {
  14826. if (!texture._workingCanvas) {
  14827. texture._workingCanvas = document.createElement("canvas");
  14828. var context = texture._workingCanvas.getContext("2d");
  14829. if (!context) {
  14830. throw new Error("Unable to get 2d context");
  14831. }
  14832. texture._workingContext = context;
  14833. texture._workingCanvas.width = texture.width;
  14834. texture._workingCanvas.height = texture.height;
  14835. }
  14836. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14837. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14838. }
  14839. else {
  14840. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14841. }
  14842. if (texture.generateMipMaps) {
  14843. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14844. }
  14845. if (!wasPreviouslyBound) {
  14846. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14847. }
  14848. // this.resetTextureCache();
  14849. texture.isReady = true;
  14850. }
  14851. catch (ex) {
  14852. // Something unexpected
  14853. // Let's disable the texture
  14854. texture._isDisabled = true;
  14855. }
  14856. };
  14857. /**
  14858. * Updates a depth texture Comparison Mode and Function.
  14859. * If the comparison Function is equal to 0, the mode will be set to none.
  14860. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14861. * @param texture The texture to set the comparison function for
  14862. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14863. */
  14864. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14865. if (this.webGLVersion === 1) {
  14866. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14867. return;
  14868. }
  14869. var gl = this._gl;
  14870. if (texture.isCube) {
  14871. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14872. if (comparisonFunction === 0) {
  14873. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14874. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14875. }
  14876. else {
  14877. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14878. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14879. }
  14880. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14881. }
  14882. else {
  14883. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14884. if (comparisonFunction === 0) {
  14885. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14886. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14887. }
  14888. else {
  14889. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14890. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14891. }
  14892. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14893. }
  14894. texture._comparisonFunction = comparisonFunction;
  14895. };
  14896. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14897. var width = size.width || size;
  14898. var height = size.height || size;
  14899. internalTexture.baseWidth = width;
  14900. internalTexture.baseHeight = height;
  14901. internalTexture.width = width;
  14902. internalTexture.height = height;
  14903. internalTexture.isReady = true;
  14904. internalTexture.samples = 1;
  14905. internalTexture.generateMipMaps = false;
  14906. internalTexture._generateDepthBuffer = true;
  14907. internalTexture._generateStencilBuffer = generateStencil;
  14908. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  14909. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14910. internalTexture._comparisonFunction = comparisonFunction;
  14911. var gl = this._gl;
  14912. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14913. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  14914. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14915. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14916. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14917. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14918. if (comparisonFunction === 0) {
  14919. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14920. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14921. }
  14922. else {
  14923. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14924. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14925. }
  14926. };
  14927. /**
  14928. * Creates a depth stencil texture.
  14929. * This is only available in WebGL 2 or with the depth texture extension available.
  14930. * @param size The size of face edge in the texture.
  14931. * @param options The options defining the texture.
  14932. * @returns The texture
  14933. */
  14934. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14935. if (options.isCube) {
  14936. var width = size.width || size;
  14937. return this._createDepthStencilCubeTexture(width, options);
  14938. }
  14939. else {
  14940. return this._createDepthStencilTexture(size, options);
  14941. }
  14942. };
  14943. /**
  14944. * Creates a depth stencil texture.
  14945. * This is only available in WebGL 2 or with the depth texture extension available.
  14946. * @param size The size of face edge in the texture.
  14947. * @param options The options defining the texture.
  14948. * @returns The texture
  14949. */
  14950. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14951. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14952. if (!this._caps.depthTextureExtension) {
  14953. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14954. return internalTexture;
  14955. }
  14956. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14957. var gl = this._gl;
  14958. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14959. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14960. if (this.webGLVersion > 1) {
  14961. if (internalOptions.generateStencil) {
  14962. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14963. }
  14964. else {
  14965. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14966. }
  14967. }
  14968. else {
  14969. if (internalOptions.generateStencil) {
  14970. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14971. }
  14972. else {
  14973. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14974. }
  14975. }
  14976. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14977. return internalTexture;
  14978. };
  14979. /**
  14980. * Creates a depth stencil cube texture.
  14981. * This is only available in WebGL 2.
  14982. * @param size The size of face edge in the cube texture.
  14983. * @param options The options defining the cube texture.
  14984. * @returns The cube texture
  14985. */
  14986. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  14987. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  14988. internalTexture.isCube = true;
  14989. if (this.webGLVersion === 1) {
  14990. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  14991. return internalTexture;
  14992. }
  14993. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14994. var gl = this._gl;
  14995. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  14996. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14997. // Create the depth/stencil buffer
  14998. for (var face = 0; face < 6; face++) {
  14999. if (internalOptions.generateStencil) {
  15000. 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);
  15001. }
  15002. else {
  15003. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15004. }
  15005. }
  15006. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15007. return internalTexture;
  15008. };
  15009. /**
  15010. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15011. * @param renderTarget The render target to set the frame buffer for
  15012. */
  15013. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15014. // Create the framebuffer
  15015. var internalTexture = renderTarget.getInternalTexture();
  15016. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15017. return;
  15018. }
  15019. var gl = this._gl;
  15020. var depthStencilTexture = renderTarget.depthStencilTexture;
  15021. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15022. if (depthStencilTexture.isCube) {
  15023. if (depthStencilTexture._generateStencilBuffer) {
  15024. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15025. }
  15026. else {
  15027. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15028. }
  15029. }
  15030. else {
  15031. if (depthStencilTexture._generateStencilBuffer) {
  15032. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15033. }
  15034. else {
  15035. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15036. }
  15037. }
  15038. this.bindUnboundFramebuffer(null);
  15039. };
  15040. /**
  15041. * Creates a new render target texture
  15042. * @param size defines the size of the texture
  15043. * @param options defines the options used to create the texture
  15044. * @returns a new render target texture stored in an InternalTexture
  15045. */
  15046. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15047. var fullOptions = new RenderTargetCreationOptions();
  15048. if (options !== undefined && typeof options === "object") {
  15049. fullOptions.generateMipMaps = options.generateMipMaps;
  15050. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15051. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15052. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15053. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15054. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15055. }
  15056. else {
  15057. fullOptions.generateMipMaps = options;
  15058. fullOptions.generateDepthBuffer = true;
  15059. fullOptions.generateStencilBuffer = false;
  15060. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15061. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15062. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15063. }
  15064. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15065. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15066. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15067. }
  15068. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15069. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15070. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15071. }
  15072. var gl = this._gl;
  15073. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15074. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15075. var width = size.width || size;
  15076. var height = size.height || size;
  15077. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15078. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15079. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15080. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15081. }
  15082. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15083. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15084. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15085. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15086. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15087. // Create the framebuffer
  15088. var currentFrameBuffer = this._currentFramebuffer;
  15089. var framebuffer = gl.createFramebuffer();
  15090. this.bindUnboundFramebuffer(framebuffer);
  15091. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15092. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15093. if (fullOptions.generateMipMaps) {
  15094. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15095. }
  15096. // Unbind
  15097. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15098. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15099. this.bindUnboundFramebuffer(currentFrameBuffer);
  15100. texture._framebuffer = framebuffer;
  15101. texture.baseWidth = width;
  15102. texture.baseHeight = height;
  15103. texture.width = width;
  15104. texture.height = height;
  15105. texture.isReady = true;
  15106. texture.samples = 1;
  15107. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15108. texture.samplingMode = fullOptions.samplingMode;
  15109. texture.type = fullOptions.type;
  15110. texture.format = fullOptions.format;
  15111. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15112. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15113. // this.resetTextureCache();
  15114. this._internalTexturesCache.push(texture);
  15115. return texture;
  15116. };
  15117. /**
  15118. * Create a multi render target texture
  15119. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15120. * @param size defines the size of the texture
  15121. * @param options defines the creation options
  15122. * @returns the cube texture as an InternalTexture
  15123. */
  15124. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15125. var generateMipMaps = false;
  15126. var generateDepthBuffer = true;
  15127. var generateStencilBuffer = false;
  15128. var generateDepthTexture = false;
  15129. var textureCount = 1;
  15130. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15131. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15132. var types = new Array();
  15133. var samplingModes = new Array();
  15134. if (options !== undefined) {
  15135. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15136. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15137. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15138. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15139. textureCount = options.textureCount || 1;
  15140. if (options.types) {
  15141. types = options.types;
  15142. }
  15143. if (options.samplingModes) {
  15144. samplingModes = options.samplingModes;
  15145. }
  15146. }
  15147. var gl = this._gl;
  15148. // Create the framebuffer
  15149. var framebuffer = gl.createFramebuffer();
  15150. this.bindUnboundFramebuffer(framebuffer);
  15151. var width = size.width || size;
  15152. var height = size.height || size;
  15153. var textures = [];
  15154. var attachments = [];
  15155. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15156. for (var i = 0; i < textureCount; i++) {
  15157. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15158. var type = types[i] || defaultType;
  15159. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15160. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15161. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15162. }
  15163. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15164. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15165. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15166. }
  15167. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15168. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15169. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15170. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15171. }
  15172. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15173. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15174. textures.push(texture);
  15175. attachments.push(attachment);
  15176. gl.activeTexture(gl["TEXTURE" + i]);
  15177. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15178. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15179. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15180. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15181. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15182. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15183. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15184. if (generateMipMaps) {
  15185. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15186. }
  15187. // Unbind
  15188. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15189. texture._framebuffer = framebuffer;
  15190. texture._depthStencilBuffer = depthStencilBuffer;
  15191. texture.baseWidth = width;
  15192. texture.baseHeight = height;
  15193. texture.width = width;
  15194. texture.height = height;
  15195. texture.isReady = true;
  15196. texture.samples = 1;
  15197. texture.generateMipMaps = generateMipMaps;
  15198. texture.samplingMode = samplingMode;
  15199. texture.type = type;
  15200. texture._generateDepthBuffer = generateDepthBuffer;
  15201. texture._generateStencilBuffer = generateStencilBuffer;
  15202. texture._attachments = attachments;
  15203. this._internalTexturesCache.push(texture);
  15204. }
  15205. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15206. // Depth texture
  15207. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15208. gl.activeTexture(gl.TEXTURE0);
  15209. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15210. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15211. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15212. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15213. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15214. 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);
  15215. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15216. depthTexture._framebuffer = framebuffer;
  15217. depthTexture.baseWidth = width;
  15218. depthTexture.baseHeight = height;
  15219. depthTexture.width = width;
  15220. depthTexture.height = height;
  15221. depthTexture.isReady = true;
  15222. depthTexture.samples = 1;
  15223. depthTexture.generateMipMaps = generateMipMaps;
  15224. depthTexture.samplingMode = gl.NEAREST;
  15225. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15226. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15227. textures.push(depthTexture);
  15228. this._internalTexturesCache.push(depthTexture);
  15229. }
  15230. gl.drawBuffers(attachments);
  15231. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15232. this.bindUnboundFramebuffer(null);
  15233. this.resetTextureCache();
  15234. return textures;
  15235. };
  15236. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15237. if (samples === void 0) { samples = 1; }
  15238. var depthStencilBuffer = null;
  15239. var gl = this._gl;
  15240. // Create the depth/stencil buffer
  15241. if (generateStencilBuffer) {
  15242. depthStencilBuffer = gl.createRenderbuffer();
  15243. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15244. if (samples > 1) {
  15245. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15246. }
  15247. else {
  15248. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15249. }
  15250. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15251. }
  15252. else if (generateDepthBuffer) {
  15253. depthStencilBuffer = gl.createRenderbuffer();
  15254. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15255. if (samples > 1) {
  15256. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15257. }
  15258. else {
  15259. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15260. }
  15261. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15262. }
  15263. return depthStencilBuffer;
  15264. };
  15265. /**
  15266. * Updates the sample count of a render target texture
  15267. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15268. * @param texture defines the texture to update
  15269. * @param samples defines the sample count to set
  15270. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15271. */
  15272. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15273. if (this.webGLVersion < 2 || !texture) {
  15274. return 1;
  15275. }
  15276. if (texture.samples === samples) {
  15277. return samples;
  15278. }
  15279. var gl = this._gl;
  15280. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15281. // Dispose previous render buffers
  15282. if (texture._depthStencilBuffer) {
  15283. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15284. texture._depthStencilBuffer = null;
  15285. }
  15286. if (texture._MSAAFramebuffer) {
  15287. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15288. texture._MSAAFramebuffer = null;
  15289. }
  15290. if (texture._MSAARenderBuffer) {
  15291. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15292. texture._MSAARenderBuffer = null;
  15293. }
  15294. if (samples > 1) {
  15295. var framebuffer = gl.createFramebuffer();
  15296. if (!framebuffer) {
  15297. throw new Error("Unable to create multi sampled framebuffer");
  15298. }
  15299. texture._MSAAFramebuffer = framebuffer;
  15300. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15301. var colorRenderbuffer = gl.createRenderbuffer();
  15302. if (!colorRenderbuffer) {
  15303. throw new Error("Unable to create multi sampled framebuffer");
  15304. }
  15305. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15306. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15307. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15308. texture._MSAARenderBuffer = colorRenderbuffer;
  15309. }
  15310. else {
  15311. this.bindUnboundFramebuffer(texture._framebuffer);
  15312. }
  15313. texture.samples = samples;
  15314. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15315. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15316. this.bindUnboundFramebuffer(null);
  15317. return samples;
  15318. };
  15319. /**
  15320. * Update the sample count for a given multiple render target texture
  15321. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15322. * @param textures defines the textures to update
  15323. * @param samples defines the sample count to set
  15324. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15325. */
  15326. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15327. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15328. return 1;
  15329. }
  15330. if (textures[0].samples === samples) {
  15331. return samples;
  15332. }
  15333. var gl = this._gl;
  15334. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15335. // Dispose previous render buffers
  15336. if (textures[0]._depthStencilBuffer) {
  15337. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15338. textures[0]._depthStencilBuffer = null;
  15339. }
  15340. if (textures[0]._MSAAFramebuffer) {
  15341. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15342. textures[0]._MSAAFramebuffer = null;
  15343. }
  15344. for (var i = 0; i < textures.length; i++) {
  15345. if (textures[i]._MSAARenderBuffer) {
  15346. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15347. textures[i]._MSAARenderBuffer = null;
  15348. }
  15349. }
  15350. if (samples > 1) {
  15351. var framebuffer = gl.createFramebuffer();
  15352. if (!framebuffer) {
  15353. throw new Error("Unable to create multi sampled framebuffer");
  15354. }
  15355. this.bindUnboundFramebuffer(framebuffer);
  15356. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15357. var attachments = [];
  15358. for (var i = 0; i < textures.length; i++) {
  15359. var texture = textures[i];
  15360. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15361. var colorRenderbuffer = gl.createRenderbuffer();
  15362. if (!colorRenderbuffer) {
  15363. throw new Error("Unable to create multi sampled framebuffer");
  15364. }
  15365. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15366. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15367. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15368. texture._MSAAFramebuffer = framebuffer;
  15369. texture._MSAARenderBuffer = colorRenderbuffer;
  15370. texture.samples = samples;
  15371. texture._depthStencilBuffer = depthStencilBuffer;
  15372. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15373. attachments.push(attachment);
  15374. }
  15375. gl.drawBuffers(attachments);
  15376. }
  15377. else {
  15378. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15379. }
  15380. this.bindUnboundFramebuffer(null);
  15381. return samples;
  15382. };
  15383. /** @hidden */
  15384. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  15385. if (faceIndex === void 0) { faceIndex = 0; }
  15386. if (lod === void 0) { lod = 0; }
  15387. var gl = this._gl;
  15388. var target = gl.TEXTURE_2D;
  15389. if (texture.isCube) {
  15390. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15391. }
  15392. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15393. };
  15394. /** @hidden */
  15395. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  15396. if (faceIndex === void 0) { faceIndex = 0; }
  15397. if (lod === void 0) { lod = 0; }
  15398. var gl = this._gl;
  15399. var textureType = this._getWebGLTextureType(texture.type);
  15400. var format = this._getInternalFormat(texture.format);
  15401. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15402. this._unpackFlipY(texture.invertY);
  15403. var target = gl.TEXTURE_2D;
  15404. if (texture.isCube) {
  15405. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15406. }
  15407. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  15408. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  15409. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  15410. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  15411. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  15412. };
  15413. /** @hidden */
  15414. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  15415. if (faceIndex === void 0) { faceIndex = 0; }
  15416. if (lod === void 0) { lod = 0; }
  15417. var gl = this._gl;
  15418. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15419. this._bindTextureDirectly(bindTarget, texture, true);
  15420. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  15421. this._bindTextureDirectly(bindTarget, null, true);
  15422. };
  15423. /** @hidden */
  15424. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  15425. if (faceIndex === void 0) { faceIndex = 0; }
  15426. if (lod === void 0) { lod = 0; }
  15427. var gl = this._gl;
  15428. var textureType = this._getWebGLTextureType(texture.type);
  15429. var format = this._getInternalFormat(texture.format);
  15430. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15431. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15432. this._bindTextureDirectly(bindTarget, texture, true);
  15433. this._unpackFlipY(texture.invertY);
  15434. var target = gl.TEXTURE_2D;
  15435. if (texture.isCube) {
  15436. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15437. }
  15438. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15439. this._bindTextureDirectly(bindTarget, null, true);
  15440. };
  15441. /**
  15442. * Creates a new render target cube texture
  15443. * @param size defines the size of the texture
  15444. * @param options defines the options used to create the texture
  15445. * @returns a new render target cube texture stored in an InternalTexture
  15446. */
  15447. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15448. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15449. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15450. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15451. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15452. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15453. }
  15454. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15455. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15456. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15457. }
  15458. var gl = this._gl;
  15459. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15460. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15461. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  15462. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15463. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15464. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15465. }
  15466. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15467. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15468. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15469. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15470. for (var face = 0; face < 6; face++) {
  15471. 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);
  15472. }
  15473. // Create the framebuffer
  15474. var framebuffer = gl.createFramebuffer();
  15475. this.bindUnboundFramebuffer(framebuffer);
  15476. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15477. // MipMaps
  15478. if (fullOptions.generateMipMaps) {
  15479. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15480. }
  15481. // Unbind
  15482. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15483. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15484. this.bindUnboundFramebuffer(null);
  15485. texture._framebuffer = framebuffer;
  15486. texture.width = size;
  15487. texture.height = size;
  15488. texture.isReady = true;
  15489. texture.isCube = true;
  15490. texture.samples = 1;
  15491. texture.generateMipMaps = fullOptions.generateMipMaps;
  15492. texture.samplingMode = fullOptions.samplingMode;
  15493. texture.type = fullOptions.type;
  15494. texture.format = fullOptions.format;
  15495. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15496. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15497. this._internalTexturesCache.push(texture);
  15498. return texture;
  15499. };
  15500. /**
  15501. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15502. * @param rootUrl defines the url where the file to load is located
  15503. * @param scene defines the current scene
  15504. * @param lodScale defines scale to apply to the mip map selection
  15505. * @param lodOffset defines offset to apply to the mip map selection
  15506. * @param onLoad defines an optional callback raised when the texture is loaded
  15507. * @param onError defines an optional callback raised if there is an issue to load the texture
  15508. * @param format defines the format of the data
  15509. * @param forcedExtension defines the extension to use to pick the right loader
  15510. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15511. * @returns the cube texture as an InternalTexture
  15512. */
  15513. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15514. var _this = this;
  15515. if (onLoad === void 0) { onLoad = null; }
  15516. if (onError === void 0) { onError = null; }
  15517. if (forcedExtension === void 0) { forcedExtension = null; }
  15518. if (createPolynomials === void 0) { createPolynomials = true; }
  15519. var callback = function (loadData) {
  15520. if (!loadData) {
  15521. if (onLoad) {
  15522. onLoad(null);
  15523. }
  15524. return;
  15525. }
  15526. var texture = loadData.texture;
  15527. if (!createPolynomials) {
  15528. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15529. }
  15530. else if (loadData.info.sphericalPolynomial) {
  15531. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15532. }
  15533. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15534. if (_this._caps.textureLOD) {
  15535. // Do not add extra process if texture lod is supported.
  15536. if (onLoad) {
  15537. onLoad(texture);
  15538. }
  15539. return;
  15540. }
  15541. var mipSlices = 3;
  15542. var gl = _this._gl;
  15543. var width = loadData.width;
  15544. if (!width) {
  15545. return;
  15546. }
  15547. var textures = [];
  15548. for (var i = 0; i < mipSlices; i++) {
  15549. //compute LOD from even spacing in smoothness (matching shader calculation)
  15550. var smoothness = i / (mipSlices - 1);
  15551. var roughness = 1 - smoothness;
  15552. var minLODIndex = lodOffset; // roughness = 0
  15553. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15554. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15555. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15556. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15557. glTextureFromLod.type = texture.type;
  15558. glTextureFromLod.format = texture.format;
  15559. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  15560. glTextureFromLod.height = glTextureFromLod.width;
  15561. glTextureFromLod.isCube = true;
  15562. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15563. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15564. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15565. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15566. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15567. if (loadData.isDDS) {
  15568. var info = loadData.info;
  15569. var data = loadData.data;
  15570. _this._unpackFlipY(info.isCompressed);
  15571. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  15572. }
  15573. else {
  15574. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15575. }
  15576. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15577. // Wrap in a base texture for easy binding.
  15578. var lodTexture = new BABYLON.BaseTexture(scene);
  15579. lodTexture.isCube = true;
  15580. lodTexture._texture = glTextureFromLod;
  15581. glTextureFromLod.isReady = true;
  15582. textures.push(lodTexture);
  15583. }
  15584. texture._lodTextureHigh = textures[2];
  15585. texture._lodTextureMid = textures[1];
  15586. texture._lodTextureLow = textures[0];
  15587. if (onLoad) {
  15588. onLoad(texture);
  15589. }
  15590. };
  15591. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15592. };
  15593. /**
  15594. * Creates a cube texture
  15595. * @param rootUrl defines the url where the files to load is located
  15596. * @param scene defines the current scene
  15597. * @param files defines the list of files to load (1 per face)
  15598. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15599. * @param onLoad defines an optional callback raised when the texture is loaded
  15600. * @param onError defines an optional callback raised if there is an issue to load the texture
  15601. * @param format defines the format of the data
  15602. * @param forcedExtension defines the extension to use to pick the right loader
  15603. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15604. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15605. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15606. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15607. * @returns the cube texture as an InternalTexture
  15608. */
  15609. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15610. var _this = this;
  15611. if (onLoad === void 0) { onLoad = null; }
  15612. if (onError === void 0) { onError = null; }
  15613. if (forcedExtension === void 0) { forcedExtension = null; }
  15614. if (createPolynomials === void 0) { createPolynomials = false; }
  15615. if (lodScale === void 0) { lodScale = 0; }
  15616. if (lodOffset === void 0) { lodOffset = 0; }
  15617. if (fallback === void 0) { fallback = null; }
  15618. var gl = this._gl;
  15619. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15620. texture.isCube = true;
  15621. texture.url = rootUrl;
  15622. texture.generateMipMaps = !noMipmap;
  15623. texture._lodGenerationScale = lodScale;
  15624. texture._lodGenerationOffset = lodOffset;
  15625. if (!this._doNotHandleContextLost) {
  15626. texture._extension = forcedExtension;
  15627. texture._files = files;
  15628. }
  15629. var lastDot = rootUrl.lastIndexOf('.');
  15630. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15631. var loader = null;
  15632. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15633. var availableLoader = _a[_i];
  15634. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  15635. loader = availableLoader;
  15636. break;
  15637. }
  15638. }
  15639. var onInternalError = function (request, exception) {
  15640. if (loader) {
  15641. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  15642. if (fallbackUrl) {
  15643. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15644. }
  15645. }
  15646. if (onError && request) {
  15647. onError(request.status + " " + request.statusText, exception);
  15648. }
  15649. };
  15650. if (loader) {
  15651. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  15652. var onloaddata = function (data) {
  15653. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15654. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  15655. };
  15656. if (files && files.length === 6) {
  15657. if (loader.supportCascades) {
  15658. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  15659. }
  15660. else if (onError) {
  15661. onError("Textures type does not support cascades.");
  15662. }
  15663. }
  15664. else {
  15665. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  15666. }
  15667. }
  15668. else {
  15669. if (!files) {
  15670. throw new Error("Cannot load cubemap because files were not defined");
  15671. }
  15672. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15673. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15674. var height = width;
  15675. _this._prepareWorkingCanvas();
  15676. if (!_this._workingCanvas || !_this._workingContext) {
  15677. return;
  15678. }
  15679. _this._workingCanvas.width = width;
  15680. _this._workingCanvas.height = height;
  15681. var faces = [
  15682. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15683. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15684. ];
  15685. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15686. _this._unpackFlipY(false);
  15687. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15688. for (var index = 0; index < faces.length; index++) {
  15689. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15690. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15691. }
  15692. if (!noMipmap) {
  15693. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15694. }
  15695. _this._setCubeMapTextureParams(!noMipmap);
  15696. texture.width = width;
  15697. texture.height = height;
  15698. texture.isReady = true;
  15699. if (format) {
  15700. texture.format = format;
  15701. }
  15702. texture.onLoadedObservable.notifyObservers(texture);
  15703. texture.onLoadedObservable.clear();
  15704. if (onLoad) {
  15705. onLoad();
  15706. }
  15707. }, files, onError);
  15708. }
  15709. this._internalTexturesCache.push(texture);
  15710. return texture;
  15711. };
  15712. /**
  15713. * @hidden
  15714. */
  15715. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  15716. var gl = this._gl;
  15717. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15718. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15719. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15720. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15721. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15722. // this.resetTextureCache();
  15723. };
  15724. /**
  15725. * Update a raw cube texture
  15726. * @param texture defines the texture to udpdate
  15727. * @param data defines the data to store
  15728. * @param format defines the data format
  15729. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15730. * @param invertY defines if data must be stored with Y axis inverted
  15731. * @param compression defines the compression used (null by default)
  15732. * @param level defines which level of the texture to update
  15733. */
  15734. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15735. if (compression === void 0) { compression = null; }
  15736. if (level === void 0) { level = 0; }
  15737. texture._bufferViewArray = data;
  15738. texture.format = format;
  15739. texture.type = type;
  15740. texture.invertY = invertY;
  15741. texture._compression = compression;
  15742. var gl = this._gl;
  15743. var textureType = this._getWebGLTextureType(type);
  15744. var internalFormat = this._getInternalFormat(format);
  15745. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15746. var needConversion = false;
  15747. if (internalFormat === gl.RGB) {
  15748. internalFormat = gl.RGBA;
  15749. needConversion = true;
  15750. }
  15751. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15752. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15753. if (texture.width % 4 !== 0) {
  15754. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15755. }
  15756. // Data are known to be in +X +Y +Z -X -Y -Z
  15757. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15758. var faceData = data[faceIndex];
  15759. if (compression) {
  15760. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15761. }
  15762. else {
  15763. if (needConversion) {
  15764. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15765. }
  15766. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15767. }
  15768. }
  15769. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15770. if (isPot && texture.generateMipMaps && level === 0) {
  15771. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15772. }
  15773. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15774. // this.resetTextureCache();
  15775. texture.isReady = true;
  15776. };
  15777. /**
  15778. * Creates a new raw cube texture
  15779. * @param data defines the array of data to use to create each face
  15780. * @param size defines the size of the textures
  15781. * @param format defines the format of the data
  15782. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15783. * @param generateMipMaps defines if the engine should generate the mip levels
  15784. * @param invertY defines if data must be stored with Y axis inverted
  15785. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15786. * @param compression defines the compression used (null by default)
  15787. * @returns the cube texture as an InternalTexture
  15788. */
  15789. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15790. if (compression === void 0) { compression = null; }
  15791. var gl = this._gl;
  15792. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15793. texture.isCube = true;
  15794. texture.format = format;
  15795. texture.type = type;
  15796. if (!this._doNotHandleContextLost) {
  15797. texture._bufferViewArray = data;
  15798. }
  15799. var textureType = this._getWebGLTextureType(type);
  15800. var internalFormat = this._getInternalFormat(format);
  15801. if (internalFormat === gl.RGB) {
  15802. internalFormat = gl.RGBA;
  15803. }
  15804. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  15805. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15806. generateMipMaps = false;
  15807. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15808. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15809. }
  15810. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15811. generateMipMaps = false;
  15812. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15813. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  15814. }
  15815. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  15816. generateMipMaps = false;
  15817. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  15818. }
  15819. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  15820. generateMipMaps = false;
  15821. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  15822. }
  15823. var width = size;
  15824. var height = width;
  15825. texture.width = width;
  15826. texture.height = height;
  15827. // Double check on POT to generate Mips.
  15828. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15829. if (!isPot) {
  15830. generateMipMaps = false;
  15831. }
  15832. // Upload data if needed. The texture won't be ready until then.
  15833. if (data) {
  15834. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15835. }
  15836. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15837. // Filters
  15838. if (data && generateMipMaps) {
  15839. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15840. }
  15841. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15842. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15843. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15844. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15845. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15846. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15847. texture.generateMipMaps = generateMipMaps;
  15848. return texture;
  15849. };
  15850. /**
  15851. * Creates a new raw cube texture from a specified url
  15852. * @param url defines the url where the data is located
  15853. * @param scene defines the current scene
  15854. * @param size defines the size of the textures
  15855. * @param format defines the format of the data
  15856. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15857. * @param noMipmap defines if the engine should avoid generating the mip levels
  15858. * @param callback defines a callback used to extract texture data from loaded data
  15859. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15860. * @param onLoad defines a callback called when texture is loaded
  15861. * @param onError defines a callback called if there is an error
  15862. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15863. * @param invertY defines if data must be stored with Y axis inverted
  15864. * @returns the cube texture as an InternalTexture
  15865. */
  15866. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15867. var _this = this;
  15868. if (onLoad === void 0) { onLoad = null; }
  15869. if (onError === void 0) { onError = null; }
  15870. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15871. if (invertY === void 0) { invertY = false; }
  15872. var gl = this._gl;
  15873. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15874. scene._addPendingData(texture);
  15875. texture.url = url;
  15876. this._internalTexturesCache.push(texture);
  15877. var onerror = function (request, exception) {
  15878. scene._removePendingData(texture);
  15879. if (onError && request) {
  15880. onError(request.status + " " + request.statusText, exception);
  15881. }
  15882. };
  15883. var internalCallback = function (data) {
  15884. var width = texture.width;
  15885. var faceDataArrays = callback(data);
  15886. if (!faceDataArrays) {
  15887. return;
  15888. }
  15889. if (mipmapGenerator) {
  15890. var textureType = _this._getWebGLTextureType(type);
  15891. var internalFormat = _this._getInternalFormat(format);
  15892. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15893. var needConversion = false;
  15894. if (internalFormat === gl.RGB) {
  15895. internalFormat = gl.RGBA;
  15896. needConversion = true;
  15897. }
  15898. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15899. _this._unpackFlipY(false);
  15900. var mipData = mipmapGenerator(faceDataArrays);
  15901. for (var level = 0; level < mipData.length; level++) {
  15902. var mipSize = width >> level;
  15903. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15904. var mipFaceData = mipData[level][faceIndex];
  15905. if (needConversion) {
  15906. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15907. }
  15908. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15909. }
  15910. }
  15911. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15912. }
  15913. else {
  15914. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15915. }
  15916. texture.isReady = true;
  15917. // this.resetTextureCache();
  15918. scene._removePendingData(texture);
  15919. if (onLoad) {
  15920. onLoad();
  15921. }
  15922. };
  15923. this._loadFile(url, function (data) {
  15924. internalCallback(data);
  15925. }, undefined, scene.database, true, onerror);
  15926. return texture;
  15927. };
  15928. ;
  15929. /**
  15930. * Update a raw 3D texture
  15931. * @param texture defines the texture to update
  15932. * @param data defines the data to store
  15933. * @param format defines the data format
  15934. * @param invertY defines if data must be stored with Y axis inverted
  15935. * @param compression defines the used compression (can be null)
  15936. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  15937. */
  15938. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  15939. if (compression === void 0) { compression = null; }
  15940. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15941. var internalType = this._getWebGLTextureType(textureType);
  15942. var internalFormat = this._getInternalFormat(format);
  15943. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  15944. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15945. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15946. if (!this._doNotHandleContextLost) {
  15947. texture._bufferView = data;
  15948. texture.format = format;
  15949. texture.invertY = invertY;
  15950. texture._compression = compression;
  15951. }
  15952. if (texture.width % 4 !== 0) {
  15953. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15954. }
  15955. if (compression && data) {
  15956. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15957. }
  15958. else {
  15959. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  15960. }
  15961. if (texture.generateMipMaps) {
  15962. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15963. }
  15964. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15965. // this.resetTextureCache();
  15966. texture.isReady = true;
  15967. };
  15968. /**
  15969. * Creates a new raw 3D texture
  15970. * @param data defines the data used to create the texture
  15971. * @param width defines the width of the texture
  15972. * @param height defines the height of the texture
  15973. * @param depth defines the depth of the texture
  15974. * @param format defines the format of the texture
  15975. * @param generateMipMaps defines if the engine must generate mip levels
  15976. * @param invertY defines if data must be stored with Y axis inverted
  15977. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15978. * @param compression defines the compressed used (can be null)
  15979. * @param textureType defines the compressed used (can be null)
  15980. * @returns a new raw 3D texture (stored in an InternalTexture)
  15981. */
  15982. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  15983. if (compression === void 0) { compression = null; }
  15984. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15985. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15986. texture.baseWidth = width;
  15987. texture.baseHeight = height;
  15988. texture.baseDepth = depth;
  15989. texture.width = width;
  15990. texture.height = height;
  15991. texture.depth = depth;
  15992. texture.format = format;
  15993. texture.type = textureType;
  15994. texture.generateMipMaps = generateMipMaps;
  15995. texture.samplingMode = samplingMode;
  15996. texture.is3D = true;
  15997. if (!this._doNotHandleContextLost) {
  15998. texture._bufferView = data;
  15999. }
  16000. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16001. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16002. // Filters
  16003. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16004. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16005. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16006. if (generateMipMaps) {
  16007. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16008. }
  16009. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16010. this._internalTexturesCache.push(texture);
  16011. return texture;
  16012. };
  16013. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16014. var gl = this._gl;
  16015. if (!gl) {
  16016. return;
  16017. }
  16018. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16019. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16020. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16021. if (!noMipmap && !isCompressed) {
  16022. gl.generateMipmap(gl.TEXTURE_2D);
  16023. }
  16024. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16025. // this.resetTextureCache();
  16026. if (scene) {
  16027. scene._removePendingData(texture);
  16028. }
  16029. texture.onLoadedObservable.notifyObservers(texture);
  16030. texture.onLoadedObservable.clear();
  16031. };
  16032. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16033. var _this = this;
  16034. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16035. var maxTextureSize = this.getCaps().maxTextureSize;
  16036. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16037. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16038. var gl = this._gl;
  16039. if (!gl) {
  16040. return;
  16041. }
  16042. if (!texture._webGLTexture) {
  16043. // this.resetTextureCache();
  16044. if (scene) {
  16045. scene._removePendingData(texture);
  16046. }
  16047. return;
  16048. }
  16049. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16050. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16051. texture.baseWidth = width;
  16052. texture.baseHeight = height;
  16053. texture.width = potWidth;
  16054. texture.height = potHeight;
  16055. texture.isReady = true;
  16056. if (processFunction(potWidth, potHeight, function () {
  16057. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16058. })) {
  16059. // Returning as texture needs extra async steps
  16060. return;
  16061. }
  16062. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16063. };
  16064. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16065. // Create new RGBA data container.
  16066. var rgbaData;
  16067. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16068. rgbaData = new Float32Array(width * height * 4);
  16069. }
  16070. else {
  16071. rgbaData = new Uint32Array(width * height * 4);
  16072. }
  16073. // Convert each pixel.
  16074. for (var x = 0; x < width; x++) {
  16075. for (var y = 0; y < height; y++) {
  16076. var index = (y * width + x) * 3;
  16077. var newIndex = (y * width + x) * 4;
  16078. // Map Old Value to new value.
  16079. rgbaData[newIndex + 0] = rgbData[index + 0];
  16080. rgbaData[newIndex + 1] = rgbData[index + 1];
  16081. rgbaData[newIndex + 2] = rgbData[index + 2];
  16082. // Add fully opaque alpha channel.
  16083. rgbaData[newIndex + 3] = 1;
  16084. }
  16085. }
  16086. return rgbaData;
  16087. };
  16088. /** @hidden */
  16089. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16090. var gl = this._gl;
  16091. if (texture._framebuffer) {
  16092. gl.deleteFramebuffer(texture._framebuffer);
  16093. texture._framebuffer = null;
  16094. }
  16095. if (texture._depthStencilBuffer) {
  16096. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16097. texture._depthStencilBuffer = null;
  16098. }
  16099. if (texture._MSAAFramebuffer) {
  16100. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16101. texture._MSAAFramebuffer = null;
  16102. }
  16103. if (texture._MSAARenderBuffer) {
  16104. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16105. texture._MSAARenderBuffer = null;
  16106. }
  16107. };
  16108. /** @hidden */
  16109. Engine.prototype._releaseTexture = function (texture) {
  16110. var gl = this._gl;
  16111. this._releaseFramebufferObjects(texture);
  16112. gl.deleteTexture(texture._webGLTexture);
  16113. // Unbind channels
  16114. this.unbindAllTextures();
  16115. var index = this._internalTexturesCache.indexOf(texture);
  16116. if (index !== -1) {
  16117. this._internalTexturesCache.splice(index, 1);
  16118. }
  16119. // Integrated fixed lod samplers.
  16120. if (texture._lodTextureHigh) {
  16121. texture._lodTextureHigh.dispose();
  16122. }
  16123. if (texture._lodTextureMid) {
  16124. texture._lodTextureMid.dispose();
  16125. }
  16126. if (texture._lodTextureLow) {
  16127. texture._lodTextureLow.dispose();
  16128. }
  16129. // Set output texture of post process to null if the texture has been released/disposed
  16130. this.scenes.forEach(function (scene) {
  16131. scene.postProcesses.forEach(function (postProcess) {
  16132. if (postProcess._outputTexture == texture) {
  16133. postProcess._outputTexture = null;
  16134. }
  16135. });
  16136. scene.cameras.forEach(function (camera) {
  16137. camera._postProcesses.forEach(function (postProcess) {
  16138. if (postProcess) {
  16139. if (postProcess._outputTexture == texture) {
  16140. postProcess._outputTexture = null;
  16141. }
  16142. }
  16143. });
  16144. });
  16145. });
  16146. };
  16147. Engine.prototype.setProgram = function (program) {
  16148. if (this._currentProgram !== program) {
  16149. this._gl.useProgram(program);
  16150. this._currentProgram = program;
  16151. }
  16152. };
  16153. /**
  16154. * Binds an effect to the webGL context
  16155. * @param effect defines the effect to bind
  16156. */
  16157. Engine.prototype.bindSamplers = function (effect) {
  16158. this.setProgram(effect.getProgram());
  16159. var samplers = effect.getSamplers();
  16160. for (var index = 0; index < samplers.length; index++) {
  16161. var uniform = effect.getUniform(samplers[index]);
  16162. if (uniform) {
  16163. this._boundUniforms[index] = uniform;
  16164. }
  16165. }
  16166. this._currentEffect = null;
  16167. };
  16168. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16169. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16170. return;
  16171. }
  16172. // Remove
  16173. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16174. // Bind last to it
  16175. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16176. // Bind to dummy
  16177. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16178. };
  16179. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16180. if (!internalTexture) {
  16181. return -1;
  16182. }
  16183. internalTexture._initialSlot = channel;
  16184. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16185. if (channel !== internalTexture._designatedSlot) {
  16186. this._textureCollisions.addCount(1, false);
  16187. }
  16188. }
  16189. else {
  16190. if (channel !== internalTexture._designatedSlot) {
  16191. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16192. return internalTexture._designatedSlot;
  16193. }
  16194. else {
  16195. // No slot for this texture, let's pick a new one (if we find a free slot)
  16196. if (this._nextFreeTextureSlots.length) {
  16197. return this._nextFreeTextureSlots[0];
  16198. }
  16199. // We need to recycle the oldest bound texture, sorry.
  16200. this._textureCollisions.addCount(1, false);
  16201. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16202. }
  16203. }
  16204. }
  16205. return channel;
  16206. };
  16207. Engine.prototype._linkTrackers = function (previous, next) {
  16208. previous.next = next;
  16209. next.previous = previous;
  16210. };
  16211. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16212. var currentSlot = internalTexture._designatedSlot;
  16213. if (currentSlot === -1) {
  16214. return -1;
  16215. }
  16216. internalTexture._designatedSlot = -1;
  16217. if (this.disableTextureBindingOptimization) {
  16218. return -1;
  16219. }
  16220. // Remove from bound list
  16221. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16222. // Free the slot
  16223. this._boundTexturesCache[currentSlot] = null;
  16224. this._nextFreeTextureSlots.push(currentSlot);
  16225. return currentSlot;
  16226. };
  16227. Engine.prototype._activateCurrentTexture = function () {
  16228. if (this._currentTextureChannel !== this._activeChannel) {
  16229. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16230. this._currentTextureChannel = this._activeChannel;
  16231. }
  16232. };
  16233. /** @hidden */
  16234. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16235. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16236. if (force === void 0) { force = false; }
  16237. var wasPreviouslyBound = false;
  16238. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16239. this._activeChannel = texture._designatedSlot;
  16240. }
  16241. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16242. var isTextureForRendering = texture && texture._initialSlot > -1;
  16243. if (currentTextureBound !== texture || force) {
  16244. if (currentTextureBound) {
  16245. this._removeDesignatedSlot(currentTextureBound);
  16246. }
  16247. this._activateCurrentTexture();
  16248. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16249. this._boundTexturesCache[this._activeChannel] = texture;
  16250. if (texture) {
  16251. if (!this.disableTextureBindingOptimization) {
  16252. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16253. if (slotIndex > -1) {
  16254. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16255. }
  16256. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16257. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16258. }
  16259. texture._designatedSlot = this._activeChannel;
  16260. }
  16261. }
  16262. else if (forTextureDataUpdate) {
  16263. wasPreviouslyBound = true;
  16264. this._activateCurrentTexture();
  16265. }
  16266. if (isTextureForRendering && !forTextureDataUpdate) {
  16267. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16268. }
  16269. return wasPreviouslyBound;
  16270. };
  16271. /** @hidden */
  16272. Engine.prototype._bindTexture = function (channel, texture) {
  16273. if (channel < 0) {
  16274. return;
  16275. }
  16276. if (texture) {
  16277. channel = this._getCorrectTextureChannel(channel, texture);
  16278. }
  16279. this._activeChannel = channel;
  16280. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16281. };
  16282. /**
  16283. * Sets a texture to the webGL context from a postprocess
  16284. * @param channel defines the channel to use
  16285. * @param postProcess defines the source postprocess
  16286. */
  16287. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16288. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16289. };
  16290. /**
  16291. * Binds the output of the passed in post process to the texture channel specified
  16292. * @param channel The channel the texture should be bound to
  16293. * @param postProcess The post process which's output should be bound
  16294. */
  16295. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16296. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16297. };
  16298. /**
  16299. * Unbind all textures from the webGL context
  16300. */
  16301. Engine.prototype.unbindAllTextures = function () {
  16302. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16303. this._activeChannel = channel;
  16304. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16305. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16306. if (this.webGLVersion > 1) {
  16307. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16308. }
  16309. }
  16310. };
  16311. /**
  16312. * Sets a texture to the according uniform.
  16313. * @param channel The texture channel
  16314. * @param uniform The uniform to set
  16315. * @param texture The texture to apply
  16316. */
  16317. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16318. if (channel < 0) {
  16319. return;
  16320. }
  16321. if (uniform) {
  16322. this._boundUniforms[channel] = uniform;
  16323. }
  16324. this._setTexture(channel, texture);
  16325. };
  16326. /**
  16327. * Sets a depth stencil texture from a render target to the according uniform.
  16328. * @param channel The texture channel
  16329. * @param uniform The uniform to set
  16330. * @param texture The render target texture containing the depth stencil texture to apply
  16331. */
  16332. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16333. if (channel < 0) {
  16334. return;
  16335. }
  16336. if (uniform) {
  16337. this._boundUniforms[channel] = uniform;
  16338. }
  16339. if (!texture || !texture.depthStencilTexture) {
  16340. this._setTexture(channel, null);
  16341. }
  16342. else {
  16343. this._setTexture(channel, texture, false, true);
  16344. }
  16345. };
  16346. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16347. var uniform = this._boundUniforms[sourceSlot];
  16348. if (uniform._currentState === destination) {
  16349. return;
  16350. }
  16351. this._gl.uniform1i(uniform, destination);
  16352. uniform._currentState = destination;
  16353. };
  16354. Engine.prototype._getTextureWrapMode = function (mode) {
  16355. switch (mode) {
  16356. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  16357. return this._gl.REPEAT;
  16358. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  16359. return this._gl.CLAMP_TO_EDGE;
  16360. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  16361. return this._gl.MIRRORED_REPEAT;
  16362. }
  16363. return this._gl.REPEAT;
  16364. };
  16365. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16366. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16367. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16368. // Not ready?
  16369. if (!texture) {
  16370. if (this._boundTexturesCache[channel] != null) {
  16371. this._activeChannel = channel;
  16372. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16373. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16374. if (this.webGLVersion > 1) {
  16375. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16376. }
  16377. }
  16378. return false;
  16379. }
  16380. // Video
  16381. if (texture.video) {
  16382. this._activeChannel = channel;
  16383. texture.update();
  16384. }
  16385. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16386. texture.delayLoad();
  16387. return false;
  16388. }
  16389. var internalTexture;
  16390. if (depthStencilTexture) {
  16391. internalTexture = texture.depthStencilTexture;
  16392. }
  16393. else if (texture.isReady()) {
  16394. internalTexture = texture.getInternalTexture();
  16395. }
  16396. else if (texture.isCube) {
  16397. internalTexture = this.emptyCubeTexture;
  16398. }
  16399. else if (texture.is3D) {
  16400. internalTexture = this.emptyTexture3D;
  16401. }
  16402. else {
  16403. internalTexture = this.emptyTexture;
  16404. }
  16405. if (!isPartOfTextureArray) {
  16406. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16407. }
  16408. var needToBind = true;
  16409. if (this._boundTexturesCache[channel] === internalTexture) {
  16410. this._moveBoundTextureOnTop(internalTexture);
  16411. if (!isPartOfTextureArray) {
  16412. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16413. }
  16414. needToBind = false;
  16415. }
  16416. this._activeChannel = channel;
  16417. if (internalTexture && internalTexture.is3D) {
  16418. if (needToBind) {
  16419. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16420. }
  16421. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16422. internalTexture._cachedWrapU = texture.wrapU;
  16423. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16424. }
  16425. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16426. internalTexture._cachedWrapV = texture.wrapV;
  16427. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16428. }
  16429. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16430. internalTexture._cachedWrapR = texture.wrapR;
  16431. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16432. }
  16433. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16434. }
  16435. else if (internalTexture && internalTexture.isCube) {
  16436. if (needToBind) {
  16437. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16438. }
  16439. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16440. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16441. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16442. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16443. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16444. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16445. }
  16446. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16447. }
  16448. else {
  16449. if (needToBind) {
  16450. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16451. }
  16452. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16453. internalTexture._cachedWrapU = texture.wrapU;
  16454. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16455. }
  16456. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16457. internalTexture._cachedWrapV = texture.wrapV;
  16458. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16459. }
  16460. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16461. }
  16462. return true;
  16463. };
  16464. /**
  16465. * Sets an array of texture to the webGL context
  16466. * @param channel defines the channel where the texture array must be set
  16467. * @param uniform defines the associated uniform location
  16468. * @param textures defines the array of textures to bind
  16469. */
  16470. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16471. if (channel < 0 || !uniform) {
  16472. return;
  16473. }
  16474. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16475. this._textureUnits = new Int32Array(textures.length);
  16476. }
  16477. for (var i = 0; i < textures.length; i++) {
  16478. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16479. }
  16480. this._gl.uniform1iv(uniform, this._textureUnits);
  16481. for (var index = 0; index < textures.length; index++) {
  16482. this._setTexture(this._textureUnits[index], textures[index], true);
  16483. }
  16484. };
  16485. /** @hidden */
  16486. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16487. var internalTexture = texture.getInternalTexture();
  16488. if (!internalTexture) {
  16489. return;
  16490. }
  16491. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16492. var value = texture.anisotropicFilteringLevel;
  16493. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  16494. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  16495. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  16496. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16497. }
  16498. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16499. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16500. internalTexture._cachedAnisotropicFilteringLevel = value;
  16501. }
  16502. };
  16503. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16504. this._bindTextureDirectly(target, texture, true, true);
  16505. this._gl.texParameterf(target, parameter, value);
  16506. };
  16507. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16508. if (texture) {
  16509. this._bindTextureDirectly(target, texture, true, true);
  16510. }
  16511. this._gl.texParameteri(target, parameter, value);
  16512. };
  16513. /**
  16514. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16515. * @param x defines the x coordinate of the rectangle where pixels must be read
  16516. * @param y defines the y coordinate of the rectangle where pixels must be read
  16517. * @param width defines the width of the rectangle where pixels must be read
  16518. * @param height defines the height of the rectangle where pixels must be read
  16519. * @returns a Uint8Array containing RGBA colors
  16520. */
  16521. Engine.prototype.readPixels = function (x, y, width, height) {
  16522. var data = new Uint8Array(height * width * 4);
  16523. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16524. return data;
  16525. };
  16526. /**
  16527. * Add an externaly attached data from its key.
  16528. * This method call will fail and return false, if such key already exists.
  16529. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16530. * @param key the unique key that identifies the data
  16531. * @param data the data object to associate to the key for this Engine instance
  16532. * @return true if no such key were already present and the data was added successfully, false otherwise
  16533. */
  16534. Engine.prototype.addExternalData = function (key, data) {
  16535. if (!this._externalData) {
  16536. this._externalData = new BABYLON.StringDictionary();
  16537. }
  16538. return this._externalData.add(key, data);
  16539. };
  16540. /**
  16541. * Get an externaly attached data from its key
  16542. * @param key the unique key that identifies the data
  16543. * @return the associated data, if present (can be null), or undefined if not present
  16544. */
  16545. Engine.prototype.getExternalData = function (key) {
  16546. if (!this._externalData) {
  16547. this._externalData = new BABYLON.StringDictionary();
  16548. }
  16549. return this._externalData.get(key);
  16550. };
  16551. /**
  16552. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16553. * @param key the unique key that identifies the data
  16554. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16555. * @return the associated data, can be null if the factory returned null.
  16556. */
  16557. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16558. if (!this._externalData) {
  16559. this._externalData = new BABYLON.StringDictionary();
  16560. }
  16561. return this._externalData.getOrAddWithFactory(key, factory);
  16562. };
  16563. /**
  16564. * Remove an externaly attached data from the Engine instance
  16565. * @param key the unique key that identifies the data
  16566. * @return true if the data was successfully removed, false if it doesn't exist
  16567. */
  16568. Engine.prototype.removeExternalData = function (key) {
  16569. if (!this._externalData) {
  16570. this._externalData = new BABYLON.StringDictionary();
  16571. }
  16572. return this._externalData.remove(key);
  16573. };
  16574. /**
  16575. * Unbind all vertex attributes from the webGL context
  16576. */
  16577. Engine.prototype.unbindAllAttributes = function () {
  16578. if (this._mustWipeVertexAttributes) {
  16579. this._mustWipeVertexAttributes = false;
  16580. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16581. this._gl.disableVertexAttribArray(i);
  16582. this._vertexAttribArraysEnabled[i] = false;
  16583. this._currentBufferPointers[i].active = false;
  16584. }
  16585. return;
  16586. }
  16587. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16588. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16589. continue;
  16590. }
  16591. this._gl.disableVertexAttribArray(i);
  16592. this._vertexAttribArraysEnabled[i] = false;
  16593. this._currentBufferPointers[i].active = false;
  16594. }
  16595. };
  16596. /**
  16597. * 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
  16598. */
  16599. Engine.prototype.releaseEffects = function () {
  16600. for (var name in this._compiledEffects) {
  16601. this._deleteProgram(this._compiledEffects[name]._program);
  16602. }
  16603. this._compiledEffects = {};
  16604. };
  16605. /**
  16606. * Dispose and release all associated resources
  16607. */
  16608. Engine.prototype.dispose = function () {
  16609. this.hideLoadingUI();
  16610. this.stopRenderLoop();
  16611. // Release postProcesses
  16612. while (this.postProcesses.length) {
  16613. this.postProcesses[0].dispose();
  16614. }
  16615. // Empty texture
  16616. if (this._emptyTexture) {
  16617. this._releaseTexture(this._emptyTexture);
  16618. this._emptyTexture = null;
  16619. }
  16620. if (this._emptyCubeTexture) {
  16621. this._releaseTexture(this._emptyCubeTexture);
  16622. this._emptyCubeTexture = null;
  16623. }
  16624. // Rescale PP
  16625. if (this._rescalePostProcess) {
  16626. this._rescalePostProcess.dispose();
  16627. }
  16628. // Release scenes
  16629. while (this.scenes.length) {
  16630. this.scenes[0].dispose();
  16631. }
  16632. // Release audio engine
  16633. if (Engine.audioEngine) {
  16634. Engine.audioEngine.dispose();
  16635. }
  16636. // Release effects
  16637. this.releaseEffects();
  16638. // Unbind
  16639. this.unbindAllAttributes();
  16640. this._boundUniforms = [];
  16641. if (this._dummyFramebuffer) {
  16642. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16643. }
  16644. //WebVR
  16645. this.disableVR();
  16646. // Events
  16647. if (BABYLON.Tools.IsWindowObjectExist()) {
  16648. window.removeEventListener("blur", this._onBlur);
  16649. window.removeEventListener("focus", this._onFocus);
  16650. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16651. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16652. if (this._renderingCanvas) {
  16653. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16654. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16655. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16656. if (!this._doNotHandleContextLost) {
  16657. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16658. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16659. }
  16660. }
  16661. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16662. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16663. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16664. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16665. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16666. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16667. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16668. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16669. if (this._onVrDisplayConnect) {
  16670. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16671. if (this._onVrDisplayDisconnect) {
  16672. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16673. }
  16674. if (this._onVrDisplayPresentChange) {
  16675. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16676. }
  16677. this._onVrDisplayConnect = null;
  16678. this._onVrDisplayDisconnect = null;
  16679. }
  16680. }
  16681. // Remove from Instances
  16682. var index = Engine.Instances.indexOf(this);
  16683. if (index >= 0) {
  16684. Engine.Instances.splice(index, 1);
  16685. }
  16686. this._workingCanvas = null;
  16687. this._workingContext = null;
  16688. this._currentBufferPointers = [];
  16689. this._renderingCanvas = null;
  16690. this._currentProgram = null;
  16691. this._bindedRenderFunction = null;
  16692. this.onResizeObservable.clear();
  16693. this.onCanvasBlurObservable.clear();
  16694. this.onCanvasFocusObservable.clear();
  16695. this.onCanvasPointerOutObservable.clear();
  16696. this.onBeginFrameObservable.clear();
  16697. this.onEndFrameObservable.clear();
  16698. BABYLON.Effect.ResetCache();
  16699. // Abort active requests
  16700. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16701. var request = _a[_i];
  16702. request.abort();
  16703. }
  16704. };
  16705. // Loading screen
  16706. /**
  16707. * Display the loading screen
  16708. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16709. */
  16710. Engine.prototype.displayLoadingUI = function () {
  16711. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16712. return;
  16713. }
  16714. var loadingScreen = this.loadingScreen;
  16715. if (loadingScreen) {
  16716. loadingScreen.displayLoadingUI();
  16717. }
  16718. };
  16719. /**
  16720. * Hide the loading screen
  16721. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16722. */
  16723. Engine.prototype.hideLoadingUI = function () {
  16724. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16725. return;
  16726. }
  16727. var loadingScreen = this.loadingScreen;
  16728. if (loadingScreen) {
  16729. loadingScreen.hideLoadingUI();
  16730. }
  16731. };
  16732. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16733. /**
  16734. * Gets the current loading screen object
  16735. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16736. */
  16737. get: function () {
  16738. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16739. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16740. return this._loadingScreen;
  16741. },
  16742. /**
  16743. * Sets the current loading screen object
  16744. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16745. */
  16746. set: function (loadingScreen) {
  16747. this._loadingScreen = loadingScreen;
  16748. },
  16749. enumerable: true,
  16750. configurable: true
  16751. });
  16752. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16753. /**
  16754. * Sets the current loading screen text
  16755. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16756. */
  16757. set: function (text) {
  16758. this.loadingScreen.loadingUIText = text;
  16759. },
  16760. enumerable: true,
  16761. configurable: true
  16762. });
  16763. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16764. /**
  16765. * Sets the current loading screen background color
  16766. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16767. */
  16768. set: function (color) {
  16769. this.loadingScreen.loadingUIBackgroundColor = color;
  16770. },
  16771. enumerable: true,
  16772. configurable: true
  16773. });
  16774. /**
  16775. * Attach a new callback raised when context lost event is fired
  16776. * @param callback defines the callback to call
  16777. */
  16778. Engine.prototype.attachContextLostEvent = function (callback) {
  16779. if (this._renderingCanvas) {
  16780. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16781. }
  16782. };
  16783. /**
  16784. * Attach a new callback raised when context restored event is fired
  16785. * @param callback defines the callback to call
  16786. */
  16787. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16788. if (this._renderingCanvas) {
  16789. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16790. }
  16791. };
  16792. /**
  16793. * Gets the source code of the vertex shader associated with a specific webGL program
  16794. * @param program defines the program to use
  16795. * @returns a string containing the source code of the vertex shader associated with the program
  16796. */
  16797. Engine.prototype.getVertexShaderSource = function (program) {
  16798. var shaders = this._gl.getAttachedShaders(program);
  16799. if (!shaders) {
  16800. return null;
  16801. }
  16802. return this._gl.getShaderSource(shaders[0]);
  16803. };
  16804. /**
  16805. * Gets the source code of the fragment shader associated with a specific webGL program
  16806. * @param program defines the program to use
  16807. * @returns a string containing the source code of the fragment shader associated with the program
  16808. */
  16809. Engine.prototype.getFragmentShaderSource = function (program) {
  16810. var shaders = this._gl.getAttachedShaders(program);
  16811. if (!shaders) {
  16812. return null;
  16813. }
  16814. return this._gl.getShaderSource(shaders[1]);
  16815. };
  16816. /**
  16817. * Get the current error code of the webGL context
  16818. * @returns the error code
  16819. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16820. */
  16821. Engine.prototype.getError = function () {
  16822. return this._gl.getError();
  16823. };
  16824. // FPS
  16825. /**
  16826. * Gets the current framerate
  16827. * @returns a number representing the framerate
  16828. */
  16829. Engine.prototype.getFps = function () {
  16830. return this._fps;
  16831. };
  16832. /**
  16833. * Gets the time spent between current and previous frame
  16834. * @returns a number representing the delta time in ms
  16835. */
  16836. Engine.prototype.getDeltaTime = function () {
  16837. return this._deltaTime;
  16838. };
  16839. Engine.prototype._measureFps = function () {
  16840. this._performanceMonitor.sampleFrame();
  16841. this._fps = this._performanceMonitor.averageFPS;
  16842. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16843. };
  16844. /** @hidden */
  16845. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  16846. if (faceIndex === void 0) { faceIndex = -1; }
  16847. if (level === void 0) { level = 0; }
  16848. var gl = this._gl;
  16849. if (!this._dummyFramebuffer) {
  16850. var dummy = gl.createFramebuffer();
  16851. if (!dummy) {
  16852. throw new Error("Unable to create dummy framebuffer");
  16853. }
  16854. this._dummyFramebuffer = dummy;
  16855. }
  16856. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16857. if (faceIndex > -1) {
  16858. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  16859. }
  16860. else {
  16861. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  16862. }
  16863. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16864. var buffer;
  16865. switch (readType) {
  16866. case gl.UNSIGNED_BYTE:
  16867. buffer = new Uint8Array(4 * width * height);
  16868. readType = gl.UNSIGNED_BYTE;
  16869. break;
  16870. default:
  16871. buffer = new Float32Array(4 * width * height);
  16872. readType = gl.FLOAT;
  16873. break;
  16874. }
  16875. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16876. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16877. return buffer;
  16878. };
  16879. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16880. if (this._webGLVersion > 1) {
  16881. return this._caps.colorBufferFloat;
  16882. }
  16883. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16884. };
  16885. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16886. if (this._webGLVersion > 1) {
  16887. return this._caps.colorBufferFloat;
  16888. }
  16889. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16890. };
  16891. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16892. Engine.prototype._canRenderToFramebuffer = function (type) {
  16893. var gl = this._gl;
  16894. //clear existing errors
  16895. while (gl.getError() !== gl.NO_ERROR) { }
  16896. var successful = true;
  16897. var texture = gl.createTexture();
  16898. gl.bindTexture(gl.TEXTURE_2D, texture);
  16899. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16900. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16901. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16902. var fb = gl.createFramebuffer();
  16903. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16904. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16905. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16906. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16907. successful = successful && (gl.getError() === gl.NO_ERROR);
  16908. //try render by clearing frame buffer's color buffer
  16909. if (successful) {
  16910. gl.clear(gl.COLOR_BUFFER_BIT);
  16911. successful = successful && (gl.getError() === gl.NO_ERROR);
  16912. }
  16913. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16914. if (successful) {
  16915. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16916. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16917. var readFormat = gl.RGBA;
  16918. var readType = gl.UNSIGNED_BYTE;
  16919. var buffer = new Uint8Array(4);
  16920. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16921. successful = successful && (gl.getError() === gl.NO_ERROR);
  16922. }
  16923. //clean up
  16924. gl.deleteTexture(texture);
  16925. gl.deleteFramebuffer(fb);
  16926. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16927. //clear accumulated errors
  16928. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16929. return successful;
  16930. };
  16931. /** @hidden */
  16932. Engine.prototype._getWebGLTextureType = function (type) {
  16933. if (this._webGLVersion === 1) {
  16934. switch (type) {
  16935. case Engine.TEXTURETYPE_FLOAT:
  16936. return this._gl.FLOAT;
  16937. case Engine.TEXTURETYPE_HALF_FLOAT:
  16938. return this._gl.HALF_FLOAT_OES;
  16939. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  16940. return this._gl.UNSIGNED_BYTE;
  16941. }
  16942. return this._gl.UNSIGNED_BYTE;
  16943. }
  16944. switch (type) {
  16945. case Engine.TEXTURETYPE_BYTE:
  16946. return this._gl.BYTE;
  16947. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  16948. return this._gl.UNSIGNED_BYTE;
  16949. case Engine.TEXTURETYPE_SHORT:
  16950. return this._gl.SHORT;
  16951. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  16952. return this._gl.UNSIGNED_SHORT;
  16953. case Engine.TEXTURETYPE_INT:
  16954. return this._gl.INT;
  16955. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  16956. return this._gl.UNSIGNED_INT;
  16957. case Engine.TEXTURETYPE_FLOAT:
  16958. return this._gl.FLOAT;
  16959. case Engine.TEXTURETYPE_HALF_FLOAT:
  16960. return this._gl.HALF_FLOAT;
  16961. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  16962. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  16963. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  16964. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  16965. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  16966. return this._gl.UNSIGNED_SHORT_5_6_5;
  16967. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  16968. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  16969. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  16970. return this._gl.UNSIGNED_INT_24_8;
  16971. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  16972. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  16973. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  16974. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  16975. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  16976. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  16977. }
  16978. return this._gl.UNSIGNED_BYTE;
  16979. };
  16980. ;
  16981. Engine.prototype._getInternalFormat = function (format) {
  16982. var internalFormat = this._gl.RGBA;
  16983. switch (format) {
  16984. case Engine.TEXTUREFORMAT_ALPHA:
  16985. internalFormat = this._gl.ALPHA;
  16986. break;
  16987. case Engine.TEXTUREFORMAT_LUMINANCE:
  16988. internalFormat = this._gl.LUMINANCE;
  16989. break;
  16990. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16991. internalFormat = this._gl.LUMINANCE_ALPHA;
  16992. break;
  16993. case Engine.TEXTUREFORMAT_RED:
  16994. internalFormat = this._gl.RED;
  16995. break;
  16996. case Engine.TEXTUREFORMAT_RG:
  16997. internalFormat = this._gl.RG;
  16998. break;
  16999. case Engine.TEXTUREFORMAT_RGB:
  17000. internalFormat = this._gl.RGB;
  17001. break;
  17002. case Engine.TEXTUREFORMAT_RGBA:
  17003. internalFormat = this._gl.RGBA;
  17004. break;
  17005. }
  17006. if (this._webGLVersion > 1) {
  17007. switch (format) {
  17008. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17009. internalFormat = this._gl.RED_INTEGER;
  17010. break;
  17011. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17012. internalFormat = this._gl.RG_INTEGER;
  17013. break;
  17014. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17015. internalFormat = this._gl.RGB_INTEGER;
  17016. break;
  17017. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17018. internalFormat = this._gl.RGBA_INTEGER;
  17019. break;
  17020. }
  17021. }
  17022. return internalFormat;
  17023. };
  17024. /** @hidden */
  17025. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17026. if (this._webGLVersion === 1) {
  17027. if (format !== undefined) {
  17028. switch (format) {
  17029. case Engine.TEXTUREFORMAT_ALPHA:
  17030. return this._gl.ALPHA;
  17031. case Engine.TEXTUREFORMAT_LUMINANCE:
  17032. return this._gl.LUMINANCE;
  17033. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17034. return this._gl.LUMINANCE_ALPHA;
  17035. }
  17036. }
  17037. return this._gl.RGBA;
  17038. }
  17039. switch (type) {
  17040. case Engine.TEXTURETYPE_BYTE:
  17041. switch (format) {
  17042. case Engine.TEXTUREFORMAT_RED:
  17043. return this._gl.R8_SNORM;
  17044. case Engine.TEXTUREFORMAT_RG:
  17045. return this._gl.RG8_SNORM;
  17046. case Engine.TEXTUREFORMAT_RGB:
  17047. return this._gl.RGB8_SNORM;
  17048. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17049. return this._gl.R8I;
  17050. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17051. return this._gl.RG8I;
  17052. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17053. return this._gl.RGB8I;
  17054. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17055. return this._gl.RGBA8I;
  17056. default:
  17057. return this._gl.RGBA8_SNORM;
  17058. }
  17059. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17060. switch (format) {
  17061. case Engine.TEXTUREFORMAT_RED:
  17062. return this._gl.R8;
  17063. case Engine.TEXTUREFORMAT_RG:
  17064. return this._gl.RG8;
  17065. case Engine.TEXTUREFORMAT_RGB:
  17066. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  17067. case Engine.TEXTUREFORMAT_RGBA:
  17068. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  17069. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17070. return this._gl.R8UI;
  17071. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17072. return this._gl.RG8UI;
  17073. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17074. return this._gl.RGB8UI;
  17075. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17076. return this._gl.RGBA8UI;
  17077. default:
  17078. return this._gl.RGBA8;
  17079. }
  17080. case Engine.TEXTURETYPE_SHORT:
  17081. switch (format) {
  17082. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17083. return this._gl.R16I;
  17084. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17085. return this._gl.RG16I;
  17086. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17087. return this._gl.RGB16I;
  17088. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17089. return this._gl.RGBA16I;
  17090. default:
  17091. return this._gl.RGBA16I;
  17092. }
  17093. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17094. switch (format) {
  17095. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17096. return this._gl.R16UI;
  17097. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17098. return this._gl.RG16UI;
  17099. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17100. return this._gl.RGB16UI;
  17101. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17102. return this._gl.RGBA16UI;
  17103. default:
  17104. return this._gl.RGBA16UI;
  17105. }
  17106. case Engine.TEXTURETYPE_INT:
  17107. switch (format) {
  17108. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17109. return this._gl.R32I;
  17110. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17111. return this._gl.RG32I;
  17112. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17113. return this._gl.RGB32I;
  17114. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17115. return this._gl.RGBA32I;
  17116. default:
  17117. return this._gl.RGBA32I;
  17118. }
  17119. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17120. switch (format) {
  17121. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17122. return this._gl.R32UI;
  17123. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17124. return this._gl.RG32UI;
  17125. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17126. return this._gl.RGB32UI;
  17127. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17128. return this._gl.RGBA32UI;
  17129. default:
  17130. return this._gl.RGBA32UI;
  17131. }
  17132. case Engine.TEXTURETYPE_FLOAT:
  17133. switch (format) {
  17134. case Engine.TEXTUREFORMAT_RED:
  17135. return this._gl.R32F; // By default. Other possibility is R16F.
  17136. case Engine.TEXTUREFORMAT_RG:
  17137. return this._gl.RG32F; // By default. Other possibility is RG16F.
  17138. case Engine.TEXTUREFORMAT_RGB:
  17139. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  17140. case Engine.TEXTUREFORMAT_RGBA:
  17141. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  17142. default:
  17143. return this._gl.RGBA32F;
  17144. }
  17145. case Engine.TEXTURETYPE_HALF_FLOAT:
  17146. switch (format) {
  17147. case Engine.TEXTUREFORMAT_RED:
  17148. return this._gl.R16F;
  17149. case Engine.TEXTUREFORMAT_RG:
  17150. return this._gl.RG16F;
  17151. case Engine.TEXTUREFORMAT_RGB:
  17152. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  17153. case Engine.TEXTUREFORMAT_RGBA:
  17154. return this._gl.RGBA16F;
  17155. default:
  17156. return this._gl.RGBA16F;
  17157. }
  17158. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17159. return this._gl.RGB565;
  17160. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17161. return this._gl.R11F_G11F_B10F;
  17162. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17163. return this._gl.RGB9_E5;
  17164. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17165. return this._gl.RGBA4;
  17166. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17167. return this._gl.RGB5_A1;
  17168. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17169. switch (format) {
  17170. case Engine.TEXTUREFORMAT_RGBA:
  17171. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  17172. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17173. return this._gl.RGB10_A2UI;
  17174. default:
  17175. return this._gl.RGB10_A2;
  17176. }
  17177. }
  17178. return this._gl.RGBA8;
  17179. };
  17180. ;
  17181. /** @hidden */
  17182. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17183. if (type === Engine.TEXTURETYPE_FLOAT) {
  17184. return this._gl.RGBA32F;
  17185. }
  17186. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17187. return this._gl.RGBA16F;
  17188. }
  17189. return this._gl.RGBA8;
  17190. };
  17191. ;
  17192. /** @hidden */
  17193. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17194. var _this = this;
  17195. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17196. this._activeRequests.push(request);
  17197. request.onCompleteObservable.add(function (request) {
  17198. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17199. });
  17200. return request;
  17201. };
  17202. /** @hidden */
  17203. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17204. var _this = this;
  17205. return new Promise(function (resolve, reject) {
  17206. _this._loadFile(url, function (data) {
  17207. resolve(data);
  17208. }, undefined, database, useArrayBuffer, function (request, exception) {
  17209. reject(exception);
  17210. });
  17211. });
  17212. };
  17213. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17214. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17215. var onload = function (data) {
  17216. loadedFiles[index] = data;
  17217. loadedFiles._internalCount++;
  17218. if (loadedFiles._internalCount === 6) {
  17219. onfinish(loadedFiles);
  17220. }
  17221. };
  17222. var onerror = function (request, exception) {
  17223. if (onErrorCallBack && request) {
  17224. onErrorCallBack(request.status + " " + request.statusText, exception);
  17225. }
  17226. };
  17227. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17228. };
  17229. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17230. if (onError === void 0) { onError = null; }
  17231. var loadedFiles = [];
  17232. loadedFiles._internalCount = 0;
  17233. for (var index = 0; index < 6; index++) {
  17234. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17235. }
  17236. };
  17237. // Statics
  17238. /**
  17239. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17240. * @returns true if the engine can be created
  17241. * @ignorenaming
  17242. */
  17243. Engine.isSupported = function () {
  17244. try {
  17245. var tempcanvas = document.createElement("canvas");
  17246. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17247. return gl != null && !!window.WebGLRenderingContext;
  17248. }
  17249. catch (e) {
  17250. return false;
  17251. }
  17252. };
  17253. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17254. Engine.ExceptionList = [
  17255. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17256. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17257. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17258. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17259. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17260. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17261. ];
  17262. /** Gets the list of created engines */
  17263. Engine.Instances = new Array();
  17264. /**
  17265. * Hidden
  17266. */
  17267. Engine._TextureLoaders = [];
  17268. // Const statics
  17269. /** Defines that alpha blending is disabled */
  17270. Engine.ALPHA_DISABLE = 0;
  17271. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  17272. Engine.ALPHA_ADD = 1;
  17273. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  17274. Engine.ALPHA_COMBINE = 2;
  17275. /** Defines that alpha blending to DEST - SRC * DEST */
  17276. Engine.ALPHA_SUBTRACT = 3;
  17277. /** Defines that alpha blending to SRC * DEST */
  17278. Engine.ALPHA_MULTIPLY = 4;
  17279. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  17280. Engine.ALPHA_MAXIMIZED = 5;
  17281. /** Defines that alpha blending to SRC + DEST */
  17282. Engine.ALPHA_ONEONE = 6;
  17283. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  17284. Engine.ALPHA_PREMULTIPLIED = 7;
  17285. /**
  17286. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  17287. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  17288. */
  17289. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17290. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  17291. Engine.ALPHA_INTERPOLATE = 9;
  17292. /**
  17293. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  17294. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  17295. */
  17296. Engine.ALPHA_SCREENMODE = 10;
  17297. /** Defines that the ressource is not delayed*/
  17298. Engine.DELAYLOADSTATE_NONE = 0;
  17299. /** Defines that the ressource was successfully delay loaded */
  17300. Engine.DELAYLOADSTATE_LOADED = 1;
  17301. /** Defines that the ressource is currently delay loading */
  17302. Engine.DELAYLOADSTATE_LOADING = 2;
  17303. /** Defines that the ressource is delayed and has not started loading */
  17304. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  17305. // Depht or Stencil test Constants.
  17306. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  17307. Engine.NEVER = 0x0200;
  17308. /** 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 */
  17309. Engine.ALWAYS = 0x0207;
  17310. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  17311. Engine.LESS = 0x0201;
  17312. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  17313. Engine.EQUAL = 0x0202;
  17314. /** 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 */
  17315. Engine.LEQUAL = 0x0203;
  17316. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  17317. Engine.GREATER = 0x0204;
  17318. /** 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 */
  17319. Engine.GEQUAL = 0x0206;
  17320. /** 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 */
  17321. Engine.NOTEQUAL = 0x0205;
  17322. // Stencil Actions Constants.
  17323. /** Passed to stencilOperation to specify that stencil value must be kept */
  17324. Engine.KEEP = 0x1E00;
  17325. /** Passed to stencilOperation to specify that stencil value must be replaced */
  17326. Engine.REPLACE = 0x1E01;
  17327. /** Passed to stencilOperation to specify that stencil value must be incremented */
  17328. Engine.INCR = 0x1E02;
  17329. /** Passed to stencilOperation to specify that stencil value must be decremented */
  17330. Engine.DECR = 0x1E03;
  17331. /** Passed to stencilOperation to specify that stencil value must be inverted */
  17332. Engine.INVERT = 0x150A;
  17333. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  17334. Engine.INCR_WRAP = 0x8507;
  17335. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  17336. Engine.DECR_WRAP = 0x8508;
  17337. /** Texture is not repeating outside of 0..1 UVs */
  17338. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  17339. /** Texture is repeating outside of 0..1 UVs */
  17340. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  17341. /** Texture is repeating and mirrored */
  17342. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  17343. /** ALPHA */
  17344. Engine.TEXTUREFORMAT_ALPHA = 0;
  17345. /** LUMINANCE */
  17346. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  17347. /** LUMINANCE_ALPHA */
  17348. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17349. /** RGB */
  17350. Engine.TEXTUREFORMAT_RGB = 4;
  17351. /** RGBA */
  17352. Engine.TEXTUREFORMAT_RGBA = 5;
  17353. /** RED */
  17354. Engine.TEXTUREFORMAT_RED = 6;
  17355. /** RED (2nd reference) */
  17356. Engine.TEXTUREFORMAT_R = 6;
  17357. /** RG */
  17358. Engine.TEXTUREFORMAT_RG = 7;
  17359. /** RED_INTEGER */
  17360. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  17361. /** RED_INTEGER (2nd reference) */
  17362. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  17363. /** RG_INTEGER */
  17364. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  17365. /** RGB_INTEGER */
  17366. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  17367. /** RGBA_INTEGER */
  17368. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  17369. /** UNSIGNED_BYTE */
  17370. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  17371. /** UNSIGNED_BYTE (2nd reference) */
  17372. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  17373. /** FLOAT */
  17374. Engine.TEXTURETYPE_FLOAT = 1;
  17375. /** HALF_FLOAT */
  17376. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  17377. /** BYTE */
  17378. Engine.TEXTURETYPE_BYTE = 3;
  17379. /** SHORT */
  17380. Engine.TEXTURETYPE_SHORT = 4;
  17381. /** UNSIGNED_SHORT */
  17382. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  17383. /** INT */
  17384. Engine.TEXTURETYPE_INT = 6;
  17385. /** UNSIGNED_INT */
  17386. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  17387. /** UNSIGNED_SHORT_4_4_4_4 */
  17388. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  17389. /** UNSIGNED_SHORT_5_5_5_1 */
  17390. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  17391. /** UNSIGNED_SHORT_5_6_5 */
  17392. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  17393. /** UNSIGNED_INT_2_10_10_10_REV */
  17394. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  17395. /** UNSIGNED_INT_24_8 */
  17396. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  17397. /** UNSIGNED_INT_10F_11F_11F_REV */
  17398. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  17399. /** UNSIGNED_INT_5_9_9_9_REV */
  17400. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  17401. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  17402. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  17403. /** nearest is mag = nearest and min = nearest and mip = linear */
  17404. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  17405. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17406. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  17407. /** Trilinear is mag = linear and min = linear and mip = linear */
  17408. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  17409. /** nearest is mag = nearest and min = nearest and mip = linear */
  17410. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  17411. /** Bilinear is mag = linear and min = linear and mip = nearest */
  17412. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  17413. /** Trilinear is mag = linear and min = linear and mip = linear */
  17414. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  17415. /** mag = nearest and min = nearest and mip = nearest */
  17416. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  17417. /** mag = nearest and min = linear and mip = nearest */
  17418. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  17419. /** mag = nearest and min = linear and mip = linear */
  17420. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  17421. /** mag = nearest and min = linear and mip = none */
  17422. Engine.TEXTURE_NEAREST_LINEAR = 7;
  17423. /** mag = nearest and min = nearest and mip = none */
  17424. Engine.TEXTURE_NEAREST_NEAREST = 8;
  17425. /** mag = linear and min = nearest and mip = nearest */
  17426. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  17427. /** mag = linear and min = nearest and mip = linear */
  17428. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  17429. /** mag = linear and min = linear and mip = none */
  17430. Engine.TEXTURE_LINEAR_LINEAR = 11;
  17431. /** mag = linear and min = nearest and mip = none */
  17432. Engine.TEXTURE_LINEAR_NEAREST = 12;
  17433. /** Explicit coordinates mode */
  17434. Engine.TEXTURE_EXPLICIT_MODE = 0;
  17435. /** Spherical coordinates mode */
  17436. Engine.TEXTURE_SPHERICAL_MODE = 1;
  17437. /** Planar coordinates mode */
  17438. Engine.TEXTURE_PLANAR_MODE = 2;
  17439. /** Cubic coordinates mode */
  17440. Engine.TEXTURE_CUBIC_MODE = 3;
  17441. /** Projection coordinates mode */
  17442. Engine.TEXTURE_PROJECTION_MODE = 4;
  17443. /** Skybox coordinates mode */
  17444. Engine.TEXTURE_SKYBOX_MODE = 5;
  17445. /** Inverse Cubic coordinates mode */
  17446. Engine.TEXTURE_INVCUBIC_MODE = 6;
  17447. /** Equirectangular coordinates mode */
  17448. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  17449. /** Equirectangular Fixed coordinates mode */
  17450. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  17451. /** Equirectangular Fixed Mirrored coordinates mode */
  17452. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  17453. // Texture rescaling mode
  17454. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  17455. Engine.SCALEMODE_FLOOR = 1;
  17456. /** Defines that texture rescaling will look for the nearest power of 2 size */
  17457. Engine.SCALEMODE_NEAREST = 2;
  17458. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  17459. Engine.SCALEMODE_CEILING = 3;
  17460. // Updatable statics so stick with vars here
  17461. /**
  17462. * Gets or sets the epsilon value used by collision engine
  17463. */
  17464. Engine.CollisionsEpsilon = 0.001;
  17465. /**
  17466. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17467. */
  17468. Engine.CodeRepository = "src/";
  17469. /**
  17470. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17471. */
  17472. Engine.ShadersRepository = "src/Shaders/";
  17473. return Engine;
  17474. }());
  17475. BABYLON.Engine = Engine;
  17476. })(BABYLON || (BABYLON = {}));
  17477. //# sourceMappingURL=babylon.engine.js.map
  17478. var BABYLON;
  17479. (function (BABYLON) {
  17480. /**
  17481. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17482. */
  17483. var Node = /** @class */ (function () {
  17484. /**
  17485. * Creates a new Node
  17486. * @param {string} name - the name and id to be given to this node
  17487. * @param {BABYLON.Scene} the scene this node will be added to
  17488. */
  17489. function Node(name, scene) {
  17490. if (scene === void 0) { scene = null; }
  17491. /**
  17492. * Gets or sets a string used to store user defined state for the node
  17493. */
  17494. this.state = "";
  17495. /**
  17496. * Gets or sets an object used to store user defined information for the node
  17497. */
  17498. this.metadata = null;
  17499. /**
  17500. * Gets or sets a boolean used to define if the node must be serialized
  17501. */
  17502. this.doNotSerialize = false;
  17503. /** @hidden */
  17504. this._isDisposed = false;
  17505. /**
  17506. * Gets a list of Animations associated with the node
  17507. */
  17508. this.animations = new Array();
  17509. this._ranges = {};
  17510. this._isEnabled = true;
  17511. this._isReady = true;
  17512. /** @hidden */
  17513. this._currentRenderId = -1;
  17514. this._parentRenderId = -1;
  17515. this._childRenderId = -1;
  17516. this._animationPropertiesOverride = null;
  17517. /**
  17518. * An event triggered when the mesh is disposed
  17519. */
  17520. this.onDisposeObservable = new BABYLON.Observable();
  17521. // Behaviors
  17522. this._behaviors = new Array();
  17523. this.name = name;
  17524. this.id = name;
  17525. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17526. this.uniqueId = this._scene.getUniqueId();
  17527. this._initCache();
  17528. }
  17529. /**
  17530. * Add a new node constructor
  17531. * @param type defines the type name of the node to construct
  17532. * @param constructorFunc defines the constructor function
  17533. */
  17534. Node.AddNodeConstructor = function (type, constructorFunc) {
  17535. this._NodeConstructors[type] = constructorFunc;
  17536. };
  17537. /**
  17538. * Returns a node constructor based on type name
  17539. * @param type defines the type name
  17540. * @param name defines the new node name
  17541. * @param scene defines the hosting scene
  17542. * @param options defines optional options to transmit to constructors
  17543. * @returns the new constructor or null
  17544. */
  17545. Node.Construct = function (type, name, scene, options) {
  17546. var constructorFunc = this._NodeConstructors[type];
  17547. if (!constructorFunc) {
  17548. return null;
  17549. }
  17550. return constructorFunc(name, scene, options);
  17551. };
  17552. /**
  17553. * Gets a boolean indicating if the node has been disposed
  17554. * @returns true if the node was disposed
  17555. */
  17556. Node.prototype.isDisposed = function () {
  17557. return this._isDisposed;
  17558. };
  17559. Object.defineProperty(Node.prototype, "parent", {
  17560. get: function () {
  17561. return this._parentNode;
  17562. },
  17563. /**
  17564. * Gets or sets the parent of the node
  17565. */
  17566. set: function (parent) {
  17567. if (this._parentNode === parent) {
  17568. return;
  17569. }
  17570. // Remove self from list of children of parent
  17571. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17572. var index = this._parentNode._children.indexOf(this);
  17573. if (index !== -1) {
  17574. this._parentNode._children.splice(index, 1);
  17575. }
  17576. }
  17577. // Store new parent
  17578. this._parentNode = parent;
  17579. // Add as child to new parent
  17580. if (this._parentNode) {
  17581. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17582. this._parentNode._children = new Array();
  17583. }
  17584. this._parentNode._children.push(this);
  17585. }
  17586. },
  17587. enumerable: true,
  17588. configurable: true
  17589. });
  17590. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17591. /**
  17592. * Gets or sets the animation properties override
  17593. */
  17594. get: function () {
  17595. if (!this._animationPropertiesOverride) {
  17596. return this._scene.animationPropertiesOverride;
  17597. }
  17598. return this._animationPropertiesOverride;
  17599. },
  17600. set: function (value) {
  17601. this._animationPropertiesOverride = value;
  17602. },
  17603. enumerable: true,
  17604. configurable: true
  17605. });
  17606. /**
  17607. * Gets a string idenfifying the name of the class
  17608. * @returns "Node" string
  17609. */
  17610. Node.prototype.getClassName = function () {
  17611. return "Node";
  17612. };
  17613. Object.defineProperty(Node.prototype, "onDispose", {
  17614. /**
  17615. * Sets a callback that will be raised when the node will be disposed
  17616. */
  17617. set: function (callback) {
  17618. if (this._onDisposeObserver) {
  17619. this.onDisposeObservable.remove(this._onDisposeObserver);
  17620. }
  17621. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17622. },
  17623. enumerable: true,
  17624. configurable: true
  17625. });
  17626. /**
  17627. * Gets the scene of the node
  17628. * @returns a {BABYLON.Scene}
  17629. */
  17630. Node.prototype.getScene = function () {
  17631. return this._scene;
  17632. };
  17633. /**
  17634. * Gets the engine of the node
  17635. * @returns a {BABYLON.Engine}
  17636. */
  17637. Node.prototype.getEngine = function () {
  17638. return this._scene.getEngine();
  17639. };
  17640. /**
  17641. * Attach a behavior to the node
  17642. * @see http://doc.babylonjs.com/features/behaviour
  17643. * @param behavior defines the behavior to attach
  17644. * @returns the current Node
  17645. */
  17646. Node.prototype.addBehavior = function (behavior) {
  17647. var _this = this;
  17648. var index = this._behaviors.indexOf(behavior);
  17649. if (index !== -1) {
  17650. return this;
  17651. }
  17652. behavior.init();
  17653. if (this._scene.isLoading) {
  17654. // We defer the attach when the scene will be loaded
  17655. this._scene.onDataLoadedObservable.addOnce(function () {
  17656. behavior.attach(_this);
  17657. });
  17658. }
  17659. else {
  17660. behavior.attach(this);
  17661. }
  17662. this._behaviors.push(behavior);
  17663. return this;
  17664. };
  17665. /**
  17666. * Remove an attached behavior
  17667. * @see http://doc.babylonjs.com/features/behaviour
  17668. * @param behavior defines the behavior to attach
  17669. * @returns the current Node
  17670. */
  17671. Node.prototype.removeBehavior = function (behavior) {
  17672. var index = this._behaviors.indexOf(behavior);
  17673. if (index === -1) {
  17674. return this;
  17675. }
  17676. this._behaviors[index].detach();
  17677. this._behaviors.splice(index, 1);
  17678. return this;
  17679. };
  17680. Object.defineProperty(Node.prototype, "behaviors", {
  17681. /**
  17682. * Gets the list of attached behaviors
  17683. * @see http://doc.babylonjs.com/features/behaviour
  17684. */
  17685. get: function () {
  17686. return this._behaviors;
  17687. },
  17688. enumerable: true,
  17689. configurable: true
  17690. });
  17691. /**
  17692. * Gets an attached behavior by name
  17693. * @param name defines the name of the behavior to look for
  17694. * @see http://doc.babylonjs.com/features/behaviour
  17695. * @returns null if behavior was not found else the requested behavior
  17696. */
  17697. Node.prototype.getBehaviorByName = function (name) {
  17698. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17699. var behavior = _a[_i];
  17700. if (behavior.name === name) {
  17701. return behavior;
  17702. }
  17703. }
  17704. return null;
  17705. };
  17706. /**
  17707. * Returns the world matrix of the node
  17708. * @returns a matrix containing the node's world matrix
  17709. */
  17710. Node.prototype.getWorldMatrix = function () {
  17711. return BABYLON.Matrix.Identity();
  17712. };
  17713. /** @hidden */
  17714. Node.prototype._getWorldMatrixDeterminant = function () {
  17715. return 1;
  17716. };
  17717. // override it in derived class if you add new variables to the cache
  17718. // and call the parent class method
  17719. /** @hidden */
  17720. Node.prototype._initCache = function () {
  17721. this._cache = {};
  17722. this._cache.parent = undefined;
  17723. };
  17724. /** @hidden */
  17725. Node.prototype.updateCache = function (force) {
  17726. if (!force && this.isSynchronized())
  17727. return;
  17728. this._cache.parent = this.parent;
  17729. this._updateCache();
  17730. };
  17731. // override it in derived class if you add new variables to the cache
  17732. // and call the parent class method if !ignoreParentClass
  17733. /** @hidden */
  17734. Node.prototype._updateCache = function (ignoreParentClass) {
  17735. };
  17736. // override it in derived class if you add new variables to the cache
  17737. /** @hidden */
  17738. Node.prototype._isSynchronized = function () {
  17739. return true;
  17740. };
  17741. /** @hidden */
  17742. Node.prototype._markSyncedWithParent = function () {
  17743. if (this.parent) {
  17744. this._parentRenderId = this.parent._childRenderId;
  17745. }
  17746. };
  17747. /** @hidden */
  17748. Node.prototype.isSynchronizedWithParent = function () {
  17749. if (!this.parent) {
  17750. return true;
  17751. }
  17752. if (this._parentRenderId !== this.parent._childRenderId) {
  17753. return false;
  17754. }
  17755. return this.parent.isSynchronized();
  17756. };
  17757. /** @hidden */
  17758. Node.prototype.isSynchronized = function (updateCache) {
  17759. var check = this.hasNewParent();
  17760. check = check || !this.isSynchronizedWithParent();
  17761. check = check || !this._isSynchronized();
  17762. if (updateCache)
  17763. this.updateCache(true);
  17764. return !check;
  17765. };
  17766. /** @hidden */
  17767. Node.prototype.hasNewParent = function (update) {
  17768. if (this._cache.parent === this.parent)
  17769. return false;
  17770. if (update)
  17771. this._cache.parent = this.parent;
  17772. return true;
  17773. };
  17774. /**
  17775. * Is this node ready to be used/rendered
  17776. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17777. * @return true if the node is ready
  17778. */
  17779. Node.prototype.isReady = function (completeCheck) {
  17780. if (completeCheck === void 0) { completeCheck = false; }
  17781. return this._isReady;
  17782. };
  17783. /**
  17784. * Is this node enabled?
  17785. * 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
  17786. * @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
  17787. * @return whether this node (and its parent) is enabled
  17788. */
  17789. Node.prototype.isEnabled = function (checkAncestors) {
  17790. if (checkAncestors === void 0) { checkAncestors = true; }
  17791. if (checkAncestors === false) {
  17792. return this._isEnabled;
  17793. }
  17794. if (this._isEnabled === false) {
  17795. return false;
  17796. }
  17797. if (this.parent !== undefined && this.parent !== null) {
  17798. return this.parent.isEnabled(checkAncestors);
  17799. }
  17800. return true;
  17801. };
  17802. /**
  17803. * Set the enabled state of this node
  17804. * @param value defines the new enabled state
  17805. */
  17806. Node.prototype.setEnabled = function (value) {
  17807. this._isEnabled = value;
  17808. };
  17809. /**
  17810. * Is this node a descendant of the given node?
  17811. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17812. * @param ancestor defines the parent node to inspect
  17813. * @returns a boolean indicating if this node is a descendant of the given node
  17814. */
  17815. Node.prototype.isDescendantOf = function (ancestor) {
  17816. if (this.parent) {
  17817. if (this.parent === ancestor) {
  17818. return true;
  17819. }
  17820. return this.parent.isDescendantOf(ancestor);
  17821. }
  17822. return false;
  17823. };
  17824. /** @hidden */
  17825. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17826. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17827. if (!this._children) {
  17828. return;
  17829. }
  17830. for (var index = 0; index < this._children.length; index++) {
  17831. var item = this._children[index];
  17832. if (!predicate || predicate(item)) {
  17833. results.push(item);
  17834. }
  17835. if (!directDescendantsOnly) {
  17836. item._getDescendants(results, false, predicate);
  17837. }
  17838. }
  17839. };
  17840. /**
  17841. * Will return all nodes that have this node as ascendant
  17842. * @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
  17843. * @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
  17844. * @return all children nodes of all types
  17845. */
  17846. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17847. var results = new Array();
  17848. this._getDescendants(results, directDescendantsOnly, predicate);
  17849. return results;
  17850. };
  17851. /**
  17852. * Get all child-meshes of this node
  17853. * @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
  17854. * @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
  17855. * @returns an array of {BABYLON.AbstractMesh}
  17856. */
  17857. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17858. var results = [];
  17859. this._getDescendants(results, directDescendantsOnly, function (node) {
  17860. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17861. });
  17862. return results;
  17863. };
  17864. /**
  17865. * Get all child-transformNodes of this node
  17866. * @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
  17867. * @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
  17868. * @returns an array of {BABYLON.TransformNode}
  17869. */
  17870. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17871. var results = [];
  17872. this._getDescendants(results, directDescendantsOnly, function (node) {
  17873. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17874. });
  17875. return results;
  17876. };
  17877. /**
  17878. * Get all direct children of this node
  17879. * @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
  17880. * @returns an array of {BABYLON.Node}
  17881. */
  17882. Node.prototype.getChildren = function (predicate) {
  17883. return this.getDescendants(true, predicate);
  17884. };
  17885. /** @hidden */
  17886. Node.prototype._setReady = function (state) {
  17887. if (state === this._isReady) {
  17888. return;
  17889. }
  17890. if (!state) {
  17891. this._isReady = false;
  17892. return;
  17893. }
  17894. if (this.onReady) {
  17895. this.onReady(this);
  17896. }
  17897. this._isReady = true;
  17898. };
  17899. /**
  17900. * Get an animation by name
  17901. * @param name defines the name of the animation to look for
  17902. * @returns null if not found else the requested animation
  17903. */
  17904. Node.prototype.getAnimationByName = function (name) {
  17905. for (var i = 0; i < this.animations.length; i++) {
  17906. var animation = this.animations[i];
  17907. if (animation.name === name) {
  17908. return animation;
  17909. }
  17910. }
  17911. return null;
  17912. };
  17913. /**
  17914. * Creates an animation range for this node
  17915. * @param name defines the name of the range
  17916. * @param from defines the starting key
  17917. * @param to defines the end key
  17918. */
  17919. Node.prototype.createAnimationRange = function (name, from, to) {
  17920. // check name not already in use
  17921. if (!this._ranges[name]) {
  17922. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17923. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17924. if (this.animations[i]) {
  17925. this.animations[i].createRange(name, from, to);
  17926. }
  17927. }
  17928. }
  17929. };
  17930. /**
  17931. * Delete a specific animation range
  17932. * @param name defines the name of the range to delete
  17933. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17934. */
  17935. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17936. if (deleteFrames === void 0) { deleteFrames = true; }
  17937. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17938. if (this.animations[i]) {
  17939. this.animations[i].deleteRange(name, deleteFrames);
  17940. }
  17941. }
  17942. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17943. };
  17944. /**
  17945. * Get an animation range by name
  17946. * @param name defines the name of the animation range to look for
  17947. * @returns null if not found else the requested animation range
  17948. */
  17949. Node.prototype.getAnimationRange = function (name) {
  17950. return this._ranges[name];
  17951. };
  17952. /**
  17953. * Will start the animation sequence
  17954. * @param name defines the range frames for animation sequence
  17955. * @param loop defines if the animation should loop (false by default)
  17956. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17957. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17958. * @returns the object created for this animation. If range does not exist, it will return null
  17959. */
  17960. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17961. var range = this.getAnimationRange(name);
  17962. if (!range) {
  17963. return null;
  17964. }
  17965. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17966. };
  17967. /**
  17968. * Serialize animation ranges into a JSON compatible object
  17969. * @returns serialization object
  17970. */
  17971. Node.prototype.serializeAnimationRanges = function () {
  17972. var serializationRanges = [];
  17973. for (var name in this._ranges) {
  17974. var localRange = this._ranges[name];
  17975. if (!localRange) {
  17976. continue;
  17977. }
  17978. var range = {};
  17979. range.name = name;
  17980. range.from = localRange.from;
  17981. range.to = localRange.to;
  17982. serializationRanges.push(range);
  17983. }
  17984. return serializationRanges;
  17985. };
  17986. /**
  17987. * Computes the world matrix of the node
  17988. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17989. * @returns the world matrix
  17990. */
  17991. Node.prototype.computeWorldMatrix = function (force) {
  17992. return BABYLON.Matrix.Identity();
  17993. };
  17994. /**
  17995. * Releases resources associated with this node.
  17996. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17997. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17998. */
  17999. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18000. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18001. if (!doNotRecurse) {
  18002. var nodes = this.getDescendants(true);
  18003. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18004. var node = nodes_1[_i];
  18005. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18006. }
  18007. }
  18008. else {
  18009. var transformNodes = this.getChildTransformNodes(true);
  18010. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18011. var transformNode = transformNodes_1[_a];
  18012. transformNode.parent = null;
  18013. transformNode.computeWorldMatrix(true);
  18014. }
  18015. }
  18016. this.parent = null;
  18017. // Callback
  18018. this.onDisposeObservable.notifyObservers(this);
  18019. this.onDisposeObservable.clear();
  18020. // Behaviors
  18021. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18022. var behavior = _c[_b];
  18023. behavior.detach();
  18024. }
  18025. this._behaviors = [];
  18026. this._isDisposed = true;
  18027. };
  18028. /**
  18029. * Parse animation range data from a serialization object and store them into a given node
  18030. * @param node defines where to store the animation ranges
  18031. * @param parsedNode defines the serialization object to read data from
  18032. * @param scene defines the hosting scene
  18033. */
  18034. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18035. if (parsedNode.ranges) {
  18036. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18037. var data = parsedNode.ranges[index];
  18038. node.createAnimationRange(data.name, data.from, data.to);
  18039. }
  18040. }
  18041. };
  18042. Node._NodeConstructors = {};
  18043. __decorate([
  18044. BABYLON.serialize()
  18045. ], Node.prototype, "name", void 0);
  18046. __decorate([
  18047. BABYLON.serialize()
  18048. ], Node.prototype, "id", void 0);
  18049. __decorate([
  18050. BABYLON.serialize()
  18051. ], Node.prototype, "uniqueId", void 0);
  18052. __decorate([
  18053. BABYLON.serialize()
  18054. ], Node.prototype, "state", void 0);
  18055. __decorate([
  18056. BABYLON.serialize()
  18057. ], Node.prototype, "metadata", void 0);
  18058. return Node;
  18059. }());
  18060. BABYLON.Node = Node;
  18061. })(BABYLON || (BABYLON = {}));
  18062. //# sourceMappingURL=babylon.node.js.map
  18063. var BABYLON;
  18064. (function (BABYLON) {
  18065. var BoundingSphere = /** @class */ (function () {
  18066. /**
  18067. * Creates a new bounding sphere
  18068. * @param min defines the minimum vector (in local space)
  18069. * @param max defines the maximum vector (in local space)
  18070. */
  18071. function BoundingSphere(min, max) {
  18072. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18073. this.reConstruct(min, max);
  18074. }
  18075. /**
  18076. * Recreates the entire bounding sphere from scratch
  18077. * @param min defines the new minimum vector (in local space)
  18078. * @param max defines the new maximum vector (in local space)
  18079. */
  18080. BoundingSphere.prototype.reConstruct = function (min, max) {
  18081. this.minimum = min.clone();
  18082. this.maximum = max.clone();
  18083. var distance = BABYLON.Vector3.Distance(min, max);
  18084. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18085. this.radius = distance * 0.5;
  18086. this.centerWorld = BABYLON.Vector3.Zero();
  18087. this._update(BABYLON.Matrix.Identity());
  18088. };
  18089. /**
  18090. * Scale the current bounding sphere by applying a scale factor
  18091. * @param factor defines the scale factor to apply
  18092. * @returns the current bounding box
  18093. */
  18094. BoundingSphere.prototype.scale = function (factor) {
  18095. var newRadius = this.radius * factor;
  18096. var newRadiusVector = new BABYLON.Vector3(newRadius, newRadius, newRadius);
  18097. var min = this.center.subtract(newRadiusVector);
  18098. var max = this.center.add(newRadiusVector);
  18099. this.reConstruct(min, max);
  18100. return this;
  18101. };
  18102. // Methods
  18103. /** @hidden */
  18104. BoundingSphere.prototype._update = function (world) {
  18105. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18106. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18107. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18108. };
  18109. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18110. for (var i = 0; i < 6; i++) {
  18111. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18112. return false;
  18113. }
  18114. return true;
  18115. };
  18116. BoundingSphere.prototype.intersectsPoint = function (point) {
  18117. var x = this.centerWorld.x - point.x;
  18118. var y = this.centerWorld.y - point.y;
  18119. var z = this.centerWorld.z - point.z;
  18120. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18121. if (this.radiusWorld < distance)
  18122. return false;
  18123. return true;
  18124. };
  18125. // Statics
  18126. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18127. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18128. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18129. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18130. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18131. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18132. return false;
  18133. return true;
  18134. };
  18135. return BoundingSphere;
  18136. }());
  18137. BABYLON.BoundingSphere = BoundingSphere;
  18138. })(BABYLON || (BABYLON = {}));
  18139. //# sourceMappingURL=babylon.boundingSphere.js.map
  18140. var BABYLON;
  18141. (function (BABYLON) {
  18142. var BoundingBox = /** @class */ (function () {
  18143. /**
  18144. * Creates a new bounding box
  18145. * @param min defines the minimum vector (in local space)
  18146. * @param max defines the maximum vector (in local space)
  18147. */
  18148. function BoundingBox(min, max) {
  18149. this.vectorsWorld = new Array();
  18150. this.reConstruct(min, max);
  18151. }
  18152. // Methods
  18153. /**
  18154. * Recreates the entire bounding box from scratch
  18155. * @param min defines the new minimum vector (in local space)
  18156. * @param max defines the new maximum vector (in local space)
  18157. */
  18158. BoundingBox.prototype.reConstruct = function (min, max) {
  18159. this.minimum = min.clone();
  18160. this.maximum = max.clone();
  18161. // Bounding vectors
  18162. this.vectors = new Array();
  18163. this.vectors.push(this.minimum.clone());
  18164. this.vectors.push(this.maximum.clone());
  18165. this.vectors.push(this.minimum.clone());
  18166. this.vectors[2].x = this.maximum.x;
  18167. this.vectors.push(this.minimum.clone());
  18168. this.vectors[3].y = this.maximum.y;
  18169. this.vectors.push(this.minimum.clone());
  18170. this.vectors[4].z = this.maximum.z;
  18171. this.vectors.push(this.maximum.clone());
  18172. this.vectors[5].z = this.minimum.z;
  18173. this.vectors.push(this.maximum.clone());
  18174. this.vectors[6].x = this.minimum.x;
  18175. this.vectors.push(this.maximum.clone());
  18176. this.vectors[7].y = this.minimum.y;
  18177. // OBB
  18178. this.center = this.maximum.add(this.minimum).scale(0.5);
  18179. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18180. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18181. // World
  18182. for (var index = 0; index < this.vectors.length; index++) {
  18183. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18184. }
  18185. this.minimumWorld = BABYLON.Vector3.Zero();
  18186. this.maximumWorld = BABYLON.Vector3.Zero();
  18187. this.centerWorld = BABYLON.Vector3.Zero();
  18188. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18189. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18190. };
  18191. /**
  18192. * Scale the current bounding box by applying a scale factor
  18193. * @param factor defines the scale factor to apply
  18194. * @returns the current bounding box
  18195. */
  18196. BoundingBox.prototype.scale = function (factor) {
  18197. var diff = this.maximum.subtract(this.minimum);
  18198. var distance = diff.length() * factor;
  18199. diff.normalize();
  18200. var newRadius = diff.scale(distance / 2);
  18201. var min = this.center.subtract(newRadius);
  18202. var max = this.center.add(newRadius);
  18203. this.reConstruct(min, max);
  18204. return this;
  18205. };
  18206. BoundingBox.prototype.getWorldMatrix = function () {
  18207. return this._worldMatrix;
  18208. };
  18209. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18210. this._worldMatrix.copyFrom(matrix);
  18211. return this;
  18212. };
  18213. /** @hidden */
  18214. BoundingBox.prototype._update = function (world) {
  18215. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18216. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18217. for (var index = 0; index < this.vectors.length; index++) {
  18218. var v = this.vectorsWorld[index];
  18219. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18220. if (v.x < this.minimumWorld.x)
  18221. this.minimumWorld.x = v.x;
  18222. if (v.y < this.minimumWorld.y)
  18223. this.minimumWorld.y = v.y;
  18224. if (v.z < this.minimumWorld.z)
  18225. this.minimumWorld.z = v.z;
  18226. if (v.x > this.maximumWorld.x)
  18227. this.maximumWorld.x = v.x;
  18228. if (v.y > this.maximumWorld.y)
  18229. this.maximumWorld.y = v.y;
  18230. if (v.z > this.maximumWorld.z)
  18231. this.maximumWorld.z = v.z;
  18232. }
  18233. // Extend
  18234. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18235. this.extendSizeWorld.scaleInPlace(0.5);
  18236. // OBB
  18237. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18238. this.centerWorld.scaleInPlace(0.5);
  18239. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18240. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18241. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18242. this._worldMatrix = world;
  18243. };
  18244. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18245. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18246. };
  18247. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18248. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18249. };
  18250. BoundingBox.prototype.intersectsPoint = function (point) {
  18251. var delta = -BABYLON.Epsilon;
  18252. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18253. return false;
  18254. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18255. return false;
  18256. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18257. return false;
  18258. return true;
  18259. };
  18260. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18261. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18262. };
  18263. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18264. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18265. return false;
  18266. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18267. return false;
  18268. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18269. return false;
  18270. return true;
  18271. };
  18272. // Statics
  18273. BoundingBox.Intersects = function (box0, box1) {
  18274. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18275. return false;
  18276. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18277. return false;
  18278. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18279. return false;
  18280. return true;
  18281. };
  18282. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18283. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18284. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18285. return (num <= (sphereRadius * sphereRadius));
  18286. };
  18287. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18288. for (var p = 0; p < 6; p++) {
  18289. for (var i = 0; i < 8; i++) {
  18290. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18291. return false;
  18292. }
  18293. }
  18294. }
  18295. return true;
  18296. };
  18297. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18298. for (var p = 0; p < 6; p++) {
  18299. var inCount = 8;
  18300. for (var i = 0; i < 8; i++) {
  18301. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18302. --inCount;
  18303. }
  18304. else {
  18305. break;
  18306. }
  18307. }
  18308. if (inCount === 0)
  18309. return false;
  18310. }
  18311. return true;
  18312. };
  18313. return BoundingBox;
  18314. }());
  18315. BABYLON.BoundingBox = BoundingBox;
  18316. })(BABYLON || (BABYLON = {}));
  18317. //# sourceMappingURL=babylon.boundingBox.js.map
  18318. var BABYLON;
  18319. (function (BABYLON) {
  18320. var computeBoxExtents = function (axis, box) {
  18321. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18322. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18323. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18324. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18325. var r = r0 + r1 + r2;
  18326. return {
  18327. min: p - r,
  18328. max: p + r
  18329. };
  18330. };
  18331. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18332. var axisOverlap = function (axis, box0, box1) {
  18333. var result0 = computeBoxExtents(axis, box0);
  18334. var result1 = computeBoxExtents(axis, box1);
  18335. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18336. };
  18337. var BoundingInfo = /** @class */ (function () {
  18338. function BoundingInfo(minimum, maximum) {
  18339. this.minimum = minimum;
  18340. this.maximum = maximum;
  18341. this._isLocked = false;
  18342. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18343. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18344. }
  18345. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18346. get: function () {
  18347. return this._isLocked;
  18348. },
  18349. set: function (value) {
  18350. this._isLocked = value;
  18351. },
  18352. enumerable: true,
  18353. configurable: true
  18354. });
  18355. // Methods
  18356. BoundingInfo.prototype.update = function (world) {
  18357. if (this._isLocked) {
  18358. return;
  18359. }
  18360. this.boundingBox._update(world);
  18361. this.boundingSphere._update(world);
  18362. };
  18363. /**
  18364. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18365. * @param center New center of the bounding info
  18366. * @param extend New extend of the bounding info
  18367. */
  18368. BoundingInfo.prototype.centerOn = function (center, extend) {
  18369. this.minimum = center.subtract(extend);
  18370. this.maximum = center.add(extend);
  18371. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18372. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18373. return this;
  18374. };
  18375. /**
  18376. * Scale the current bounding info by applying a scale factor
  18377. * @param factor defines the scale factor to apply
  18378. * @returns the current bounding info
  18379. */
  18380. BoundingInfo.prototype.scale = function (factor) {
  18381. this.boundingBox.scale(factor);
  18382. this.boundingSphere.scale(factor);
  18383. return this;
  18384. };
  18385. /**
  18386. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  18387. * @param frustumPlanes defines the frustum to test
  18388. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  18389. * @returns true if the bounding info is in the frustum planes
  18390. */
  18391. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  18392. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  18393. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  18394. return false;
  18395. }
  18396. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  18397. return true;
  18398. }
  18399. return this.boundingBox.isInFrustum(frustumPlanes);
  18400. };
  18401. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18402. /**
  18403. * Gets the world distance between the min and max points of the bounding box
  18404. */
  18405. get: function () {
  18406. var boundingBox = this.boundingBox;
  18407. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18408. return size.length();
  18409. },
  18410. enumerable: true,
  18411. configurable: true
  18412. });
  18413. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18414. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18415. };
  18416. /** @hidden */
  18417. BoundingInfo.prototype._checkCollision = function (collider) {
  18418. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18419. };
  18420. BoundingInfo.prototype.intersectsPoint = function (point) {
  18421. if (!this.boundingSphere.centerWorld) {
  18422. return false;
  18423. }
  18424. if (!this.boundingSphere.intersectsPoint(point)) {
  18425. return false;
  18426. }
  18427. if (!this.boundingBox.intersectsPoint(point)) {
  18428. return false;
  18429. }
  18430. return true;
  18431. };
  18432. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18433. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18434. return false;
  18435. }
  18436. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18437. return false;
  18438. }
  18439. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18440. return false;
  18441. }
  18442. if (!precise) {
  18443. return true;
  18444. }
  18445. var box0 = this.boundingBox;
  18446. var box1 = boundingInfo.boundingBox;
  18447. if (!axisOverlap(box0.directions[0], box0, box1))
  18448. return false;
  18449. if (!axisOverlap(box0.directions[1], box0, box1))
  18450. return false;
  18451. if (!axisOverlap(box0.directions[2], box0, box1))
  18452. return false;
  18453. if (!axisOverlap(box1.directions[0], box0, box1))
  18454. return false;
  18455. if (!axisOverlap(box1.directions[1], box0, box1))
  18456. return false;
  18457. if (!axisOverlap(box1.directions[2], box0, box1))
  18458. return false;
  18459. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18460. return false;
  18461. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18462. return false;
  18463. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18464. return false;
  18465. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18466. return false;
  18467. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18468. return false;
  18469. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18470. return false;
  18471. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18472. return false;
  18473. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18474. return false;
  18475. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18476. return false;
  18477. return true;
  18478. };
  18479. return BoundingInfo;
  18480. }());
  18481. BABYLON.BoundingInfo = BoundingInfo;
  18482. })(BABYLON || (BABYLON = {}));
  18483. //# sourceMappingURL=babylon.boundingInfo.js.map
  18484. var BABYLON;
  18485. (function (BABYLON) {
  18486. var TransformNode = /** @class */ (function (_super) {
  18487. __extends(TransformNode, _super);
  18488. function TransformNode(name, scene, isPure) {
  18489. if (scene === void 0) { scene = null; }
  18490. if (isPure === void 0) { isPure = true; }
  18491. var _this = _super.call(this, name, scene) || this;
  18492. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18493. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18494. _this._up = new BABYLON.Vector3(0, 1, 0);
  18495. _this._right = new BABYLON.Vector3(1, 0, 0);
  18496. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18497. // Properties
  18498. _this._rotation = BABYLON.Vector3.Zero();
  18499. _this._scaling = BABYLON.Vector3.One();
  18500. _this._isDirty = false;
  18501. /**
  18502. * Set the billboard mode. Default is 0.
  18503. *
  18504. * | Value | Type | Description |
  18505. * | --- | --- | --- |
  18506. * | 0 | BILLBOARDMODE_NONE | |
  18507. * | 1 | BILLBOARDMODE_X | |
  18508. * | 2 | BILLBOARDMODE_Y | |
  18509. * | 4 | BILLBOARDMODE_Z | |
  18510. * | 7 | BILLBOARDMODE_ALL | |
  18511. *
  18512. */
  18513. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18514. _this.scalingDeterminant = 1;
  18515. _this.infiniteDistance = false;
  18516. /**
  18517. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18518. * By default the system will update normals to compensate
  18519. */
  18520. _this.ignoreNonUniformScaling = false;
  18521. _this.position = BABYLON.Vector3.Zero();
  18522. _this._localWorld = BABYLON.Matrix.Zero();
  18523. /** @hidden */
  18524. _this._worldMatrix = BABYLON.Matrix.Zero();
  18525. /** @hidden */
  18526. _this._worldMatrixDeterminant = 0;
  18527. _this._absolutePosition = BABYLON.Vector3.Zero();
  18528. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18529. _this._postMultiplyPivotMatrix = false;
  18530. _this._isWorldMatrixFrozen = false;
  18531. /**
  18532. * An event triggered after the world matrix is updated
  18533. */
  18534. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18535. _this._nonUniformScaling = false;
  18536. if (isPure) {
  18537. _this.getScene().addTransformNode(_this);
  18538. }
  18539. return _this;
  18540. }
  18541. /**
  18542. * Gets a string identifying the name of the class
  18543. * @returns "TransformNode" string
  18544. */
  18545. TransformNode.prototype.getClassName = function () {
  18546. return "TransformNode";
  18547. };
  18548. Object.defineProperty(TransformNode.prototype, "rotation", {
  18549. /**
  18550. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18551. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18552. * Default : (0.0, 0.0, 0.0)
  18553. */
  18554. get: function () {
  18555. return this._rotation;
  18556. },
  18557. set: function (newRotation) {
  18558. this._rotation = newRotation;
  18559. },
  18560. enumerable: true,
  18561. configurable: true
  18562. });
  18563. Object.defineProperty(TransformNode.prototype, "scaling", {
  18564. /**
  18565. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18566. * Default : (1.0, 1.0, 1.0)
  18567. */
  18568. get: function () {
  18569. return this._scaling;
  18570. },
  18571. /**
  18572. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18573. * Default : (1.0, 1.0, 1.0)
  18574. */
  18575. set: function (newScaling) {
  18576. this._scaling = newScaling;
  18577. },
  18578. enumerable: true,
  18579. configurable: true
  18580. });
  18581. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18582. /**
  18583. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18584. * It's null by default.
  18585. * 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)
  18586. */
  18587. get: function () {
  18588. return this._rotationQuaternion;
  18589. },
  18590. set: function (quaternion) {
  18591. this._rotationQuaternion = quaternion;
  18592. //reset the rotation vector.
  18593. if (quaternion && this.rotation.length()) {
  18594. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18595. }
  18596. },
  18597. enumerable: true,
  18598. configurable: true
  18599. });
  18600. Object.defineProperty(TransformNode.prototype, "forward", {
  18601. /**
  18602. * The forward direction of that transform in world space.
  18603. */
  18604. get: function () {
  18605. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18606. },
  18607. enumerable: true,
  18608. configurable: true
  18609. });
  18610. Object.defineProperty(TransformNode.prototype, "up", {
  18611. /**
  18612. * The up direction of that transform in world space.
  18613. */
  18614. get: function () {
  18615. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18616. },
  18617. enumerable: true,
  18618. configurable: true
  18619. });
  18620. Object.defineProperty(TransformNode.prototype, "right", {
  18621. /**
  18622. * The right direction of that transform in world space.
  18623. */
  18624. get: function () {
  18625. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18626. },
  18627. enumerable: true,
  18628. configurable: true
  18629. });
  18630. /**
  18631. * Returns the latest update of the World matrix
  18632. * Returns a Matrix.
  18633. */
  18634. TransformNode.prototype.getWorldMatrix = function () {
  18635. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18636. this.computeWorldMatrix();
  18637. }
  18638. return this._worldMatrix;
  18639. };
  18640. /** @hidden */
  18641. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18642. return this._worldMatrixDeterminant;
  18643. };
  18644. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18645. /**
  18646. * Returns directly the latest state of the mesh World matrix.
  18647. * A Matrix is returned.
  18648. */
  18649. get: function () {
  18650. return this._worldMatrix;
  18651. },
  18652. enumerable: true,
  18653. configurable: true
  18654. });
  18655. /**
  18656. * Copies the parameter passed Matrix into the mesh Pose matrix.
  18657. * Returns the TransformNode.
  18658. */
  18659. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18660. this._poseMatrix.copyFrom(matrix);
  18661. return this;
  18662. };
  18663. /**
  18664. * Returns the mesh Pose matrix.
  18665. * Returned object : Matrix
  18666. */
  18667. TransformNode.prototype.getPoseMatrix = function () {
  18668. return this._poseMatrix;
  18669. };
  18670. /** @hidden */
  18671. TransformNode.prototype._isSynchronized = function () {
  18672. if (this._isDirty) {
  18673. return false;
  18674. }
  18675. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18676. return false;
  18677. if (this._cache.pivotMatrixUpdated) {
  18678. return false;
  18679. }
  18680. if (this.infiniteDistance) {
  18681. return false;
  18682. }
  18683. if (!this._cache.position.equals(this.position))
  18684. return false;
  18685. if (this.rotationQuaternion) {
  18686. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18687. return false;
  18688. }
  18689. if (!this._cache.rotation.equals(this.rotation))
  18690. return false;
  18691. if (!this._cache.scaling.equals(this.scaling))
  18692. return false;
  18693. return true;
  18694. };
  18695. /** @hidden */
  18696. TransformNode.prototype._initCache = function () {
  18697. _super.prototype._initCache.call(this);
  18698. this._cache.localMatrixUpdated = false;
  18699. this._cache.position = BABYLON.Vector3.Zero();
  18700. this._cache.scaling = BABYLON.Vector3.Zero();
  18701. this._cache.rotation = BABYLON.Vector3.Zero();
  18702. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18703. this._cache.billboardMode = -1;
  18704. };
  18705. TransformNode.prototype.markAsDirty = function (property) {
  18706. if (property === "rotation") {
  18707. this.rotationQuaternion = null;
  18708. }
  18709. this._currentRenderId = Number.MAX_VALUE;
  18710. this._isDirty = true;
  18711. return this;
  18712. };
  18713. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18714. /**
  18715. * Returns the current mesh absolute position.
  18716. * Returns a Vector3.
  18717. */
  18718. get: function () {
  18719. return this._absolutePosition;
  18720. },
  18721. enumerable: true,
  18722. configurable: true
  18723. });
  18724. /**
  18725. * Sets a new matrix to apply before all other transformation
  18726. * @param matrix defines the transform matrix
  18727. * @returns the current TransformNode
  18728. */
  18729. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18730. return this.setPivotMatrix(matrix, false);
  18731. };
  18732. /**
  18733. * Sets a new pivot matrix to the current node
  18734. * @param matrix defines the new pivot matrix to use
  18735. * @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
  18736. * @returns the current TransformNode
  18737. */
  18738. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18739. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18740. this._pivotMatrix = matrix.clone();
  18741. this._cache.pivotMatrixUpdated = true;
  18742. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18743. if (this._postMultiplyPivotMatrix) {
  18744. if (!this._pivotMatrixInverse) {
  18745. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18746. }
  18747. else {
  18748. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18749. }
  18750. }
  18751. return this;
  18752. };
  18753. /**
  18754. * Returns the mesh pivot matrix.
  18755. * Default : Identity.
  18756. * A Matrix is returned.
  18757. */
  18758. TransformNode.prototype.getPivotMatrix = function () {
  18759. return this._pivotMatrix;
  18760. };
  18761. /**
  18762. * Prevents the World matrix to be computed any longer.
  18763. * Returns the TransformNode.
  18764. */
  18765. TransformNode.prototype.freezeWorldMatrix = function () {
  18766. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18767. this.computeWorldMatrix(true);
  18768. this._isWorldMatrixFrozen = true;
  18769. return this;
  18770. };
  18771. /**
  18772. * Allows back the World matrix computation.
  18773. * Returns the TransformNode.
  18774. */
  18775. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18776. this._isWorldMatrixFrozen = false;
  18777. this.computeWorldMatrix(true);
  18778. return this;
  18779. };
  18780. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18781. /**
  18782. * True if the World matrix has been frozen.
  18783. * Returns a boolean.
  18784. */
  18785. get: function () {
  18786. return this._isWorldMatrixFrozen;
  18787. },
  18788. enumerable: true,
  18789. configurable: true
  18790. });
  18791. /**
  18792. * Retuns the mesh absolute position in the World.
  18793. * Returns a Vector3.
  18794. */
  18795. TransformNode.prototype.getAbsolutePosition = function () {
  18796. this.computeWorldMatrix();
  18797. return this._absolutePosition;
  18798. };
  18799. /**
  18800. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18801. * Returns the TransformNode.
  18802. */
  18803. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18804. if (!absolutePosition) {
  18805. return this;
  18806. }
  18807. var absolutePositionX;
  18808. var absolutePositionY;
  18809. var absolutePositionZ;
  18810. if (absolutePosition.x === undefined) {
  18811. if (arguments.length < 3) {
  18812. return this;
  18813. }
  18814. absolutePositionX = arguments[0];
  18815. absolutePositionY = arguments[1];
  18816. absolutePositionZ = arguments[2];
  18817. }
  18818. else {
  18819. absolutePositionX = absolutePosition.x;
  18820. absolutePositionY = absolutePosition.y;
  18821. absolutePositionZ = absolutePosition.z;
  18822. }
  18823. if (this.parent) {
  18824. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18825. invertParentWorldMatrix.invert();
  18826. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18827. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18828. }
  18829. else {
  18830. this.position.x = absolutePositionX;
  18831. this.position.y = absolutePositionY;
  18832. this.position.z = absolutePositionZ;
  18833. }
  18834. return this;
  18835. };
  18836. /**
  18837. * Sets the mesh position in its local space.
  18838. * Returns the TransformNode.
  18839. */
  18840. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18841. this.computeWorldMatrix();
  18842. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18843. return this;
  18844. };
  18845. /**
  18846. * Returns the mesh position in the local space from the current World matrix values.
  18847. * Returns a new Vector3.
  18848. */
  18849. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18850. this.computeWorldMatrix();
  18851. var invLocalWorldMatrix = this._localWorld.clone();
  18852. invLocalWorldMatrix.invert();
  18853. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18854. };
  18855. /**
  18856. * Translates the mesh along the passed Vector3 in its local space.
  18857. * Returns the TransformNode.
  18858. */
  18859. TransformNode.prototype.locallyTranslate = function (vector3) {
  18860. this.computeWorldMatrix(true);
  18861. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18862. return this;
  18863. };
  18864. /**
  18865. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18866. * @param targetPoint the position (must be in same space as current mesh) to look at
  18867. * @param yawCor optional yaw (y-axis) correction in radians
  18868. * @param pitchCor optional pitch (x-axis) correction in radians
  18869. * @param rollCor optional roll (z-axis) correction in radians
  18870. * @param space the choosen space of the target
  18871. * @returns the TransformNode.
  18872. */
  18873. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18874. if (yawCor === void 0) { yawCor = 0; }
  18875. if (pitchCor === void 0) { pitchCor = 0; }
  18876. if (rollCor === void 0) { rollCor = 0; }
  18877. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18878. var dv = TransformNode._lookAtVectorCache;
  18879. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18880. targetPoint.subtractToRef(pos, dv);
  18881. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18882. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18883. var pitch = Math.atan2(dv.y, len);
  18884. if (this.rotationQuaternion) {
  18885. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18886. }
  18887. else {
  18888. this.rotation.x = pitch + pitchCor;
  18889. this.rotation.y = yaw + yawCor;
  18890. this.rotation.z = rollCor;
  18891. }
  18892. return this;
  18893. };
  18894. /**
  18895. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18896. * This Vector3 is expressed in the World space.
  18897. */
  18898. TransformNode.prototype.getDirection = function (localAxis) {
  18899. var result = BABYLON.Vector3.Zero();
  18900. this.getDirectionToRef(localAxis, result);
  18901. return result;
  18902. };
  18903. /**
  18904. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18905. * localAxis is expressed in the mesh local space.
  18906. * result is computed in the Wordl space from the mesh World matrix.
  18907. * Returns the TransformNode.
  18908. */
  18909. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18910. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18911. return this;
  18912. };
  18913. /**
  18914. * Sets a new pivot point to the current node
  18915. * @param point defines the new pivot point to use
  18916. * @param space defines if the point is in world or local space (local by default)
  18917. * @returns the current TransformNode
  18918. */
  18919. TransformNode.prototype.setPivotPoint = function (point, space) {
  18920. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18921. if (this.getScene().getRenderId() == 0) {
  18922. this.computeWorldMatrix(true);
  18923. }
  18924. var wm = this.getWorldMatrix();
  18925. if (space == BABYLON.Space.WORLD) {
  18926. var tmat = BABYLON.Tmp.Matrix[0];
  18927. wm.invertToRef(tmat);
  18928. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18929. }
  18930. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18931. };
  18932. /**
  18933. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18934. */
  18935. TransformNode.prototype.getPivotPoint = function () {
  18936. var point = BABYLON.Vector3.Zero();
  18937. this.getPivotPointToRef(point);
  18938. return point;
  18939. };
  18940. /**
  18941. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18942. * Returns the TransformNode.
  18943. */
  18944. TransformNode.prototype.getPivotPointToRef = function (result) {
  18945. result.x = -this._pivotMatrix.m[12];
  18946. result.y = -this._pivotMatrix.m[13];
  18947. result.z = -this._pivotMatrix.m[14];
  18948. return this;
  18949. };
  18950. /**
  18951. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18952. */
  18953. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18954. var point = BABYLON.Vector3.Zero();
  18955. this.getAbsolutePivotPointToRef(point);
  18956. return point;
  18957. };
  18958. /**
  18959. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18960. * Returns the TransformNode.
  18961. */
  18962. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18963. result.x = this._pivotMatrix.m[12];
  18964. result.y = this._pivotMatrix.m[13];
  18965. result.z = this._pivotMatrix.m[14];
  18966. this.getPivotPointToRef(result);
  18967. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18968. return this;
  18969. };
  18970. /**
  18971. * Defines the passed node as the parent of the current node.
  18972. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18973. * Returns the TransformNode.
  18974. */
  18975. TransformNode.prototype.setParent = function (node) {
  18976. if (!node && !this.parent) {
  18977. return this;
  18978. }
  18979. if (!node) {
  18980. var rotation = BABYLON.Tmp.Quaternion[0];
  18981. var position = BABYLON.Tmp.Vector3[0];
  18982. var scale = BABYLON.Tmp.Vector3[1];
  18983. if (this.parent && this.parent.computeWorldMatrix) {
  18984. this.parent.computeWorldMatrix(true);
  18985. }
  18986. this.computeWorldMatrix(true);
  18987. this.getWorldMatrix().decompose(scale, rotation, position);
  18988. if (this.rotationQuaternion) {
  18989. this.rotationQuaternion.copyFrom(rotation);
  18990. }
  18991. else {
  18992. rotation.toEulerAnglesToRef(this.rotation);
  18993. }
  18994. this.scaling.x = scale.x;
  18995. this.scaling.y = scale.y;
  18996. this.scaling.z = scale.z;
  18997. this.position.x = position.x;
  18998. this.position.y = position.y;
  18999. this.position.z = position.z;
  19000. }
  19001. else {
  19002. var rotation = BABYLON.Tmp.Quaternion[0];
  19003. var position = BABYLON.Tmp.Vector3[0];
  19004. var scale = BABYLON.Tmp.Vector3[1];
  19005. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19006. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19007. this.computeWorldMatrix(true);
  19008. node.computeWorldMatrix(true);
  19009. node.getWorldMatrix().invertToRef(invParentMatrix);
  19010. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19011. diffMatrix.decompose(scale, rotation, position);
  19012. if (this.rotationQuaternion) {
  19013. this.rotationQuaternion.copyFrom(rotation);
  19014. }
  19015. else {
  19016. rotation.toEulerAnglesToRef(this.rotation);
  19017. }
  19018. this.position.x = position.x;
  19019. this.position.y = position.y;
  19020. this.position.z = position.z;
  19021. this.scaling.x = scale.x;
  19022. this.scaling.y = scale.y;
  19023. this.scaling.z = scale.z;
  19024. }
  19025. this.parent = node;
  19026. return this;
  19027. };
  19028. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19029. get: function () {
  19030. return this._nonUniformScaling;
  19031. },
  19032. enumerable: true,
  19033. configurable: true
  19034. });
  19035. /** @hidden */
  19036. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19037. if (this._nonUniformScaling === value) {
  19038. return false;
  19039. }
  19040. this._nonUniformScaling = value;
  19041. return true;
  19042. };
  19043. /**
  19044. * Attach the current TransformNode to another TransformNode associated with a bone
  19045. * @param bone Bone affecting the TransformNode
  19046. * @param affectedTransformNode TransformNode associated with the bone
  19047. */
  19048. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19049. this._transformToBoneReferal = affectedTransformNode;
  19050. this.parent = bone;
  19051. if (bone.getWorldMatrix().determinant() < 0) {
  19052. this.scalingDeterminant *= -1;
  19053. }
  19054. return this;
  19055. };
  19056. TransformNode.prototype.detachFromBone = function () {
  19057. if (!this.parent) {
  19058. return this;
  19059. }
  19060. if (this.parent.getWorldMatrix().determinant() < 0) {
  19061. this.scalingDeterminant *= -1;
  19062. }
  19063. this._transformToBoneReferal = null;
  19064. this.parent = null;
  19065. return this;
  19066. };
  19067. /**
  19068. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19069. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19070. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19071. * The passed axis is also normalized.
  19072. * Returns the TransformNode.
  19073. */
  19074. TransformNode.prototype.rotate = function (axis, amount, space) {
  19075. axis.normalize();
  19076. if (!this.rotationQuaternion) {
  19077. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19078. this.rotation = BABYLON.Vector3.Zero();
  19079. }
  19080. var rotationQuaternion;
  19081. if (!space || space === BABYLON.Space.LOCAL) {
  19082. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19083. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19084. }
  19085. else {
  19086. if (this.parent) {
  19087. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19088. invertParentWorldMatrix.invert();
  19089. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19090. }
  19091. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19092. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19093. }
  19094. return this;
  19095. };
  19096. /**
  19097. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19098. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19099. * The passed axis is also normalized.
  19100. * Returns the TransformNode.
  19101. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19102. */
  19103. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19104. axis.normalize();
  19105. if (!this.rotationQuaternion) {
  19106. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19107. this.rotation.copyFromFloats(0, 0, 0);
  19108. }
  19109. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19110. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19111. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19112. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19113. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19114. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19115. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19116. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19117. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19118. return this;
  19119. };
  19120. /**
  19121. * Translates the mesh along the axis vector for the passed distance in the given space.
  19122. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19123. * Returns the TransformNode.
  19124. */
  19125. TransformNode.prototype.translate = function (axis, distance, space) {
  19126. var displacementVector = axis.scale(distance);
  19127. if (!space || space === BABYLON.Space.LOCAL) {
  19128. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19129. this.setPositionWithLocalVector(tempV3);
  19130. }
  19131. else {
  19132. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19133. }
  19134. return this;
  19135. };
  19136. /**
  19137. * Adds a rotation step to the mesh current rotation.
  19138. * x, y, z are Euler angles expressed in radians.
  19139. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19140. * This means this rotation is made in the mesh local space only.
  19141. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19142. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19143. * ```javascript
  19144. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19145. * ```
  19146. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19147. * 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.
  19148. * Returns the TransformNode.
  19149. */
  19150. TransformNode.prototype.addRotation = function (x, y, z) {
  19151. var rotationQuaternion;
  19152. if (this.rotationQuaternion) {
  19153. rotationQuaternion = this.rotationQuaternion;
  19154. }
  19155. else {
  19156. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19157. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19158. }
  19159. var accumulation = BABYLON.Tmp.Quaternion[0];
  19160. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19161. rotationQuaternion.multiplyInPlace(accumulation);
  19162. if (!this.rotationQuaternion) {
  19163. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19164. }
  19165. return this;
  19166. };
  19167. /**
  19168. * Computes the mesh World matrix and returns it.
  19169. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19170. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19171. * If the parameter `force`is set to `true`, the actual computation is done.
  19172. * Returns the mesh World Matrix.
  19173. */
  19174. TransformNode.prototype.computeWorldMatrix = function (force) {
  19175. if (this._isWorldMatrixFrozen) {
  19176. return this._worldMatrix;
  19177. }
  19178. if (!force && this.isSynchronized(true)) {
  19179. this._currentRenderId = this.getScene().getRenderId();
  19180. return this._worldMatrix;
  19181. }
  19182. this._cache.position.copyFrom(this.position);
  19183. this._cache.scaling.copyFrom(this.scaling);
  19184. this._cache.pivotMatrixUpdated = false;
  19185. this._cache.billboardMode = this.billboardMode;
  19186. this._currentRenderId = this.getScene().getRenderId();
  19187. this._childRenderId = this.getScene().getRenderId();
  19188. this._isDirty = false;
  19189. // Scaling
  19190. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19191. // Rotation
  19192. //rotate, if quaternion is set and rotation was used
  19193. if (this.rotationQuaternion) {
  19194. var len = this.rotation.length();
  19195. if (len) {
  19196. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19197. this.rotation.copyFromFloats(0, 0, 0);
  19198. }
  19199. }
  19200. if (this.rotationQuaternion) {
  19201. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19202. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19203. }
  19204. else {
  19205. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19206. this._cache.rotation.copyFrom(this.rotation);
  19207. }
  19208. // Translation
  19209. var camera = this.getScene().activeCamera;
  19210. if (this.infiniteDistance && !this.parent && camera) {
  19211. var cameraWorldMatrix = camera.getWorldMatrix();
  19212. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19213. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19214. }
  19215. else {
  19216. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19217. }
  19218. // Composing transformations
  19219. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19220. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19221. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19222. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19223. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19224. // Need to decompose each rotation here
  19225. var currentPosition = BABYLON.Tmp.Vector3[3];
  19226. if (this.parent && this.parent.getWorldMatrix) {
  19227. if (this._transformToBoneReferal) {
  19228. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19229. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19230. }
  19231. else {
  19232. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19233. }
  19234. }
  19235. else {
  19236. currentPosition.copyFrom(this.position);
  19237. }
  19238. currentPosition.subtractInPlace(camera.globalPosition);
  19239. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19240. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19241. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19242. }
  19243. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19244. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19245. }
  19246. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19247. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19248. }
  19249. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19250. }
  19251. else {
  19252. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19253. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19254. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19255. }
  19256. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19257. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19258. }
  19259. // Post multiply inverse of pivotMatrix
  19260. if (this._postMultiplyPivotMatrix) {
  19261. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  19262. }
  19263. // Local world
  19264. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19265. // Parent
  19266. if (this.parent && this.parent.getWorldMatrix) {
  19267. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19268. if (this._transformToBoneReferal) {
  19269. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19270. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19271. }
  19272. else {
  19273. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19274. }
  19275. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19276. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19277. this._worldMatrix.copyFrom(this._localWorld);
  19278. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19279. }
  19280. else {
  19281. if (this._transformToBoneReferal) {
  19282. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19283. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19284. }
  19285. else {
  19286. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19287. }
  19288. }
  19289. this._markSyncedWithParent();
  19290. }
  19291. else {
  19292. this._worldMatrix.copyFrom(this._localWorld);
  19293. }
  19294. // Normal matrix
  19295. if (!this.ignoreNonUniformScaling) {
  19296. if (this.scaling.isNonUniform) {
  19297. this._updateNonUniformScalingState(true);
  19298. }
  19299. else if (this.parent && this.parent._nonUniformScaling) {
  19300. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19301. }
  19302. else {
  19303. this._updateNonUniformScalingState(false);
  19304. }
  19305. }
  19306. else {
  19307. this._updateNonUniformScalingState(false);
  19308. }
  19309. this._afterComputeWorldMatrix();
  19310. // Absolute position
  19311. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19312. // Callbacks
  19313. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19314. if (!this._poseMatrix) {
  19315. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19316. }
  19317. // Cache the determinant
  19318. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19319. return this._worldMatrix;
  19320. };
  19321. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19322. };
  19323. /**
  19324. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19325. * @param func: callback function to add
  19326. *
  19327. * Returns the TransformNode.
  19328. */
  19329. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19330. this.onAfterWorldMatrixUpdateObservable.add(func);
  19331. return this;
  19332. };
  19333. /**
  19334. * Removes a registered callback function.
  19335. * Returns the TransformNode.
  19336. */
  19337. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19338. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19339. return this;
  19340. };
  19341. /**
  19342. * Clone the current transform node
  19343. * Returns the new transform node
  19344. * @param name Name of the new clone
  19345. * @param newParent New parent for the clone
  19346. * @param doNotCloneChildren Do not clone children hierarchy
  19347. */
  19348. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19349. var _this = this;
  19350. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19351. result.name = name;
  19352. result.id = name;
  19353. if (newParent) {
  19354. result.parent = newParent;
  19355. }
  19356. if (!doNotCloneChildren) {
  19357. // Children
  19358. var directDescendants = this.getDescendants(true);
  19359. for (var index = 0; index < directDescendants.length; index++) {
  19360. var child = directDescendants[index];
  19361. if (child.clone) {
  19362. child.clone(name + "." + child.name, result);
  19363. }
  19364. }
  19365. }
  19366. return result;
  19367. };
  19368. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19369. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19370. serializationObject.type = this.getClassName();
  19371. // Parent
  19372. if (this.parent) {
  19373. serializationObject.parentId = this.parent.id;
  19374. }
  19375. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19376. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19377. }
  19378. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19379. serializationObject.isEnabled = this.isEnabled();
  19380. // Parent
  19381. if (this.parent) {
  19382. serializationObject.parentId = this.parent.id;
  19383. }
  19384. return serializationObject;
  19385. };
  19386. // Statics
  19387. /**
  19388. * Returns a new TransformNode object parsed from the source provided.
  19389. * The parameter `parsedMesh` is the source.
  19390. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19391. */
  19392. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19393. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19394. if (BABYLON.Tags) {
  19395. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19396. }
  19397. if (parsedTransformNode.localMatrix) {
  19398. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19399. }
  19400. else if (parsedTransformNode.pivotMatrix) {
  19401. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19402. }
  19403. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19404. // Parent
  19405. if (parsedTransformNode.parentId) {
  19406. transformNode._waitingParentId = parsedTransformNode.parentId;
  19407. }
  19408. return transformNode;
  19409. };
  19410. /**
  19411. * Releases resources associated with this transform node.
  19412. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19413. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19414. */
  19415. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19416. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19417. // Animations
  19418. this.getScene().stopAnimation(this);
  19419. // Remove from scene
  19420. this.getScene().removeTransformNode(this);
  19421. this.onAfterWorldMatrixUpdateObservable.clear();
  19422. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19423. };
  19424. // Statics
  19425. TransformNode.BILLBOARDMODE_NONE = 0;
  19426. TransformNode.BILLBOARDMODE_X = 1;
  19427. TransformNode.BILLBOARDMODE_Y = 2;
  19428. TransformNode.BILLBOARDMODE_Z = 4;
  19429. TransformNode.BILLBOARDMODE_ALL = 7;
  19430. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19431. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19432. __decorate([
  19433. BABYLON.serializeAsVector3()
  19434. ], TransformNode.prototype, "_rotation", void 0);
  19435. __decorate([
  19436. BABYLON.serializeAsQuaternion()
  19437. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19438. __decorate([
  19439. BABYLON.serializeAsVector3()
  19440. ], TransformNode.prototype, "_scaling", void 0);
  19441. __decorate([
  19442. BABYLON.serialize()
  19443. ], TransformNode.prototype, "billboardMode", void 0);
  19444. __decorate([
  19445. BABYLON.serialize()
  19446. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19447. __decorate([
  19448. BABYLON.serialize()
  19449. ], TransformNode.prototype, "infiniteDistance", void 0);
  19450. __decorate([
  19451. BABYLON.serialize()
  19452. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19453. __decorate([
  19454. BABYLON.serializeAsVector3()
  19455. ], TransformNode.prototype, "position", void 0);
  19456. return TransformNode;
  19457. }(BABYLON.Node));
  19458. BABYLON.TransformNode = TransformNode;
  19459. })(BABYLON || (BABYLON = {}));
  19460. //# sourceMappingURL=babylon.transformNode.js.map
  19461. var BABYLON;
  19462. (function (BABYLON) {
  19463. /**
  19464. * Class used to store all common mesh properties
  19465. */
  19466. var AbstractMesh = /** @class */ (function (_super) {
  19467. __extends(AbstractMesh, _super);
  19468. // Constructor
  19469. /**
  19470. * Creates a new AbstractMesh
  19471. * @param name defines the name of the mesh
  19472. * @param scene defines the hosting scene
  19473. */
  19474. function AbstractMesh(name, scene) {
  19475. if (scene === void 0) { scene = null; }
  19476. var _this = _super.call(this, name, scene, false) || this;
  19477. _this._facetNb = 0; // facet number
  19478. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19479. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19480. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19481. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19482. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19483. _this._subDiv = {
  19484. max: 1,
  19485. X: 1,
  19486. Y: 1,
  19487. Z: 1
  19488. };
  19489. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19490. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19491. /** Gets ot sets the culling strategy to use to find visible meshes */
  19492. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  19493. // Events
  19494. /**
  19495. * An event triggered when this mesh collides with another one
  19496. */
  19497. _this.onCollideObservable = new BABYLON.Observable();
  19498. /**
  19499. * An event triggered when the collision's position changes
  19500. */
  19501. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19502. /**
  19503. * An event triggered when material is changed
  19504. */
  19505. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19506. // Properties
  19507. /**
  19508. * Gets or sets the orientation for POV movement & rotation
  19509. */
  19510. _this.definedFacingForward = true;
  19511. /**
  19512. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19513. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19514. * * 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.
  19515. * @see http://doc.babylonjs.com/features/occlusionquery
  19516. */
  19517. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19518. /**
  19519. * 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:
  19520. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19521. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19522. * * 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.
  19523. * @see http://doc.babylonjs.com/features/occlusionquery
  19524. */
  19525. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19526. /**
  19527. * 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.
  19528. * The default value is -1 which means don't break the query and wait till the result
  19529. * @see http://doc.babylonjs.com/features/occlusionquery
  19530. */
  19531. _this.occlusionRetryCount = -1;
  19532. /** @hidden */
  19533. _this._occlusionInternalRetryCounter = 0;
  19534. /** @hidden */
  19535. _this._isOccluded = false;
  19536. /** @hidden */
  19537. _this._isOcclusionQueryInProgress = false;
  19538. _this._visibility = 1.0;
  19539. /** Gets or sets the alpha index used to sort transparent meshes
  19540. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19541. */
  19542. _this.alphaIndex = Number.MAX_VALUE;
  19543. /**
  19544. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19545. */
  19546. _this.isVisible = true;
  19547. /**
  19548. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19549. */
  19550. _this.isPickable = true;
  19551. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19552. _this.showSubMeshesBoundingBox = false;
  19553. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19554. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19555. */
  19556. _this.isBlocker = false;
  19557. /**
  19558. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19559. */
  19560. _this.enablePointerMoveEvents = false;
  19561. /**
  19562. * Specifies the rendering group id for this mesh (0 by default)
  19563. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19564. */
  19565. _this.renderingGroupId = 0;
  19566. _this._receiveShadows = false;
  19567. /**
  19568. * Gets or sets a boolean indicating if the outline must be rendered as well
  19569. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19570. */
  19571. _this.renderOutline = false;
  19572. /** Defines color to use when rendering outline */
  19573. _this.outlineColor = BABYLON.Color3.Red();
  19574. /** Define width to use when rendering outline */
  19575. _this.outlineWidth = 0.02;
  19576. /**
  19577. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19578. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19579. */
  19580. _this.renderOverlay = false;
  19581. /** Defines color to use when rendering overlay */
  19582. _this.overlayColor = BABYLON.Color3.Red();
  19583. /** Defines alpha to use when rendering overlay */
  19584. _this.overlayAlpha = 0.5;
  19585. _this._hasVertexAlpha = false;
  19586. _this._useVertexColors = true;
  19587. _this._computeBonesUsingShaders = true;
  19588. _this._numBoneInfluencers = 4;
  19589. _this._applyFog = true;
  19590. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19591. _this.useOctreeForRenderingSelection = true;
  19592. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19593. _this.useOctreeForPicking = true;
  19594. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19595. _this.useOctreeForCollisions = true;
  19596. _this._layerMask = 0x0FFFFFFF;
  19597. /**
  19598. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19599. */
  19600. _this.alwaysSelectAsActiveMesh = false;
  19601. /**
  19602. * Gets or sets the current action manager
  19603. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19604. */
  19605. _this.actionManager = null;
  19606. /**
  19607. * Gets or sets impostor used for physic simulation
  19608. * @see http://doc.babylonjs.com/features/physics_engine
  19609. */
  19610. _this.physicsImpostor = null;
  19611. // Collisions
  19612. _this._checkCollisions = false;
  19613. _this._collisionMask = -1;
  19614. _this._collisionGroup = -1;
  19615. /**
  19616. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19617. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19618. */
  19619. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19620. /**
  19621. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19622. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19623. */
  19624. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19625. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19626. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19627. // Edges
  19628. /**
  19629. * Defines edge width used when edgesRenderer is enabled
  19630. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19631. */
  19632. _this.edgesWidth = 1;
  19633. /**
  19634. * Defines edge color used when edgesRenderer is enabled
  19635. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19636. */
  19637. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19638. // Cache
  19639. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19640. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19641. /** @hidden */
  19642. _this._renderId = 0;
  19643. /** @hidden */
  19644. _this._intersectionsInProgress = new Array();
  19645. /** @hidden */
  19646. _this._unIndexed = false;
  19647. /** @hidden */
  19648. _this._lightSources = new Array();
  19649. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19650. if (collidedMesh === void 0) { collidedMesh = null; }
  19651. //TODO move this to the collision coordinator!
  19652. if (_this.getScene().workerCollisions)
  19653. newPosition.multiplyInPlace(_this._collider._radius);
  19654. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19655. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19656. _this.position.addInPlace(_this._diffPositionForCollisions);
  19657. }
  19658. if (collidedMesh) {
  19659. _this.onCollideObservable.notifyObservers(collidedMesh);
  19660. }
  19661. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19662. };
  19663. _this.getScene().addMesh(_this);
  19664. _this._resyncLightSources();
  19665. return _this;
  19666. }
  19667. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19668. /**
  19669. * No billboard
  19670. */
  19671. get: function () {
  19672. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19673. },
  19674. enumerable: true,
  19675. configurable: true
  19676. });
  19677. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19678. /** Billboard on X axis */
  19679. get: function () {
  19680. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19681. },
  19682. enumerable: true,
  19683. configurable: true
  19684. });
  19685. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19686. /** Billboard on Y axis */
  19687. get: function () {
  19688. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19689. },
  19690. enumerable: true,
  19691. configurable: true
  19692. });
  19693. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19694. /** Billboard on Z axis */
  19695. get: function () {
  19696. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19697. },
  19698. enumerable: true,
  19699. configurable: true
  19700. });
  19701. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19702. /** Billboard on all axes */
  19703. get: function () {
  19704. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19705. },
  19706. enumerable: true,
  19707. configurable: true
  19708. });
  19709. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19710. /**
  19711. * Gets the number of facets in the mesh
  19712. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19713. */
  19714. get: function () {
  19715. return this._facetNb;
  19716. },
  19717. enumerable: true,
  19718. configurable: true
  19719. });
  19720. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19721. /**
  19722. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19723. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19724. */
  19725. get: function () {
  19726. return this._partitioningSubdivisions;
  19727. },
  19728. set: function (nb) {
  19729. this._partitioningSubdivisions = nb;
  19730. },
  19731. enumerable: true,
  19732. configurable: true
  19733. });
  19734. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19735. /**
  19736. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19737. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19738. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19739. */
  19740. get: function () {
  19741. return this._partitioningBBoxRatio;
  19742. },
  19743. set: function (ratio) {
  19744. this._partitioningBBoxRatio = ratio;
  19745. },
  19746. enumerable: true,
  19747. configurable: true
  19748. });
  19749. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19750. /**
  19751. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19752. * Works only for updatable meshes.
  19753. * Doesn't work with multi-materials
  19754. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19755. */
  19756. get: function () {
  19757. return this._facetDepthSort;
  19758. },
  19759. set: function (sort) {
  19760. this._facetDepthSort = sort;
  19761. },
  19762. enumerable: true,
  19763. configurable: true
  19764. });
  19765. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19766. /**
  19767. * The location (Vector3) where the facet depth sort must be computed from.
  19768. * By default, the active camera position.
  19769. * Used only when facet depth sort is enabled
  19770. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19771. */
  19772. get: function () {
  19773. return this._facetDepthSortFrom;
  19774. },
  19775. set: function (location) {
  19776. this._facetDepthSortFrom = location;
  19777. },
  19778. enumerable: true,
  19779. configurable: true
  19780. });
  19781. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19782. /**
  19783. * gets a boolean indicating if facetData is enabled
  19784. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19785. */
  19786. get: function () {
  19787. return this._facetDataEnabled;
  19788. },
  19789. enumerable: true,
  19790. configurable: true
  19791. });
  19792. /** @hidden */
  19793. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19794. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19795. return false;
  19796. }
  19797. this._markSubMeshesAsMiscDirty();
  19798. return true;
  19799. };
  19800. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19801. /** Set a function to call when this mesh collides with another one */
  19802. set: function (callback) {
  19803. if (this._onCollideObserver) {
  19804. this.onCollideObservable.remove(this._onCollideObserver);
  19805. }
  19806. this._onCollideObserver = this.onCollideObservable.add(callback);
  19807. },
  19808. enumerable: true,
  19809. configurable: true
  19810. });
  19811. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19812. /** Set a function to call when the collision's position changes */
  19813. set: function (callback) {
  19814. if (this._onCollisionPositionChangeObserver) {
  19815. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19816. }
  19817. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19818. },
  19819. enumerable: true,
  19820. configurable: true
  19821. });
  19822. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19823. /**
  19824. * 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
  19825. * @see http://doc.babylonjs.com/features/occlusionquery
  19826. */
  19827. get: function () {
  19828. return this._isOccluded;
  19829. },
  19830. set: function (value) {
  19831. this._isOccluded = value;
  19832. },
  19833. enumerable: true,
  19834. configurable: true
  19835. });
  19836. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19837. /**
  19838. * Flag to check the progress status of the query
  19839. * @see http://doc.babylonjs.com/features/occlusionquery
  19840. */
  19841. get: function () {
  19842. return this._isOcclusionQueryInProgress;
  19843. },
  19844. enumerable: true,
  19845. configurable: true
  19846. });
  19847. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19848. /**
  19849. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19850. */
  19851. get: function () {
  19852. return this._visibility;
  19853. },
  19854. /**
  19855. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19856. */
  19857. set: function (value) {
  19858. if (this._visibility === value) {
  19859. return;
  19860. }
  19861. this._visibility = value;
  19862. this._markSubMeshesAsMiscDirty();
  19863. },
  19864. enumerable: true,
  19865. configurable: true
  19866. });
  19867. Object.defineProperty(AbstractMesh.prototype, "material", {
  19868. /** Gets or sets current material */
  19869. get: function () {
  19870. return this._material;
  19871. },
  19872. set: function (value) {
  19873. if (this._material === value) {
  19874. return;
  19875. }
  19876. this._material = value;
  19877. if (this.onMaterialChangedObservable.hasObservers) {
  19878. this.onMaterialChangedObservable.notifyObservers(this);
  19879. }
  19880. if (!this.subMeshes) {
  19881. return;
  19882. }
  19883. this._unBindEffect();
  19884. },
  19885. enumerable: true,
  19886. configurable: true
  19887. });
  19888. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19889. /**
  19890. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19891. * @see http://doc.babylonjs.com/babylon101/shadows
  19892. */
  19893. get: function () {
  19894. return this._receiveShadows;
  19895. },
  19896. set: function (value) {
  19897. if (this._receiveShadows === value) {
  19898. return;
  19899. }
  19900. this._receiveShadows = value;
  19901. this._markSubMeshesAsLightDirty();
  19902. },
  19903. enumerable: true,
  19904. configurable: true
  19905. });
  19906. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19907. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19908. get: function () {
  19909. return this._hasVertexAlpha;
  19910. },
  19911. set: function (value) {
  19912. if (this._hasVertexAlpha === value) {
  19913. return;
  19914. }
  19915. this._hasVertexAlpha = value;
  19916. this._markSubMeshesAsAttributesDirty();
  19917. this._markSubMeshesAsMiscDirty();
  19918. },
  19919. enumerable: true,
  19920. configurable: true
  19921. });
  19922. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19923. /** 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) */
  19924. get: function () {
  19925. return this._useVertexColors;
  19926. },
  19927. set: function (value) {
  19928. if (this._useVertexColors === value) {
  19929. return;
  19930. }
  19931. this._useVertexColors = value;
  19932. this._markSubMeshesAsAttributesDirty();
  19933. },
  19934. enumerable: true,
  19935. configurable: true
  19936. });
  19937. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19938. /**
  19939. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19940. */
  19941. get: function () {
  19942. return this._computeBonesUsingShaders;
  19943. },
  19944. set: function (value) {
  19945. if (this._computeBonesUsingShaders === value) {
  19946. return;
  19947. }
  19948. this._computeBonesUsingShaders = value;
  19949. this._markSubMeshesAsAttributesDirty();
  19950. },
  19951. enumerable: true,
  19952. configurable: true
  19953. });
  19954. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19955. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19956. get: function () {
  19957. return this._numBoneInfluencers;
  19958. },
  19959. set: function (value) {
  19960. if (this._numBoneInfluencers === value) {
  19961. return;
  19962. }
  19963. this._numBoneInfluencers = value;
  19964. this._markSubMeshesAsAttributesDirty();
  19965. },
  19966. enumerable: true,
  19967. configurable: true
  19968. });
  19969. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19970. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19971. get: function () {
  19972. return this._applyFog;
  19973. },
  19974. set: function (value) {
  19975. if (this._applyFog === value) {
  19976. return;
  19977. }
  19978. this._applyFog = value;
  19979. this._markSubMeshesAsMiscDirty();
  19980. },
  19981. enumerable: true,
  19982. configurable: true
  19983. });
  19984. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19985. /**
  19986. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19987. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19988. */
  19989. get: function () {
  19990. return this._layerMask;
  19991. },
  19992. set: function (value) {
  19993. if (value === this._layerMask) {
  19994. return;
  19995. }
  19996. this._layerMask = value;
  19997. this._resyncLightSources();
  19998. },
  19999. enumerable: true,
  20000. configurable: true
  20001. });
  20002. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20003. /**
  20004. * Gets or sets a collision mask used to mask collisions (default is -1).
  20005. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20006. */
  20007. get: function () {
  20008. return this._collisionMask;
  20009. },
  20010. set: function (mask) {
  20011. this._collisionMask = !isNaN(mask) ? mask : -1;
  20012. },
  20013. enumerable: true,
  20014. configurable: true
  20015. });
  20016. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20017. /**
  20018. * Gets or sets the current collision group mask (-1 by default).
  20019. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20020. */
  20021. get: function () {
  20022. return this._collisionGroup;
  20023. },
  20024. set: function (mask) {
  20025. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20026. },
  20027. enumerable: true,
  20028. configurable: true
  20029. });
  20030. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20031. /** @hidden */
  20032. get: function () {
  20033. return null;
  20034. },
  20035. enumerable: true,
  20036. configurable: true
  20037. });
  20038. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20039. get: function () {
  20040. return this._skeleton;
  20041. },
  20042. /**
  20043. * Gets or sets a skeleton to apply skining transformations
  20044. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20045. */
  20046. set: function (value) {
  20047. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20048. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20049. }
  20050. if (value && value.needInitialSkinMatrix) {
  20051. value._registerMeshWithPoseMatrix(this);
  20052. }
  20053. this._skeleton = value;
  20054. if (!this._skeleton) {
  20055. this._bonesTransformMatrices = null;
  20056. }
  20057. this._markSubMeshesAsAttributesDirty();
  20058. },
  20059. enumerable: true,
  20060. configurable: true
  20061. });
  20062. /**
  20063. * Returns the string "AbstractMesh"
  20064. * @returns "AbstractMesh"
  20065. */
  20066. AbstractMesh.prototype.getClassName = function () {
  20067. return "AbstractMesh";
  20068. };
  20069. /**
  20070. * Gets a string representation of the current mesh
  20071. * @param fullDetails defines a boolean indicating if full details must be included
  20072. * @returns a string representation of the current mesh
  20073. */
  20074. AbstractMesh.prototype.toString = function (fullDetails) {
  20075. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20076. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20077. if (this._skeleton) {
  20078. ret += ", skeleton: " + this._skeleton.name;
  20079. }
  20080. if (fullDetails) {
  20081. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20082. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20083. }
  20084. return ret;
  20085. };
  20086. /** @hidden */
  20087. AbstractMesh.prototype._rebuild = function () {
  20088. if (this._occlusionQuery) {
  20089. this._occlusionQuery = null;
  20090. }
  20091. if (this._edgesRenderer) {
  20092. this._edgesRenderer._rebuild();
  20093. }
  20094. if (!this.subMeshes) {
  20095. return;
  20096. }
  20097. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20098. var subMesh = _a[_i];
  20099. subMesh._rebuild();
  20100. }
  20101. };
  20102. /** @hidden */
  20103. AbstractMesh.prototype._resyncLightSources = function () {
  20104. this._lightSources.length = 0;
  20105. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20106. var light = _a[_i];
  20107. if (!light.isEnabled()) {
  20108. continue;
  20109. }
  20110. if (light.canAffectMesh(this)) {
  20111. this._lightSources.push(light);
  20112. }
  20113. }
  20114. this._markSubMeshesAsLightDirty();
  20115. };
  20116. /** @hidden */
  20117. AbstractMesh.prototype._resyncLighSource = function (light) {
  20118. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20119. var index = this._lightSources.indexOf(light);
  20120. if (index === -1) {
  20121. if (!isIn) {
  20122. return;
  20123. }
  20124. this._lightSources.push(light);
  20125. }
  20126. else {
  20127. if (isIn) {
  20128. return;
  20129. }
  20130. this._lightSources.splice(index, 1);
  20131. }
  20132. this._markSubMeshesAsLightDirty();
  20133. };
  20134. /** @hidden */
  20135. AbstractMesh.prototype._unBindEffect = function () {
  20136. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20137. var subMesh = _a[_i];
  20138. subMesh.setEffect(null);
  20139. }
  20140. };
  20141. /** @hidden */
  20142. AbstractMesh.prototype._removeLightSource = function (light) {
  20143. var index = this._lightSources.indexOf(light);
  20144. if (index === -1) {
  20145. return;
  20146. }
  20147. this._lightSources.splice(index, 1);
  20148. this._markSubMeshesAsLightDirty();
  20149. };
  20150. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20151. if (!this.subMeshes) {
  20152. return;
  20153. }
  20154. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20155. var subMesh = _a[_i];
  20156. if (subMesh._materialDefines) {
  20157. func(subMesh._materialDefines);
  20158. }
  20159. }
  20160. };
  20161. /** @hidden */
  20162. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20163. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20164. };
  20165. /** @hidden */
  20166. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20167. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20168. };
  20169. /** @hidden */
  20170. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20171. if (!this.subMeshes) {
  20172. return;
  20173. }
  20174. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20175. var subMesh = _a[_i];
  20176. var material = subMesh.getMaterial();
  20177. if (material) {
  20178. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20179. }
  20180. }
  20181. };
  20182. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20183. /**
  20184. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20185. */
  20186. get: function () {
  20187. return this._scaling;
  20188. },
  20189. set: function (newScaling) {
  20190. this._scaling = newScaling;
  20191. if (this.physicsImpostor) {
  20192. this.physicsImpostor.forceUpdate();
  20193. }
  20194. },
  20195. enumerable: true,
  20196. configurable: true
  20197. });
  20198. // Methods
  20199. /**
  20200. * Disables the mesh edge rendering mode
  20201. * @returns the currentAbstractMesh
  20202. */
  20203. AbstractMesh.prototype.disableEdgesRendering = function () {
  20204. if (this._edgesRenderer) {
  20205. this._edgesRenderer.dispose();
  20206. this._edgesRenderer = null;
  20207. }
  20208. return this;
  20209. };
  20210. /**
  20211. * Enables the edge rendering mode on the mesh.
  20212. * This mode makes the mesh edges visible
  20213. * @param epsilon defines the maximal distance between two angles to detect a face
  20214. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20215. * @returns the currentAbstractMesh
  20216. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20217. */
  20218. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20219. if (epsilon === void 0) { epsilon = 0.95; }
  20220. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20221. this.disableEdgesRendering();
  20222. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20223. return this;
  20224. };
  20225. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20226. /**
  20227. * Gets the edgesRenderer associated with the mesh
  20228. */
  20229. get: function () {
  20230. return this._edgesRenderer;
  20231. },
  20232. enumerable: true,
  20233. configurable: true
  20234. });
  20235. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20236. /**
  20237. * Returns true if the mesh is blocked. Implemented by child classes
  20238. */
  20239. get: function () {
  20240. return false;
  20241. },
  20242. enumerable: true,
  20243. configurable: true
  20244. });
  20245. /**
  20246. * Returns the mesh itself by default. Implemented by child classes
  20247. * @param camera defines the camera to use to pick the right LOD level
  20248. * @returns the currentAbstractMesh
  20249. */
  20250. AbstractMesh.prototype.getLOD = function (camera) {
  20251. return this;
  20252. };
  20253. /**
  20254. * Returns 0 by default. Implemented by child classes
  20255. * @returns an integer
  20256. */
  20257. AbstractMesh.prototype.getTotalVertices = function () {
  20258. return 0;
  20259. };
  20260. /**
  20261. * Returns null by default. Implemented by child classes
  20262. * @returns null
  20263. */
  20264. AbstractMesh.prototype.getIndices = function () {
  20265. return null;
  20266. };
  20267. /**
  20268. * Returns the array of the requested vertex data kind. Implemented by child classes
  20269. * @param kind defines the vertex data kind to use
  20270. * @returns null
  20271. */
  20272. AbstractMesh.prototype.getVerticesData = function (kind) {
  20273. return null;
  20274. };
  20275. /**
  20276. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20277. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20278. * Note that a new underlying VertexBuffer object is created each call.
  20279. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20280. * @param kind defines vertex data kind:
  20281. * * BABYLON.VertexBuffer.PositionKind
  20282. * * BABYLON.VertexBuffer.UVKind
  20283. * * BABYLON.VertexBuffer.UV2Kind
  20284. * * BABYLON.VertexBuffer.UV3Kind
  20285. * * BABYLON.VertexBuffer.UV4Kind
  20286. * * BABYLON.VertexBuffer.UV5Kind
  20287. * * BABYLON.VertexBuffer.UV6Kind
  20288. * * BABYLON.VertexBuffer.ColorKind
  20289. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20290. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20291. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20292. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20293. * @param data defines the data source
  20294. * @param updatable defines if the data must be flagged as updatable (or static)
  20295. * @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
  20296. * @returns the current mesh
  20297. */
  20298. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20299. return this;
  20300. };
  20301. /**
  20302. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20303. * If the mesh has no geometry, it is simply returned as it is.
  20304. * @param kind defines vertex data kind:
  20305. * * BABYLON.VertexBuffer.PositionKind
  20306. * * BABYLON.VertexBuffer.UVKind
  20307. * * BABYLON.VertexBuffer.UV2Kind
  20308. * * BABYLON.VertexBuffer.UV3Kind
  20309. * * BABYLON.VertexBuffer.UV4Kind
  20310. * * BABYLON.VertexBuffer.UV5Kind
  20311. * * BABYLON.VertexBuffer.UV6Kind
  20312. * * BABYLON.VertexBuffer.ColorKind
  20313. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20314. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20315. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20316. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20317. * @param data defines the data source
  20318. * @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
  20319. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20320. * @returns the current mesh
  20321. */
  20322. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20323. return this;
  20324. };
  20325. /**
  20326. * Sets the mesh indices,
  20327. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20328. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20329. * @param totalVertices Defines the total number of vertices
  20330. * @returns the current mesh
  20331. */
  20332. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20333. return this;
  20334. };
  20335. /**
  20336. * Gets a boolean indicating if specific vertex data is present
  20337. * @param kind defines the vertex data kind to use
  20338. * @returns true is data kind is present
  20339. */
  20340. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20341. return false;
  20342. };
  20343. /**
  20344. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20345. * @returns a BoundingInfo
  20346. */
  20347. AbstractMesh.prototype.getBoundingInfo = function () {
  20348. if (this._masterMesh) {
  20349. return this._masterMesh.getBoundingInfo();
  20350. }
  20351. if (!this._boundingInfo) {
  20352. // this._boundingInfo is being created here
  20353. this._updateBoundingInfo();
  20354. }
  20355. // cannot be null.
  20356. return this._boundingInfo;
  20357. };
  20358. /**
  20359. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20360. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20361. * @returns the current mesh
  20362. */
  20363. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20364. if (includeDescendants === void 0) { includeDescendants = true; }
  20365. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20366. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20367. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20368. if (maxDimension === 0) {
  20369. return this;
  20370. }
  20371. var scale = 1 / maxDimension;
  20372. this.scaling.scaleInPlace(scale);
  20373. return this;
  20374. };
  20375. /**
  20376. * Overwrite the current bounding info
  20377. * @param boundingInfo defines the new bounding info
  20378. * @returns the current mesh
  20379. */
  20380. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20381. this._boundingInfo = boundingInfo;
  20382. return this;
  20383. };
  20384. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20385. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20386. get: function () {
  20387. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20388. },
  20389. enumerable: true,
  20390. configurable: true
  20391. });
  20392. /** @hidden */
  20393. AbstractMesh.prototype._preActivate = function () {
  20394. };
  20395. /** @hidden */
  20396. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20397. };
  20398. /** @hidden */
  20399. AbstractMesh.prototype._activate = function (renderId) {
  20400. this._renderId = renderId;
  20401. };
  20402. /**
  20403. * Gets the current world matrix
  20404. * @returns a Matrix
  20405. */
  20406. AbstractMesh.prototype.getWorldMatrix = function () {
  20407. if (this._masterMesh) {
  20408. return this._masterMesh.getWorldMatrix();
  20409. }
  20410. return _super.prototype.getWorldMatrix.call(this);
  20411. };
  20412. /** @hidden */
  20413. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20414. if (this._masterMesh) {
  20415. return this._masterMesh._getWorldMatrixDeterminant();
  20416. }
  20417. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20418. };
  20419. // ================================== Point of View Movement =================================
  20420. /**
  20421. * Perform relative position change from the point of view of behind the front of the mesh.
  20422. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20423. * Supports definition of mesh facing forward or backward
  20424. * @param amountRight defines the distance on the right axis
  20425. * @param amountUp defines the distance on the up axis
  20426. * @param amountForward defines the distance on the forward axis
  20427. * @returns the current mesh
  20428. */
  20429. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20430. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20431. return this;
  20432. };
  20433. /**
  20434. * Calculate relative position change from the point of view of behind the front of the mesh.
  20435. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20436. * Supports definition of mesh facing forward or backward
  20437. * @param amountRight defines the distance on the right axis
  20438. * @param amountUp defines the distance on the up axis
  20439. * @param amountForward defines the distance on the forward axis
  20440. * @returns the new displacement vector
  20441. */
  20442. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20443. var rotMatrix = new BABYLON.Matrix();
  20444. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20445. rotQuaternion.toRotationMatrix(rotMatrix);
  20446. var translationDelta = BABYLON.Vector3.Zero();
  20447. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20448. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20449. return translationDelta;
  20450. };
  20451. // ================================== Point of View Rotation =================================
  20452. /**
  20453. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20454. * Supports definition of mesh facing forward or backward
  20455. * @param flipBack defines the flip
  20456. * @param twirlClockwise defines the twirl
  20457. * @param tiltRight defines the tilt
  20458. * @returns the current mesh
  20459. */
  20460. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20461. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20462. return this;
  20463. };
  20464. /**
  20465. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20466. * Supports definition of mesh facing forward or backward.
  20467. * @param flipBack defines the flip
  20468. * @param twirlClockwise defines the twirl
  20469. * @param tiltRight defines the tilt
  20470. * @returns the new rotation vector
  20471. */
  20472. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20473. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20474. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20475. };
  20476. /**
  20477. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20478. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20479. * @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
  20480. * @returns the new bounding vectors
  20481. */
  20482. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20483. if (includeDescendants === void 0) { includeDescendants = true; }
  20484. if (predicate === void 0) { predicate = null; }
  20485. // Ensures that all world matrix will be recomputed.
  20486. this.getScene().incrementRenderId();
  20487. this.computeWorldMatrix(true);
  20488. var min;
  20489. var max;
  20490. var boundingInfo = this.getBoundingInfo();
  20491. if (!this.subMeshes) {
  20492. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20493. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20494. }
  20495. else {
  20496. min = boundingInfo.boundingBox.minimumWorld;
  20497. max = boundingInfo.boundingBox.maximumWorld;
  20498. }
  20499. if (includeDescendants) {
  20500. var descendants = this.getDescendants(false);
  20501. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20502. var descendant = descendants_1[_i];
  20503. var childMesh = descendant;
  20504. childMesh.computeWorldMatrix(true);
  20505. // Filters meshes based on custom predicate function.
  20506. if (predicate && !predicate(childMesh)) {
  20507. continue;
  20508. }
  20509. //make sure we have the needed params to get mix and max
  20510. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20511. continue;
  20512. }
  20513. var childBoundingInfo = childMesh.getBoundingInfo();
  20514. var boundingBox = childBoundingInfo.boundingBox;
  20515. var minBox = boundingBox.minimumWorld;
  20516. var maxBox = boundingBox.maximumWorld;
  20517. BABYLON.Tools.CheckExtends(minBox, min, max);
  20518. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20519. }
  20520. }
  20521. return {
  20522. min: min,
  20523. max: max
  20524. };
  20525. };
  20526. /** @hidden */
  20527. AbstractMesh.prototype._updateBoundingInfo = function () {
  20528. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20529. this._boundingInfo.update(this.worldMatrixFromCache);
  20530. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20531. return this;
  20532. };
  20533. /** @hidden */
  20534. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20535. if (!this.subMeshes) {
  20536. return this;
  20537. }
  20538. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20539. var subMesh = this.subMeshes[subIndex];
  20540. if (!subMesh.IsGlobal) {
  20541. subMesh.updateBoundingInfo(matrix);
  20542. }
  20543. }
  20544. return this;
  20545. };
  20546. /** @hidden */
  20547. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20548. // Bounding info
  20549. this._updateBoundingInfo();
  20550. };
  20551. /**
  20552. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20553. * A mesh is in the frustum if its bounding box intersects the frustum
  20554. * @param frustumPlanes defines the frustum to test
  20555. * @returns true if the mesh is in the frustum planes
  20556. */
  20557. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20558. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  20559. };
  20560. /**
  20561. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20562. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20563. * @param frustumPlanes defines the frustum to test
  20564. * @returns true if the mesh is completely in the frustum planes
  20565. */
  20566. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20567. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20568. };
  20569. /**
  20570. * True if the mesh intersects another mesh or a SolidParticle object
  20571. * @param mesh defines a target mesh or SolidParticle to test
  20572. * @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)
  20573. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20574. * @returns true if there is an intersection
  20575. */
  20576. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20577. if (precise === void 0) { precise = false; }
  20578. if (!this._boundingInfo || !mesh._boundingInfo) {
  20579. return false;
  20580. }
  20581. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20582. return true;
  20583. }
  20584. if (includeDescendants) {
  20585. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20586. var child = _a[_i];
  20587. if (child.intersectsMesh(mesh, precise, true)) {
  20588. return true;
  20589. }
  20590. }
  20591. }
  20592. return false;
  20593. };
  20594. /**
  20595. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20596. * @param point defines the point to test
  20597. * @returns true if there is an intersection
  20598. */
  20599. AbstractMesh.prototype.intersectsPoint = function (point) {
  20600. if (!this._boundingInfo) {
  20601. return false;
  20602. }
  20603. return this._boundingInfo.intersectsPoint(point);
  20604. };
  20605. /**
  20606. * Gets the current physics impostor
  20607. * @see http://doc.babylonjs.com/features/physics_engine
  20608. * @returns a physics impostor or null
  20609. */
  20610. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20611. return this.physicsImpostor;
  20612. };
  20613. /**
  20614. * Gets the position of the current mesh in camera space
  20615. * @param camera defines the camera to use
  20616. * @returns a position
  20617. */
  20618. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20619. if (camera === void 0) { camera = null; }
  20620. if (!camera) {
  20621. camera = this.getScene().activeCamera;
  20622. }
  20623. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20624. };
  20625. /**
  20626. * Returns the distance from the mesh to the active camera
  20627. * @param camera defines the camera to use
  20628. * @returns the distance
  20629. */
  20630. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20631. if (camera === void 0) { camera = null; }
  20632. if (!camera) {
  20633. camera = this.getScene().activeCamera;
  20634. }
  20635. return this.absolutePosition.subtract(camera.position).length();
  20636. };
  20637. /**
  20638. * Apply a physic impulse to the mesh
  20639. * @param force defines the force to apply
  20640. * @param contactPoint defines where to apply the force
  20641. * @returns the current mesh
  20642. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20643. */
  20644. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20645. if (!this.physicsImpostor) {
  20646. return this;
  20647. }
  20648. this.physicsImpostor.applyImpulse(force, contactPoint);
  20649. return this;
  20650. };
  20651. /**
  20652. * Creates a physic joint between two meshes
  20653. * @param otherMesh defines the other mesh to use
  20654. * @param pivot1 defines the pivot to use on this mesh
  20655. * @param pivot2 defines the pivot to use on the other mesh
  20656. * @param options defines additional options (can be plugin dependent)
  20657. * @returns the current mesh
  20658. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20659. */
  20660. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20661. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20662. return this;
  20663. }
  20664. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20665. mainPivot: pivot1,
  20666. connectedPivot: pivot2,
  20667. nativeParams: options
  20668. });
  20669. return this;
  20670. };
  20671. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20672. // Collisions
  20673. /**
  20674. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20675. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20676. */
  20677. get: function () {
  20678. return this._checkCollisions;
  20679. },
  20680. set: function (collisionEnabled) {
  20681. this._checkCollisions = collisionEnabled;
  20682. if (this.getScene().workerCollisions) {
  20683. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20684. }
  20685. },
  20686. enumerable: true,
  20687. configurable: true
  20688. });
  20689. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20690. /**
  20691. * Gets Collider object used to compute collisions (not physics)
  20692. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20693. */
  20694. get: function () {
  20695. return this._collider;
  20696. },
  20697. enumerable: true,
  20698. configurable: true
  20699. });
  20700. /**
  20701. * Move the mesh using collision engine
  20702. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20703. * @param displacement defines the requested displacement vector
  20704. * @returns the current mesh
  20705. */
  20706. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20707. var globalPosition = this.getAbsolutePosition();
  20708. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20709. if (!this._collider) {
  20710. this._collider = new BABYLON.Collider();
  20711. }
  20712. this._collider._radius = this.ellipsoid;
  20713. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20714. return this;
  20715. };
  20716. // Submeshes octree
  20717. /**
  20718. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20719. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20720. * @param maxCapacity defines the maximum size of each block (64 by default)
  20721. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20722. * @returns the new octree
  20723. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20724. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20725. */
  20726. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20727. if (maxCapacity === void 0) { maxCapacity = 64; }
  20728. if (maxDepth === void 0) { maxDepth = 2; }
  20729. if (!this._submeshesOctree) {
  20730. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20731. }
  20732. this.computeWorldMatrix(true);
  20733. var boundingInfo = this.getBoundingInfo();
  20734. // Update octree
  20735. var bbox = boundingInfo.boundingBox;
  20736. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20737. return this._submeshesOctree;
  20738. };
  20739. // Collisions
  20740. /** @hidden */
  20741. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20742. this._generatePointsArray();
  20743. if (!this._positions) {
  20744. return this;
  20745. }
  20746. // Transformation
  20747. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20748. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20749. subMesh._lastColliderWorldVertices = [];
  20750. subMesh._trianglePlanes = [];
  20751. var start = subMesh.verticesStart;
  20752. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20753. for (var i = start; i < end; i++) {
  20754. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20755. }
  20756. }
  20757. // Collide
  20758. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20759. if (collider.collisionFound) {
  20760. collider.collidedMesh = this;
  20761. }
  20762. return this;
  20763. };
  20764. /** @hidden */
  20765. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20766. var subMeshes;
  20767. var len;
  20768. // Octrees
  20769. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20770. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20771. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20772. len = intersections.length;
  20773. subMeshes = intersections.data;
  20774. }
  20775. else {
  20776. subMeshes = this.subMeshes;
  20777. len = subMeshes.length;
  20778. }
  20779. for (var index = 0; index < len; index++) {
  20780. var subMesh = subMeshes[index];
  20781. // Bounding test
  20782. if (len > 1 && !subMesh._checkCollision(collider))
  20783. continue;
  20784. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20785. }
  20786. return this;
  20787. };
  20788. /** @hidden */
  20789. AbstractMesh.prototype._checkCollision = function (collider) {
  20790. // Bounding box test
  20791. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20792. return this;
  20793. // Transformation matrix
  20794. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20795. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20796. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20797. return this;
  20798. };
  20799. // Picking
  20800. /** @hidden */
  20801. AbstractMesh.prototype._generatePointsArray = function () {
  20802. return false;
  20803. };
  20804. /**
  20805. * Checks if the passed Ray intersects with the mesh
  20806. * @param ray defines the ray to use
  20807. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20808. * @returns the picking info
  20809. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20810. */
  20811. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20812. var pickingInfo = new BABYLON.PickingInfo();
  20813. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20814. return pickingInfo;
  20815. }
  20816. if (!this._generatePointsArray()) {
  20817. return pickingInfo;
  20818. }
  20819. var intersectInfo = null;
  20820. // Octrees
  20821. var subMeshes;
  20822. var len;
  20823. if (this._submeshesOctree && this.useOctreeForPicking) {
  20824. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20825. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20826. len = intersections.length;
  20827. subMeshes = intersections.data;
  20828. }
  20829. else {
  20830. subMeshes = this.subMeshes;
  20831. len = subMeshes.length;
  20832. }
  20833. for (var index = 0; index < len; index++) {
  20834. var subMesh = subMeshes[index];
  20835. // Bounding test
  20836. if (len > 1 && !subMesh.canIntersects(ray))
  20837. continue;
  20838. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20839. if (currentIntersectInfo) {
  20840. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20841. intersectInfo = currentIntersectInfo;
  20842. intersectInfo.subMeshId = index;
  20843. if (fastCheck) {
  20844. break;
  20845. }
  20846. }
  20847. }
  20848. }
  20849. if (intersectInfo) {
  20850. // Get picked point
  20851. var world = this.getWorldMatrix();
  20852. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20853. var direction = ray.direction.clone();
  20854. direction = direction.scale(intersectInfo.distance);
  20855. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20856. var pickedPoint = worldOrigin.add(worldDirection);
  20857. // Return result
  20858. pickingInfo.hit = true;
  20859. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20860. pickingInfo.pickedPoint = pickedPoint;
  20861. pickingInfo.pickedMesh = this;
  20862. pickingInfo.bu = intersectInfo.bu || 0;
  20863. pickingInfo.bv = intersectInfo.bv || 0;
  20864. pickingInfo.faceId = intersectInfo.faceId;
  20865. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20866. return pickingInfo;
  20867. }
  20868. return pickingInfo;
  20869. };
  20870. /**
  20871. * Clones the current mesh
  20872. * @param name defines the mesh name
  20873. * @param newParent defines the new mesh parent
  20874. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20875. * @returns the new mesh
  20876. */
  20877. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20878. return null;
  20879. };
  20880. /**
  20881. * Disposes all the submeshes of the current meshnp
  20882. * @returns the current mesh
  20883. */
  20884. AbstractMesh.prototype.releaseSubMeshes = function () {
  20885. if (this.subMeshes) {
  20886. while (this.subMeshes.length) {
  20887. this.subMeshes[0].dispose();
  20888. }
  20889. }
  20890. else {
  20891. this.subMeshes = new Array();
  20892. }
  20893. return this;
  20894. };
  20895. /**
  20896. * Releases resources associated with this abstract mesh.
  20897. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20898. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20899. */
  20900. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20901. var _this = this;
  20902. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20903. var index;
  20904. // Smart Array Retainers.
  20905. this.getScene().freeActiveMeshes();
  20906. this.getScene().freeRenderingGroups();
  20907. // Action manager
  20908. if (this.actionManager !== undefined && this.actionManager !== null) {
  20909. this.actionManager.dispose();
  20910. this.actionManager = null;
  20911. }
  20912. // Skeleton
  20913. this._skeleton = null;
  20914. // Physics
  20915. if (this.physicsImpostor) {
  20916. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20917. }
  20918. // Intersections in progress
  20919. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20920. var other = this._intersectionsInProgress[index];
  20921. var pos = other._intersectionsInProgress.indexOf(this);
  20922. other._intersectionsInProgress.splice(pos, 1);
  20923. }
  20924. this._intersectionsInProgress = [];
  20925. // Lights
  20926. var lights = this.getScene().lights;
  20927. lights.forEach(function (light) {
  20928. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20929. if (meshIndex !== -1) {
  20930. light.includedOnlyMeshes.splice(meshIndex, 1);
  20931. }
  20932. meshIndex = light.excludedMeshes.indexOf(_this);
  20933. if (meshIndex !== -1) {
  20934. light.excludedMeshes.splice(meshIndex, 1);
  20935. }
  20936. // Shadow generators
  20937. var generator = light.getShadowGenerator();
  20938. if (generator) {
  20939. var shadowMap = generator.getShadowMap();
  20940. if (shadowMap && shadowMap.renderList) {
  20941. meshIndex = shadowMap.renderList.indexOf(_this);
  20942. if (meshIndex !== -1) {
  20943. shadowMap.renderList.splice(meshIndex, 1);
  20944. }
  20945. }
  20946. }
  20947. });
  20948. // Edges
  20949. if (this._edgesRenderer) {
  20950. this._edgesRenderer.dispose();
  20951. this._edgesRenderer = null;
  20952. }
  20953. // SubMeshes
  20954. if (this.getClassName() !== "InstancedMesh") {
  20955. this.releaseSubMeshes();
  20956. }
  20957. // Octree
  20958. var sceneOctree = this.getScene().selectionOctree;
  20959. if (sceneOctree !== undefined && sceneOctree !== null) {
  20960. var index = sceneOctree.dynamicContent.indexOf(this);
  20961. if (index !== -1) {
  20962. sceneOctree.dynamicContent.splice(index, 1);
  20963. }
  20964. }
  20965. // Query
  20966. var engine = this.getScene().getEngine();
  20967. if (this._occlusionQuery) {
  20968. this._isOcclusionQueryInProgress = false;
  20969. engine.deleteQuery(this._occlusionQuery);
  20970. this._occlusionQuery = null;
  20971. }
  20972. // Engine
  20973. engine.wipeCaches();
  20974. // Remove from scene
  20975. this.getScene().removeMesh(this);
  20976. if (disposeMaterialAndTextures) {
  20977. if (this.material) {
  20978. this.material.dispose(false, true);
  20979. }
  20980. }
  20981. if (!doNotRecurse) {
  20982. // Particles
  20983. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20984. if (this.getScene().particleSystems[index].emitter === this) {
  20985. this.getScene().particleSystems[index].dispose();
  20986. index--;
  20987. }
  20988. }
  20989. }
  20990. // facet data
  20991. if (this._facetDataEnabled) {
  20992. this.disableFacetData();
  20993. }
  20994. this.onAfterWorldMatrixUpdateObservable.clear();
  20995. this.onCollideObservable.clear();
  20996. this.onCollisionPositionChangeObservable.clear();
  20997. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20998. };
  20999. /**
  21000. * Adds the passed mesh as a child to the current mesh
  21001. * @param mesh defines the child mesh
  21002. * @returns the current mesh
  21003. */
  21004. AbstractMesh.prototype.addChild = function (mesh) {
  21005. mesh.setParent(this);
  21006. return this;
  21007. };
  21008. /**
  21009. * Removes the passed mesh from the current mesh children list
  21010. * @param mesh defines the child mesh
  21011. * @returns the current mesh
  21012. */
  21013. AbstractMesh.prototype.removeChild = function (mesh) {
  21014. mesh.setParent(null);
  21015. return this;
  21016. };
  21017. // Facet data
  21018. /** @hidden */
  21019. AbstractMesh.prototype._initFacetData = function () {
  21020. if (!this._facetNormals) {
  21021. this._facetNormals = new Array();
  21022. }
  21023. if (!this._facetPositions) {
  21024. this._facetPositions = new Array();
  21025. }
  21026. if (!this._facetPartitioning) {
  21027. this._facetPartitioning = new Array();
  21028. }
  21029. this._facetNb = (this.getIndices().length / 3) | 0;
  21030. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21031. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21032. for (var f = 0; f < this._facetNb; f++) {
  21033. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21034. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21035. }
  21036. this._facetDataEnabled = true;
  21037. return this;
  21038. };
  21039. /**
  21040. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21041. * This method can be called within the render loop.
  21042. * 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
  21043. * @returns the current mesh
  21044. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21045. */
  21046. AbstractMesh.prototype.updateFacetData = function () {
  21047. if (!this._facetDataEnabled) {
  21048. this._initFacetData();
  21049. }
  21050. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21051. var indices = this.getIndices();
  21052. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21053. var bInfo = this.getBoundingInfo();
  21054. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21055. // init arrays, matrix and sort function on first call
  21056. this._facetDepthSortEnabled = true;
  21057. if (indices instanceof Uint16Array) {
  21058. this._depthSortedIndices = new Uint16Array(indices);
  21059. }
  21060. else if (indices instanceof Uint32Array) {
  21061. this._depthSortedIndices = new Uint32Array(indices);
  21062. }
  21063. else {
  21064. var needs32bits = false;
  21065. for (var i = 0; i < indices.length; i++) {
  21066. if (indices[i] > 65535) {
  21067. needs32bits = true;
  21068. break;
  21069. }
  21070. }
  21071. if (needs32bits) {
  21072. this._depthSortedIndices = new Uint32Array(indices);
  21073. }
  21074. else {
  21075. this._depthSortedIndices = new Uint16Array(indices);
  21076. }
  21077. }
  21078. this._facetDepthSortFunction = function (f1, f2) {
  21079. return (f2.sqDistance - f1.sqDistance);
  21080. };
  21081. if (!this._facetDepthSortFrom) {
  21082. var camera = this.getScene().activeCamera;
  21083. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21084. }
  21085. this._depthSortedFacets = [];
  21086. for (var f = 0; f < this._facetNb; f++) {
  21087. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21088. this._depthSortedFacets.push(depthSortedFacet);
  21089. }
  21090. this._invertedMatrix = BABYLON.Matrix.Identity();
  21091. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21092. }
  21093. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21094. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21095. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21096. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21097. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21098. this._subDiv.max = this._partitioningSubdivisions;
  21099. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21100. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21101. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21102. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21103. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21104. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21105. // set the parameters for ComputeNormals()
  21106. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21107. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21108. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21109. this._facetParameters.bInfo = bInfo;
  21110. this._facetParameters.bbSize = this._bbSize;
  21111. this._facetParameters.subDiv = this._subDiv;
  21112. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21113. this._facetParameters.depthSort = this._facetDepthSort;
  21114. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21115. this.computeWorldMatrix(true);
  21116. this._worldMatrix.invertToRef(this._invertedMatrix);
  21117. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21118. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21119. }
  21120. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21121. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21122. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21123. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21124. var l = (this._depthSortedIndices.length / 3) | 0;
  21125. for (var f = 0; f < l; f++) {
  21126. var sind = this._depthSortedFacets[f].ind;
  21127. this._depthSortedIndices[f * 3] = indices[sind];
  21128. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21129. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21130. }
  21131. this.updateIndices(this._depthSortedIndices);
  21132. }
  21133. return this;
  21134. };
  21135. /**
  21136. * Returns the facetLocalNormals array.
  21137. * The normals are expressed in the mesh local spac
  21138. * @returns an array of Vector3
  21139. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21140. */
  21141. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21142. if (!this._facetNormals) {
  21143. this.updateFacetData();
  21144. }
  21145. return this._facetNormals;
  21146. };
  21147. /**
  21148. * Returns the facetLocalPositions array.
  21149. * The facet positions are expressed in the mesh local space
  21150. * @returns an array of Vector3
  21151. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21152. */
  21153. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21154. if (!this._facetPositions) {
  21155. this.updateFacetData();
  21156. }
  21157. return this._facetPositions;
  21158. };
  21159. /**
  21160. * Returns the facetLocalPartioning array
  21161. * @returns an array of array of numbers
  21162. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21163. */
  21164. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21165. if (!this._facetPartitioning) {
  21166. this.updateFacetData();
  21167. }
  21168. return this._facetPartitioning;
  21169. };
  21170. /**
  21171. * Returns the i-th facet position in the world system.
  21172. * This method allocates a new Vector3 per call
  21173. * @param i defines the facet index
  21174. * @returns a new Vector3
  21175. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21176. */
  21177. AbstractMesh.prototype.getFacetPosition = function (i) {
  21178. var pos = BABYLON.Vector3.Zero();
  21179. this.getFacetPositionToRef(i, pos);
  21180. return pos;
  21181. };
  21182. /**
  21183. * Sets the reference Vector3 with the i-th facet position in the world system
  21184. * @param i defines the facet index
  21185. * @param ref defines the target vector
  21186. * @returns the current mesh
  21187. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21188. */
  21189. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21190. var localPos = (this.getFacetLocalPositions())[i];
  21191. var world = this.getWorldMatrix();
  21192. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21193. return this;
  21194. };
  21195. /**
  21196. * Returns the i-th facet normal in the world system.
  21197. * This method allocates a new Vector3 per call
  21198. * @param i defines the facet index
  21199. * @returns a new Vector3
  21200. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21201. */
  21202. AbstractMesh.prototype.getFacetNormal = function (i) {
  21203. var norm = BABYLON.Vector3.Zero();
  21204. this.getFacetNormalToRef(i, norm);
  21205. return norm;
  21206. };
  21207. /**
  21208. * Sets the reference Vector3 with the i-th facet normal in the world system
  21209. * @param i defines the facet index
  21210. * @param ref defines the target vector
  21211. * @returns the current mesh
  21212. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21213. */
  21214. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21215. var localNorm = (this.getFacetLocalNormals())[i];
  21216. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21217. return this;
  21218. };
  21219. /**
  21220. * 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)
  21221. * @param x defines x coordinate
  21222. * @param y defines y coordinate
  21223. * @param z defines z coordinate
  21224. * @returns the array of facet indexes
  21225. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21226. */
  21227. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21228. var bInfo = this.getBoundingInfo();
  21229. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21230. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21231. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21232. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21233. return null;
  21234. }
  21235. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21236. };
  21237. /**
  21238. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21239. * @param projected sets as the (x,y,z) world projection on the facet
  21240. * @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
  21241. * @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
  21242. * @param x defines x coordinate
  21243. * @param y defines y coordinate
  21244. * @param z defines z coordinate
  21245. * @returns the face index if found (or null instead)
  21246. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21247. */
  21248. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21249. if (checkFace === void 0) { checkFace = false; }
  21250. if (facing === void 0) { facing = true; }
  21251. var world = this.getWorldMatrix();
  21252. var invMat = BABYLON.Tmp.Matrix[5];
  21253. world.invertToRef(invMat);
  21254. var invVect = BABYLON.Tmp.Vector3[8];
  21255. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21256. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21257. if (projected) {
  21258. // tranform the local computed projected vector to world coordinates
  21259. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21260. }
  21261. return closest;
  21262. };
  21263. /**
  21264. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21265. * @param projected sets as the (x,y,z) local projection on the facet
  21266. * @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
  21267. * @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
  21268. * @param x defines x coordinate
  21269. * @param y defines y coordinate
  21270. * @param z defines z coordinate
  21271. * @returns the face index if found (or null instead)
  21272. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21273. */
  21274. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21275. if (checkFace === void 0) { checkFace = false; }
  21276. if (facing === void 0) { facing = true; }
  21277. var closest = null;
  21278. var tmpx = 0.0;
  21279. var tmpy = 0.0;
  21280. var tmpz = 0.0;
  21281. var d = 0.0; // tmp dot facet normal * facet position
  21282. var t0 = 0.0;
  21283. var projx = 0.0;
  21284. var projy = 0.0;
  21285. var projz = 0.0;
  21286. // Get all the facets in the same partitioning block than (x, y, z)
  21287. var facetPositions = this.getFacetLocalPositions();
  21288. var facetNormals = this.getFacetLocalNormals();
  21289. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21290. if (!facetsInBlock) {
  21291. return null;
  21292. }
  21293. // Get the closest facet to (x, y, z)
  21294. var shortest = Number.MAX_VALUE; // init distance vars
  21295. var tmpDistance = shortest;
  21296. var fib; // current facet in the block
  21297. var norm; // current facet normal
  21298. var p0; // current facet barycenter position
  21299. // loop on all the facets in the current partitioning block
  21300. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21301. fib = facetsInBlock[idx];
  21302. norm = facetNormals[fib];
  21303. p0 = facetPositions[fib];
  21304. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21305. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21306. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21307. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21308. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21309. projx = x + norm.x * t0;
  21310. projy = y + norm.y * t0;
  21311. projz = z + norm.z * t0;
  21312. tmpx = projx - x;
  21313. tmpy = projy - y;
  21314. tmpz = projz - z;
  21315. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21316. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21317. shortest = tmpDistance;
  21318. closest = fib;
  21319. if (projected) {
  21320. projected.x = projx;
  21321. projected.y = projy;
  21322. projected.z = projz;
  21323. }
  21324. }
  21325. }
  21326. }
  21327. return closest;
  21328. };
  21329. /**
  21330. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21331. * @returns the parameters
  21332. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21333. */
  21334. AbstractMesh.prototype.getFacetDataParameters = function () {
  21335. return this._facetParameters;
  21336. };
  21337. /**
  21338. * Disables the feature FacetData and frees the related memory
  21339. * @returns the current mesh
  21340. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21341. */
  21342. AbstractMesh.prototype.disableFacetData = function () {
  21343. if (this._facetDataEnabled) {
  21344. this._facetDataEnabled = false;
  21345. this._facetPositions = new Array();
  21346. this._facetNormals = new Array();
  21347. this._facetPartitioning = new Array();
  21348. this._facetParameters = null;
  21349. this._depthSortedIndices = new Uint32Array(0);
  21350. }
  21351. return this;
  21352. };
  21353. /**
  21354. * Updates the AbstractMesh indices array
  21355. * @param indices defines the data source
  21356. * @returns the current mesh
  21357. */
  21358. AbstractMesh.prototype.updateIndices = function (indices) {
  21359. return this;
  21360. };
  21361. /**
  21362. * Creates new normals data for the mesh
  21363. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21364. * @returns the current mesh
  21365. */
  21366. AbstractMesh.prototype.createNormals = function (updatable) {
  21367. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21368. var indices = this.getIndices();
  21369. var normals;
  21370. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21371. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21372. }
  21373. else {
  21374. normals = [];
  21375. }
  21376. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21377. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21378. return this;
  21379. };
  21380. /**
  21381. * Align the mesh with a normal
  21382. * @param normal defines the normal to use
  21383. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21384. * @returns the current mesh
  21385. */
  21386. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21387. if (!upDirection) {
  21388. upDirection = BABYLON.Axis.Y;
  21389. }
  21390. var axisX = BABYLON.Tmp.Vector3[0];
  21391. var axisZ = BABYLON.Tmp.Vector3[1];
  21392. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21393. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21394. if (this.rotationQuaternion) {
  21395. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21396. }
  21397. else {
  21398. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21399. }
  21400. return this;
  21401. };
  21402. /** @hidden */
  21403. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21404. this._isOccluded = false;
  21405. };
  21406. /** No occlusion */
  21407. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21408. /** Occlusion set to optimisitic */
  21409. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21410. /** Occlusion set to strict */
  21411. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21412. /** Use an accurante occlusion algorithm */
  21413. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21414. /** Use a conservative occlusion algorithm */
  21415. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21416. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  21417. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  21418. /** Culling strategy with bounding sphere only and then frustum culling */
  21419. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  21420. return AbstractMesh;
  21421. }(BABYLON.TransformNode));
  21422. BABYLON.AbstractMesh = AbstractMesh;
  21423. })(BABYLON || (BABYLON = {}));
  21424. //# sourceMappingURL=babylon.abstractMesh.js.map
  21425. var BABYLON;
  21426. (function (BABYLON) {
  21427. /**
  21428. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21429. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21430. * 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.
  21431. */
  21432. var Light = /** @class */ (function (_super) {
  21433. __extends(Light, _super);
  21434. /**
  21435. * Creates a Light object in the scene.
  21436. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21437. * @param name The firendly name of the light
  21438. * @param scene The scene the light belongs too
  21439. */
  21440. function Light(name, scene) {
  21441. var _this = _super.call(this, name, scene) || this;
  21442. /**
  21443. * Diffuse gives the basic color to an object.
  21444. */
  21445. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21446. /**
  21447. * Specular produces a highlight color on an object.
  21448. * Note: This is note affecting PBR materials.
  21449. */
  21450. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21451. /**
  21452. * Defines the falloff type for this light. This lets overrriding how punctual light are
  21453. * falling off base on range or angle.
  21454. * This can be set to any values in Light.FALLOFF_x.
  21455. *
  21456. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  21457. * other types of materials.
  21458. */
  21459. _this.falloffType = Light.FALLOFF_DEFAULT;
  21460. /**
  21461. * Strength of the light.
  21462. * Note: By default it is define in the framework own unit.
  21463. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21464. */
  21465. _this.intensity = 1.0;
  21466. _this._range = Number.MAX_VALUE;
  21467. _this._inverseSquaredRange = 0;
  21468. /**
  21469. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21470. * of light.
  21471. */
  21472. _this._photometricScale = 1.0;
  21473. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21474. _this._radius = 0.00001;
  21475. /**
  21476. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21477. * exceeding the number allowed of the materials.
  21478. */
  21479. _this.renderPriority = 0;
  21480. _this._shadowEnabled = true;
  21481. _this._excludeWithLayerMask = 0;
  21482. _this._includeOnlyWithLayerMask = 0;
  21483. _this._lightmapMode = 0;
  21484. /**
  21485. * @hidden Internal use only.
  21486. */
  21487. _this._excludedMeshesIds = new Array();
  21488. /**
  21489. * @hidden Internal use only.
  21490. */
  21491. _this._includedOnlyMeshesIds = new Array();
  21492. _this.getScene().addLight(_this);
  21493. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21494. _this._buildUniformLayout();
  21495. _this.includedOnlyMeshes = new Array();
  21496. _this.excludedMeshes = new Array();
  21497. _this._resyncMeshes();
  21498. return _this;
  21499. }
  21500. Object.defineProperty(Light.prototype, "range", {
  21501. /**
  21502. * Defines how far from the source the light is impacting in scene units.
  21503. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21504. */
  21505. get: function () {
  21506. return this._range;
  21507. },
  21508. /**
  21509. * Defines how far from the source the light is impacting in scene units.
  21510. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21511. */
  21512. set: function (value) {
  21513. this._range = value;
  21514. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  21515. },
  21516. enumerable: true,
  21517. configurable: true
  21518. });
  21519. Object.defineProperty(Light.prototype, "intensityMode", {
  21520. /**
  21521. * Gets the photometric scale used to interpret the intensity.
  21522. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21523. */
  21524. get: function () {
  21525. return this._intensityMode;
  21526. },
  21527. /**
  21528. * Sets the photometric scale used to interpret the intensity.
  21529. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21530. */
  21531. set: function (value) {
  21532. this._intensityMode = value;
  21533. this._computePhotometricScale();
  21534. },
  21535. enumerable: true,
  21536. configurable: true
  21537. });
  21538. ;
  21539. ;
  21540. Object.defineProperty(Light.prototype, "radius", {
  21541. /**
  21542. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21543. */
  21544. get: function () {
  21545. return this._radius;
  21546. },
  21547. /**
  21548. * sets the light radius used by PBR Materials to simulate soft area lights.
  21549. */
  21550. set: function (value) {
  21551. this._radius = value;
  21552. this._computePhotometricScale();
  21553. },
  21554. enumerable: true,
  21555. configurable: true
  21556. });
  21557. ;
  21558. ;
  21559. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21560. /**
  21561. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21562. * the current shadow generator.
  21563. */
  21564. get: function () {
  21565. return this._shadowEnabled;
  21566. },
  21567. /**
  21568. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21569. * the current shadow generator.
  21570. */
  21571. set: function (value) {
  21572. if (this._shadowEnabled === value) {
  21573. return;
  21574. }
  21575. this._shadowEnabled = value;
  21576. this._markMeshesAsLightDirty();
  21577. },
  21578. enumerable: true,
  21579. configurable: true
  21580. });
  21581. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21582. /**
  21583. * Gets the only meshes impacted by this light.
  21584. */
  21585. get: function () {
  21586. return this._includedOnlyMeshes;
  21587. },
  21588. /**
  21589. * Sets the only meshes impacted by this light.
  21590. */
  21591. set: function (value) {
  21592. this._includedOnlyMeshes = value;
  21593. this._hookArrayForIncludedOnly(value);
  21594. },
  21595. enumerable: true,
  21596. configurable: true
  21597. });
  21598. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21599. /**
  21600. * Gets the meshes not impacted by this light.
  21601. */
  21602. get: function () {
  21603. return this._excludedMeshes;
  21604. },
  21605. /**
  21606. * Sets the meshes not impacted by this light.
  21607. */
  21608. set: function (value) {
  21609. this._excludedMeshes = value;
  21610. this._hookArrayForExcluded(value);
  21611. },
  21612. enumerable: true,
  21613. configurable: true
  21614. });
  21615. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21616. /**
  21617. * Gets the layer id use to find what meshes are not impacted by the light.
  21618. * Inactive if 0
  21619. */
  21620. get: function () {
  21621. return this._excludeWithLayerMask;
  21622. },
  21623. /**
  21624. * Sets the layer id use to find what meshes are not impacted by the light.
  21625. * Inactive if 0
  21626. */
  21627. set: function (value) {
  21628. this._excludeWithLayerMask = value;
  21629. this._resyncMeshes();
  21630. },
  21631. enumerable: true,
  21632. configurable: true
  21633. });
  21634. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21635. /**
  21636. * Gets the layer id use to find what meshes are impacted by the light.
  21637. * Inactive if 0
  21638. */
  21639. get: function () {
  21640. return this._includeOnlyWithLayerMask;
  21641. },
  21642. /**
  21643. * Sets the layer id use to find what meshes are impacted by the light.
  21644. * Inactive if 0
  21645. */
  21646. set: function (value) {
  21647. this._includeOnlyWithLayerMask = value;
  21648. this._resyncMeshes();
  21649. },
  21650. enumerable: true,
  21651. configurable: true
  21652. });
  21653. Object.defineProperty(Light.prototype, "lightmapMode", {
  21654. /**
  21655. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21656. */
  21657. get: function () {
  21658. return this._lightmapMode;
  21659. },
  21660. /**
  21661. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21662. */
  21663. set: function (value) {
  21664. if (this._lightmapMode === value) {
  21665. return;
  21666. }
  21667. this._lightmapMode = value;
  21668. this._markMeshesAsLightDirty();
  21669. },
  21670. enumerable: true,
  21671. configurable: true
  21672. });
  21673. /**
  21674. * Returns the string "Light".
  21675. * @returns the class name
  21676. */
  21677. Light.prototype.getClassName = function () {
  21678. return "Light";
  21679. };
  21680. /**
  21681. * Converts the light information to a readable string for debug purpose.
  21682. * @param fullDetails Supports for multiple levels of logging within scene loading
  21683. * @returns the human readable light info
  21684. */
  21685. Light.prototype.toString = function (fullDetails) {
  21686. var ret = "Name: " + this.name;
  21687. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21688. if (this.animations) {
  21689. for (var i = 0; i < this.animations.length; i++) {
  21690. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21691. }
  21692. }
  21693. if (fullDetails) {
  21694. }
  21695. return ret;
  21696. };
  21697. /**
  21698. * Set the enabled state of this node.
  21699. * @param value - the new enabled state
  21700. */
  21701. Light.prototype.setEnabled = function (value) {
  21702. _super.prototype.setEnabled.call(this, value);
  21703. this._resyncMeshes();
  21704. };
  21705. /**
  21706. * Returns the Light associated shadow generator if any.
  21707. * @return the associated shadow generator.
  21708. */
  21709. Light.prototype.getShadowGenerator = function () {
  21710. return this._shadowGenerator;
  21711. };
  21712. /**
  21713. * Returns a Vector3, the absolute light position in the World.
  21714. * @returns the world space position of the light
  21715. */
  21716. Light.prototype.getAbsolutePosition = function () {
  21717. return BABYLON.Vector3.Zero();
  21718. };
  21719. /**
  21720. * Specifies if the light will affect the passed mesh.
  21721. * @param mesh The mesh to test against the light
  21722. * @return true the mesh is affected otherwise, false.
  21723. */
  21724. Light.prototype.canAffectMesh = function (mesh) {
  21725. if (!mesh) {
  21726. return true;
  21727. }
  21728. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21729. return false;
  21730. }
  21731. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21732. return false;
  21733. }
  21734. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21735. return false;
  21736. }
  21737. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21738. return false;
  21739. }
  21740. return true;
  21741. };
  21742. /**
  21743. * Computes and Returns the light World matrix.
  21744. * @returns the world matrix
  21745. */
  21746. Light.prototype.getWorldMatrix = function () {
  21747. this._currentRenderId = this.getScene().getRenderId();
  21748. this._childRenderId = this._currentRenderId;
  21749. var worldMatrix = this._getWorldMatrix();
  21750. if (this.parent && this.parent.getWorldMatrix) {
  21751. if (!this._parentedWorldMatrix) {
  21752. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21753. }
  21754. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21755. this._markSyncedWithParent();
  21756. return this._parentedWorldMatrix;
  21757. }
  21758. return worldMatrix;
  21759. };
  21760. /**
  21761. * Sort function to order lights for rendering.
  21762. * @param a First Light object to compare to second.
  21763. * @param b Second Light object to compare first.
  21764. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21765. */
  21766. Light.CompareLightsPriority = function (a, b) {
  21767. //shadow-casting lights have priority over non-shadow-casting lights
  21768. //the renderPrioirty is a secondary sort criterion
  21769. if (a.shadowEnabled !== b.shadowEnabled) {
  21770. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21771. }
  21772. return b.renderPriority - a.renderPriority;
  21773. };
  21774. /**
  21775. * Releases resources associated with this node.
  21776. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21777. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21778. */
  21779. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21780. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21781. if (this._shadowGenerator) {
  21782. this._shadowGenerator.dispose();
  21783. this._shadowGenerator = null;
  21784. }
  21785. // Animations
  21786. this.getScene().stopAnimation(this);
  21787. // Remove from meshes
  21788. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21789. var mesh = _a[_i];
  21790. mesh._removeLightSource(this);
  21791. }
  21792. this._uniformBuffer.dispose();
  21793. // Remove from scene
  21794. this.getScene().removeLight(this);
  21795. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21796. };
  21797. /**
  21798. * Returns the light type ID (integer).
  21799. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21800. */
  21801. Light.prototype.getTypeID = function () {
  21802. return 0;
  21803. };
  21804. /**
  21805. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21806. * @returns the scaled intensity in intensity mode unit
  21807. */
  21808. Light.prototype.getScaledIntensity = function () {
  21809. return this._photometricScale * this.intensity;
  21810. };
  21811. /**
  21812. * Returns a new Light object, named "name", from the current one.
  21813. * @param name The name of the cloned light
  21814. * @returns the new created light
  21815. */
  21816. Light.prototype.clone = function (name) {
  21817. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21818. if (!constructor) {
  21819. return null;
  21820. }
  21821. return BABYLON.SerializationHelper.Clone(constructor, this);
  21822. };
  21823. /**
  21824. * Serializes the current light into a Serialization object.
  21825. * @returns the serialized object.
  21826. */
  21827. Light.prototype.serialize = function () {
  21828. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21829. // Type
  21830. serializationObject.type = this.getTypeID();
  21831. // Parent
  21832. if (this.parent) {
  21833. serializationObject.parentId = this.parent.id;
  21834. }
  21835. // Inclusion / exclusions
  21836. if (this.excludedMeshes.length > 0) {
  21837. serializationObject.excludedMeshesIds = [];
  21838. this.excludedMeshes.forEach(function (mesh) {
  21839. serializationObject.excludedMeshesIds.push(mesh.id);
  21840. });
  21841. }
  21842. if (this.includedOnlyMeshes.length > 0) {
  21843. serializationObject.includedOnlyMeshesIds = [];
  21844. this.includedOnlyMeshes.forEach(function (mesh) {
  21845. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21846. });
  21847. }
  21848. // Animations
  21849. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21850. serializationObject.ranges = this.serializeAnimationRanges();
  21851. return serializationObject;
  21852. };
  21853. /**
  21854. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21855. * This new light is named "name" and added to the passed scene.
  21856. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21857. * @param name The friendly name of the light
  21858. * @param scene The scene the new light will belong to
  21859. * @returns the constructor function
  21860. */
  21861. Light.GetConstructorFromName = function (type, name, scene) {
  21862. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  21863. if (constructorFunc) {
  21864. return constructorFunc;
  21865. }
  21866. // Default to no light for none present once.
  21867. return null;
  21868. };
  21869. /**
  21870. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21871. * @param parsedLight The JSON representation of the light
  21872. * @param scene The scene to create the parsed light in
  21873. * @returns the created light after parsing
  21874. */
  21875. Light.Parse = function (parsedLight, scene) {
  21876. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21877. if (!constructor) {
  21878. return null;
  21879. }
  21880. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21881. // Inclusion / exclusions
  21882. if (parsedLight.excludedMeshesIds) {
  21883. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21884. }
  21885. if (parsedLight.includedOnlyMeshesIds) {
  21886. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21887. }
  21888. // Parent
  21889. if (parsedLight.parentId) {
  21890. light._waitingParentId = parsedLight.parentId;
  21891. }
  21892. // Animations
  21893. if (parsedLight.animations) {
  21894. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21895. var parsedAnimation = parsedLight.animations[animationIndex];
  21896. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21897. }
  21898. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21899. }
  21900. if (parsedLight.autoAnimate) {
  21901. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21902. }
  21903. return light;
  21904. };
  21905. Light.prototype._hookArrayForExcluded = function (array) {
  21906. var _this = this;
  21907. var oldPush = array.push;
  21908. array.push = function () {
  21909. var items = [];
  21910. for (var _i = 0; _i < arguments.length; _i++) {
  21911. items[_i] = arguments[_i];
  21912. }
  21913. var result = oldPush.apply(array, items);
  21914. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21915. var item = items_1[_a];
  21916. item._resyncLighSource(_this);
  21917. }
  21918. return result;
  21919. };
  21920. var oldSplice = array.splice;
  21921. array.splice = function (index, deleteCount) {
  21922. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21923. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21924. var item = deleted_1[_i];
  21925. item._resyncLighSource(_this);
  21926. }
  21927. return deleted;
  21928. };
  21929. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21930. var item = array_1[_i];
  21931. item._resyncLighSource(this);
  21932. }
  21933. };
  21934. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21935. var _this = this;
  21936. var oldPush = array.push;
  21937. array.push = function () {
  21938. var items = [];
  21939. for (var _i = 0; _i < arguments.length; _i++) {
  21940. items[_i] = arguments[_i];
  21941. }
  21942. var result = oldPush.apply(array, items);
  21943. _this._resyncMeshes();
  21944. return result;
  21945. };
  21946. var oldSplice = array.splice;
  21947. array.splice = function (index, deleteCount) {
  21948. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21949. _this._resyncMeshes();
  21950. return deleted;
  21951. };
  21952. this._resyncMeshes();
  21953. };
  21954. Light.prototype._resyncMeshes = function () {
  21955. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21956. var mesh = _a[_i];
  21957. mesh._resyncLighSource(this);
  21958. }
  21959. };
  21960. /**
  21961. * Forces the meshes to update their light related information in their rendering used effects
  21962. * @hidden Internal Use Only
  21963. */
  21964. Light.prototype._markMeshesAsLightDirty = function () {
  21965. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21966. var mesh = _a[_i];
  21967. if (mesh._lightSources.indexOf(this) !== -1) {
  21968. mesh._markSubMeshesAsLightDirty();
  21969. }
  21970. }
  21971. };
  21972. /**
  21973. * Recomputes the cached photometric scale if needed.
  21974. */
  21975. Light.prototype._computePhotometricScale = function () {
  21976. this._photometricScale = this._getPhotometricScale();
  21977. this.getScene().resetCachedMaterial();
  21978. };
  21979. /**
  21980. * Returns the Photometric Scale according to the light type and intensity mode.
  21981. */
  21982. Light.prototype._getPhotometricScale = function () {
  21983. var photometricScale = 0.0;
  21984. var lightTypeID = this.getTypeID();
  21985. //get photometric mode
  21986. var photometricMode = this.intensityMode;
  21987. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21988. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21989. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21990. }
  21991. else {
  21992. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21993. }
  21994. }
  21995. //compute photometric scale
  21996. switch (lightTypeID) {
  21997. case Light.LIGHTTYPEID_POINTLIGHT:
  21998. case Light.LIGHTTYPEID_SPOTLIGHT:
  21999. switch (photometricMode) {
  22000. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22001. photometricScale = 1.0 / (4.0 * Math.PI);
  22002. break;
  22003. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22004. photometricScale = 1.0;
  22005. break;
  22006. case Light.INTENSITYMODE_LUMINANCE:
  22007. photometricScale = this.radius * this.radius;
  22008. break;
  22009. }
  22010. break;
  22011. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22012. switch (photometricMode) {
  22013. case Light.INTENSITYMODE_ILLUMINANCE:
  22014. photometricScale = 1.0;
  22015. break;
  22016. case Light.INTENSITYMODE_LUMINANCE:
  22017. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22018. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22019. var apexAngleRadians = this.radius;
  22020. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22021. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22022. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22023. photometricScale = solidAngle;
  22024. break;
  22025. }
  22026. break;
  22027. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22028. // No fall off in hemisperic light.
  22029. photometricScale = 1.0;
  22030. break;
  22031. }
  22032. return photometricScale;
  22033. };
  22034. /**
  22035. * Reorder the light in the scene according to their defined priority.
  22036. * @hidden Internal Use Only
  22037. */
  22038. Light.prototype._reorderLightsInScene = function () {
  22039. var scene = this.getScene();
  22040. if (this._renderPriority != 0) {
  22041. scene.requireLightSorting = true;
  22042. }
  22043. this.getScene().sortLightsByPriority();
  22044. };
  22045. /**
  22046. * Falloff Default: light is falling off following the material specification:
  22047. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  22048. */
  22049. Light.FALLOFF_DEFAULT = 0;
  22050. /**
  22051. * Falloff Physical: light is falling off following the inverse squared distance law.
  22052. */
  22053. Light.FALLOFF_PHYSICAL = 1;
  22054. /**
  22055. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  22056. * to enhance interoperability with other engines.
  22057. */
  22058. Light.FALLOFF_GLTF = 2;
  22059. /**
  22060. * Falloff Standard: light is falling off like in the standard material
  22061. * to enhance interoperability with other materials.
  22062. */
  22063. Light.FALLOFF_STANDARD = 3;
  22064. //lightmapMode Consts
  22065. /**
  22066. * If every light affecting the material is in this lightmapMode,
  22067. * material.lightmapTexture adds or multiplies
  22068. * (depends on material.useLightmapAsShadowmap)
  22069. * after every other light calculations.
  22070. */
  22071. Light.LIGHTMAP_DEFAULT = 0;
  22072. /**
  22073. * material.lightmapTexture as only diffuse lighting from this light
  22074. * adds only specular lighting from this light
  22075. * adds dynamic shadows
  22076. */
  22077. Light.LIGHTMAP_SPECULAR = 1;
  22078. /**
  22079. * material.lightmapTexture as only lighting
  22080. * no light calculation from this light
  22081. * only adds dynamic shadows from this light
  22082. */
  22083. Light.LIGHTMAP_SHADOWSONLY = 2;
  22084. // Intensity Mode Consts
  22085. /**
  22086. * Each light type uses the default quantity according to its type:
  22087. * point/spot lights use luminous intensity
  22088. * directional lights use illuminance
  22089. */
  22090. Light.INTENSITYMODE_AUTOMATIC = 0;
  22091. /**
  22092. * lumen (lm)
  22093. */
  22094. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  22095. /**
  22096. * candela (lm/sr)
  22097. */
  22098. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22099. /**
  22100. * lux (lm/m^2)
  22101. */
  22102. Light.INTENSITYMODE_ILLUMINANCE = 3;
  22103. /**
  22104. * nit (cd/m^2)
  22105. */
  22106. Light.INTENSITYMODE_LUMINANCE = 4;
  22107. // Light types ids const.
  22108. /**
  22109. * Light type const id of the point light.
  22110. */
  22111. Light.LIGHTTYPEID_POINTLIGHT = 0;
  22112. /**
  22113. * Light type const id of the directional light.
  22114. */
  22115. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22116. /**
  22117. * Light type const id of the spot light.
  22118. */
  22119. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  22120. /**
  22121. * Light type const id of the hemispheric light.
  22122. */
  22123. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22124. __decorate([
  22125. BABYLON.serializeAsColor3()
  22126. ], Light.prototype, "diffuse", void 0);
  22127. __decorate([
  22128. BABYLON.serializeAsColor3()
  22129. ], Light.prototype, "specular", void 0);
  22130. __decorate([
  22131. BABYLON.serialize()
  22132. ], Light.prototype, "falloffType", void 0);
  22133. __decorate([
  22134. BABYLON.serialize()
  22135. ], Light.prototype, "intensity", void 0);
  22136. __decorate([
  22137. BABYLON.serialize()
  22138. ], Light.prototype, "range", null);
  22139. __decorate([
  22140. BABYLON.serialize()
  22141. ], Light.prototype, "intensityMode", null);
  22142. __decorate([
  22143. BABYLON.serialize()
  22144. ], Light.prototype, "radius", null);
  22145. __decorate([
  22146. BABYLON.serialize()
  22147. ], Light.prototype, "_renderPriority", void 0);
  22148. __decorate([
  22149. BABYLON.expandToProperty("_reorderLightsInScene")
  22150. ], Light.prototype, "renderPriority", void 0);
  22151. __decorate([
  22152. BABYLON.serialize("shadowEnabled")
  22153. ], Light.prototype, "_shadowEnabled", void 0);
  22154. __decorate([
  22155. BABYLON.serialize("excludeWithLayerMask")
  22156. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22157. __decorate([
  22158. BABYLON.serialize("includeOnlyWithLayerMask")
  22159. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22160. __decorate([
  22161. BABYLON.serialize("lightmapMode")
  22162. ], Light.prototype, "_lightmapMode", void 0);
  22163. return Light;
  22164. }(BABYLON.Node));
  22165. BABYLON.Light = Light;
  22166. })(BABYLON || (BABYLON = {}));
  22167. //# sourceMappingURL=babylon.light.js.map
  22168. var BABYLON;
  22169. (function (BABYLON) {
  22170. var Camera = /** @class */ (function (_super) {
  22171. __extends(Camera, _super);
  22172. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22173. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22174. var _this = _super.call(this, name, scene) || this;
  22175. /**
  22176. * The vector the camera should consider as up.
  22177. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22178. */
  22179. _this.upVector = BABYLON.Vector3.Up();
  22180. _this.orthoLeft = null;
  22181. _this.orthoRight = null;
  22182. _this.orthoBottom = null;
  22183. _this.orthoTop = null;
  22184. /**
  22185. * FOV is set in Radians. (default is 0.8)
  22186. */
  22187. _this.fov = 0.8;
  22188. _this.minZ = 1;
  22189. _this.maxZ = 10000.0;
  22190. _this.inertia = 0.9;
  22191. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22192. _this.isIntermediate = false;
  22193. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22194. /**
  22195. * Restricts the camera to viewing objects with the same layerMask.
  22196. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22197. */
  22198. _this.layerMask = 0x0FFFFFFF;
  22199. /**
  22200. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22201. */
  22202. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22203. // Camera rig members
  22204. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22205. /** @hidden */
  22206. _this._rigCameras = new Array();
  22207. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22208. /** @hidden */
  22209. _this._skipRendering = false;
  22210. _this.customRenderTargets = new Array();
  22211. // Observables
  22212. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22213. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22214. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22215. _this.onRestoreStateObservable = new BABYLON.Observable();
  22216. // Cache
  22217. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22218. _this._projectionMatrix = new BABYLON.Matrix();
  22219. _this._doNotComputeProjectionMatrix = false;
  22220. _this._worldMatrix = BABYLON.Matrix.Identity();
  22221. _this._postProcesses = new Array();
  22222. _this._transformMatrix = BABYLON.Matrix.Zero();
  22223. _this._activeMeshes = new BABYLON.SmartArray(256);
  22224. _this._globalPosition = BABYLON.Vector3.Zero();
  22225. _this._refreshFrustumPlanes = true;
  22226. _this.getScene().addCamera(_this);
  22227. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22228. _this.getScene().activeCamera = _this;
  22229. }
  22230. _this.position = position;
  22231. return _this;
  22232. }
  22233. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22234. get: function () {
  22235. return Camera._PERSPECTIVE_CAMERA;
  22236. },
  22237. enumerable: true,
  22238. configurable: true
  22239. });
  22240. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22241. get: function () {
  22242. return Camera._ORTHOGRAPHIC_CAMERA;
  22243. },
  22244. enumerable: true,
  22245. configurable: true
  22246. });
  22247. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22248. /**
  22249. * This is the default FOV mode for perspective cameras.
  22250. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22251. *
  22252. */
  22253. get: function () {
  22254. return Camera._FOVMODE_VERTICAL_FIXED;
  22255. },
  22256. enumerable: true,
  22257. configurable: true
  22258. });
  22259. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22260. /**
  22261. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22262. *
  22263. */
  22264. get: function () {
  22265. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22266. },
  22267. enumerable: true,
  22268. configurable: true
  22269. });
  22270. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22271. get: function () {
  22272. return Camera._RIG_MODE_NONE;
  22273. },
  22274. enumerable: true,
  22275. configurable: true
  22276. });
  22277. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22278. get: function () {
  22279. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22280. },
  22281. enumerable: true,
  22282. configurable: true
  22283. });
  22284. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22285. get: function () {
  22286. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22287. },
  22288. enumerable: true,
  22289. configurable: true
  22290. });
  22291. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22292. get: function () {
  22293. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22294. },
  22295. enumerable: true,
  22296. configurable: true
  22297. });
  22298. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22299. get: function () {
  22300. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22301. },
  22302. enumerable: true,
  22303. configurable: true
  22304. });
  22305. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22306. get: function () {
  22307. return Camera._RIG_MODE_VR;
  22308. },
  22309. enumerable: true,
  22310. configurable: true
  22311. });
  22312. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22313. get: function () {
  22314. return Camera._RIG_MODE_WEBVR;
  22315. },
  22316. enumerable: true,
  22317. configurable: true
  22318. });
  22319. /**
  22320. * Store current camera state (fov, position, etc..)
  22321. */
  22322. Camera.prototype.storeState = function () {
  22323. this._stateStored = true;
  22324. this._storedFov = this.fov;
  22325. return this;
  22326. };
  22327. /**
  22328. * Restores the camera state values if it has been stored. You must call storeState() first
  22329. */
  22330. Camera.prototype._restoreStateValues = function () {
  22331. if (!this._stateStored) {
  22332. return false;
  22333. }
  22334. this.fov = this._storedFov;
  22335. return true;
  22336. };
  22337. /**
  22338. * Restored camera state. You must call storeState() first
  22339. */
  22340. Camera.prototype.restoreState = function () {
  22341. if (this._restoreStateValues()) {
  22342. this.onRestoreStateObservable.notifyObservers(this);
  22343. return true;
  22344. }
  22345. return false;
  22346. };
  22347. Camera.prototype.getClassName = function () {
  22348. return "Camera";
  22349. };
  22350. /**
  22351. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22352. */
  22353. Camera.prototype.toString = function (fullDetails) {
  22354. var ret = "Name: " + this.name;
  22355. ret += ", type: " + this.getClassName();
  22356. if (this.animations) {
  22357. for (var i = 0; i < this.animations.length; i++) {
  22358. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22359. }
  22360. }
  22361. if (fullDetails) {
  22362. }
  22363. return ret;
  22364. };
  22365. Object.defineProperty(Camera.prototype, "globalPosition", {
  22366. get: function () {
  22367. return this._globalPosition;
  22368. },
  22369. enumerable: true,
  22370. configurable: true
  22371. });
  22372. Camera.prototype.getActiveMeshes = function () {
  22373. return this._activeMeshes;
  22374. };
  22375. Camera.prototype.isActiveMesh = function (mesh) {
  22376. return (this._activeMeshes.indexOf(mesh) !== -1);
  22377. };
  22378. /**
  22379. * Is this camera ready to be used/rendered
  22380. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22381. * @return true if the camera is ready
  22382. */
  22383. Camera.prototype.isReady = function (completeCheck) {
  22384. if (completeCheck === void 0) { completeCheck = false; }
  22385. if (completeCheck) {
  22386. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22387. var pp = _a[_i];
  22388. if (pp && !pp.isReady()) {
  22389. return false;
  22390. }
  22391. }
  22392. }
  22393. return _super.prototype.isReady.call(this, completeCheck);
  22394. };
  22395. //Cache
  22396. /** @hidden */
  22397. Camera.prototype._initCache = function () {
  22398. _super.prototype._initCache.call(this);
  22399. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22400. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22401. this._cache.mode = undefined;
  22402. this._cache.minZ = undefined;
  22403. this._cache.maxZ = undefined;
  22404. this._cache.fov = undefined;
  22405. this._cache.fovMode = undefined;
  22406. this._cache.aspectRatio = undefined;
  22407. this._cache.orthoLeft = undefined;
  22408. this._cache.orthoRight = undefined;
  22409. this._cache.orthoBottom = undefined;
  22410. this._cache.orthoTop = undefined;
  22411. this._cache.renderWidth = undefined;
  22412. this._cache.renderHeight = undefined;
  22413. };
  22414. /** @hidden */
  22415. Camera.prototype._updateCache = function (ignoreParentClass) {
  22416. if (!ignoreParentClass) {
  22417. _super.prototype._updateCache.call(this);
  22418. }
  22419. this._cache.position.copyFrom(this.position);
  22420. this._cache.upVector.copyFrom(this.upVector);
  22421. };
  22422. // Synchronized
  22423. /** @hidden */
  22424. Camera.prototype._isSynchronized = function () {
  22425. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22426. };
  22427. /** @hidden */
  22428. Camera.prototype._isSynchronizedViewMatrix = function () {
  22429. if (!_super.prototype._isSynchronized.call(this))
  22430. return false;
  22431. return this._cache.position.equals(this.position)
  22432. && this._cache.upVector.equals(this.upVector)
  22433. && this.isSynchronizedWithParent();
  22434. };
  22435. /** @hidden */
  22436. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22437. var check = this._cache.mode === this.mode
  22438. && this._cache.minZ === this.minZ
  22439. && this._cache.maxZ === this.maxZ;
  22440. if (!check) {
  22441. return false;
  22442. }
  22443. var engine = this.getEngine();
  22444. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22445. check = this._cache.fov === this.fov
  22446. && this._cache.fovMode === this.fovMode
  22447. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22448. }
  22449. else {
  22450. check = this._cache.orthoLeft === this.orthoLeft
  22451. && this._cache.orthoRight === this.orthoRight
  22452. && this._cache.orthoBottom === this.orthoBottom
  22453. && this._cache.orthoTop === this.orthoTop
  22454. && this._cache.renderWidth === engine.getRenderWidth()
  22455. && this._cache.renderHeight === engine.getRenderHeight();
  22456. }
  22457. return check;
  22458. };
  22459. // Controls
  22460. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22461. };
  22462. Camera.prototype.detachControl = function (element) {
  22463. };
  22464. Camera.prototype.update = function () {
  22465. this._checkInputs();
  22466. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22467. this._updateRigCameras();
  22468. }
  22469. };
  22470. /** @hidden */
  22471. Camera.prototype._checkInputs = function () {
  22472. this.onAfterCheckInputsObservable.notifyObservers(this);
  22473. };
  22474. Object.defineProperty(Camera.prototype, "rigCameras", {
  22475. get: function () {
  22476. return this._rigCameras;
  22477. },
  22478. enumerable: true,
  22479. configurable: true
  22480. });
  22481. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22482. get: function () {
  22483. return this._rigPostProcess;
  22484. },
  22485. enumerable: true,
  22486. configurable: true
  22487. });
  22488. /**
  22489. * Internal, gets the first post proces.
  22490. * @returns the first post process to be run on this camera.
  22491. */
  22492. Camera.prototype._getFirstPostProcess = function () {
  22493. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22494. if (this._postProcesses[ppIndex] !== null) {
  22495. return this._postProcesses[ppIndex];
  22496. }
  22497. }
  22498. return null;
  22499. };
  22500. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22501. // invalidate framebuffer
  22502. var firstPostProcess = this._getFirstPostProcess();
  22503. if (firstPostProcess) {
  22504. firstPostProcess.markTextureDirty();
  22505. }
  22506. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22507. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22508. var cam = this._rigCameras[i];
  22509. var rigPostProcess = cam._rigPostProcess;
  22510. // for VR rig, there does not have to be a post process
  22511. if (rigPostProcess) {
  22512. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22513. if (isPass) {
  22514. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22515. cam.isIntermediate = this._postProcesses.length === 0;
  22516. }
  22517. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22518. rigPostProcess.markTextureDirty();
  22519. }
  22520. else {
  22521. cam._postProcesses = this._postProcesses.slice(0);
  22522. }
  22523. }
  22524. };
  22525. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22526. if (insertAt === void 0) { insertAt = null; }
  22527. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22528. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22529. return 0;
  22530. }
  22531. if (insertAt == null || insertAt < 0) {
  22532. this._postProcesses.push(postProcess);
  22533. }
  22534. else if (this._postProcesses[insertAt] === null) {
  22535. this._postProcesses[insertAt] = postProcess;
  22536. }
  22537. else {
  22538. this._postProcesses.splice(insertAt, 0, postProcess);
  22539. }
  22540. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22541. return this._postProcesses.indexOf(postProcess);
  22542. };
  22543. Camera.prototype.detachPostProcess = function (postProcess) {
  22544. var idx = this._postProcesses.indexOf(postProcess);
  22545. if (idx !== -1) {
  22546. this._postProcesses[idx] = null;
  22547. }
  22548. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22549. };
  22550. Camera.prototype.getWorldMatrix = function () {
  22551. if (this._isSynchronizedViewMatrix()) {
  22552. return this._worldMatrix;
  22553. }
  22554. // Getting the the view matrix will also compute the world matrix.
  22555. this.getViewMatrix();
  22556. return this._worldMatrix;
  22557. };
  22558. /** @hidden */
  22559. Camera.prototype._getViewMatrix = function () {
  22560. return BABYLON.Matrix.Identity();
  22561. };
  22562. Camera.prototype.getViewMatrix = function (force) {
  22563. if (!force && this._isSynchronizedViewMatrix()) {
  22564. return this._computedViewMatrix;
  22565. }
  22566. this.updateCache();
  22567. this._computedViewMatrix = this._getViewMatrix();
  22568. this._currentRenderId = this.getScene().getRenderId();
  22569. this._childRenderId = this._currentRenderId;
  22570. this._refreshFrustumPlanes = true;
  22571. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22572. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22573. }
  22574. this.onViewMatrixChangedObservable.notifyObservers(this);
  22575. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22576. return this._computedViewMatrix;
  22577. };
  22578. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22579. this._doNotComputeProjectionMatrix = true;
  22580. if (projection !== undefined) {
  22581. this._projectionMatrix = projection;
  22582. }
  22583. };
  22584. ;
  22585. Camera.prototype.unfreezeProjectionMatrix = function () {
  22586. this._doNotComputeProjectionMatrix = false;
  22587. };
  22588. ;
  22589. Camera.prototype.getProjectionMatrix = function (force) {
  22590. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22591. return this._projectionMatrix;
  22592. }
  22593. // Cache
  22594. this._cache.mode = this.mode;
  22595. this._cache.minZ = this.minZ;
  22596. this._cache.maxZ = this.maxZ;
  22597. // Matrix
  22598. this._refreshFrustumPlanes = true;
  22599. var engine = this.getEngine();
  22600. var scene = this.getScene();
  22601. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22602. this._cache.fov = this.fov;
  22603. this._cache.fovMode = this.fovMode;
  22604. this._cache.aspectRatio = engine.getAspectRatio(this);
  22605. if (this.minZ <= 0) {
  22606. this.minZ = 0.1;
  22607. }
  22608. if (scene.useRightHandedSystem) {
  22609. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22610. }
  22611. else {
  22612. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22613. }
  22614. }
  22615. else {
  22616. var halfWidth = engine.getRenderWidth() / 2.0;
  22617. var halfHeight = engine.getRenderHeight() / 2.0;
  22618. if (scene.useRightHandedSystem) {
  22619. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22620. }
  22621. else {
  22622. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22623. }
  22624. this._cache.orthoLeft = this.orthoLeft;
  22625. this._cache.orthoRight = this.orthoRight;
  22626. this._cache.orthoBottom = this.orthoBottom;
  22627. this._cache.orthoTop = this.orthoTop;
  22628. this._cache.renderWidth = engine.getRenderWidth();
  22629. this._cache.renderHeight = engine.getRenderHeight();
  22630. }
  22631. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22632. return this._projectionMatrix;
  22633. };
  22634. /**
  22635. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  22636. * @returns a Matrix
  22637. */
  22638. Camera.prototype.getTransformationMatrix = function () {
  22639. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22640. return this._transformMatrix;
  22641. };
  22642. Camera.prototype.updateFrustumPlanes = function () {
  22643. if (!this._refreshFrustumPlanes) {
  22644. return;
  22645. }
  22646. this.getTransformationMatrix();
  22647. if (!this._frustumPlanes) {
  22648. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22649. }
  22650. else {
  22651. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22652. }
  22653. this._refreshFrustumPlanes = false;
  22654. };
  22655. Camera.prototype.isInFrustum = function (target) {
  22656. this.updateFrustumPlanes();
  22657. return target.isInFrustum(this._frustumPlanes);
  22658. };
  22659. Camera.prototype.isCompletelyInFrustum = function (target) {
  22660. this.updateFrustumPlanes();
  22661. return target.isCompletelyInFrustum(this._frustumPlanes);
  22662. };
  22663. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22664. if (length === void 0) { length = 100; }
  22665. if (!transform) {
  22666. transform = this.getWorldMatrix();
  22667. }
  22668. if (!origin) {
  22669. origin = this.position;
  22670. }
  22671. var forward = new BABYLON.Vector3(0, 0, 1);
  22672. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22673. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22674. return new BABYLON.Ray(origin, direction, length);
  22675. };
  22676. /**
  22677. * Releases resources associated with this node.
  22678. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22679. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22680. */
  22681. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22682. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22683. // Observables
  22684. this.onViewMatrixChangedObservable.clear();
  22685. this.onProjectionMatrixChangedObservable.clear();
  22686. this.onAfterCheckInputsObservable.clear();
  22687. this.onRestoreStateObservable.clear();
  22688. // Inputs
  22689. if (this.inputs) {
  22690. this.inputs.clear();
  22691. }
  22692. // Animations
  22693. this.getScene().stopAnimation(this);
  22694. // Remove from scene
  22695. this.getScene().removeCamera(this);
  22696. while (this._rigCameras.length > 0) {
  22697. var camera = this._rigCameras.pop();
  22698. if (camera) {
  22699. camera.dispose();
  22700. }
  22701. }
  22702. // Postprocesses
  22703. if (this._rigPostProcess) {
  22704. this._rigPostProcess.dispose(this);
  22705. this._rigPostProcess = null;
  22706. this._postProcesses = [];
  22707. }
  22708. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22709. this._rigPostProcess = null;
  22710. this._postProcesses = [];
  22711. }
  22712. else {
  22713. var i = this._postProcesses.length;
  22714. while (--i >= 0) {
  22715. var postProcess = this._postProcesses[i];
  22716. if (postProcess) {
  22717. postProcess.dispose(this);
  22718. }
  22719. }
  22720. }
  22721. // Render targets
  22722. var i = this.customRenderTargets.length;
  22723. while (--i >= 0) {
  22724. this.customRenderTargets[i].dispose();
  22725. }
  22726. this.customRenderTargets = [];
  22727. // Active Meshes
  22728. this._activeMeshes.dispose();
  22729. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22730. };
  22731. Object.defineProperty(Camera.prototype, "leftCamera", {
  22732. // ---- Camera rigs section ----
  22733. get: function () {
  22734. if (this._rigCameras.length < 1) {
  22735. return null;
  22736. }
  22737. return this._rigCameras[0];
  22738. },
  22739. enumerable: true,
  22740. configurable: true
  22741. });
  22742. Object.defineProperty(Camera.prototype, "rightCamera", {
  22743. get: function () {
  22744. if (this._rigCameras.length < 2) {
  22745. return null;
  22746. }
  22747. return this._rigCameras[1];
  22748. },
  22749. enumerable: true,
  22750. configurable: true
  22751. });
  22752. Camera.prototype.getLeftTarget = function () {
  22753. if (this._rigCameras.length < 1) {
  22754. return null;
  22755. }
  22756. return this._rigCameras[0].getTarget();
  22757. };
  22758. Camera.prototype.getRightTarget = function () {
  22759. if (this._rigCameras.length < 2) {
  22760. return null;
  22761. }
  22762. return this._rigCameras[1].getTarget();
  22763. };
  22764. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22765. if (this.cameraRigMode === mode) {
  22766. return;
  22767. }
  22768. while (this._rigCameras.length > 0) {
  22769. var camera = this._rigCameras.pop();
  22770. if (camera) {
  22771. camera.dispose();
  22772. }
  22773. }
  22774. this.cameraRigMode = mode;
  22775. this._cameraRigParams = {};
  22776. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22777. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22778. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22779. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22780. // create the rig cameras, unless none
  22781. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22782. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22783. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22784. if (leftCamera && rightCamera) {
  22785. this._rigCameras.push(leftCamera);
  22786. this._rigCameras.push(rightCamera);
  22787. }
  22788. }
  22789. switch (this.cameraRigMode) {
  22790. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22791. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22792. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22793. break;
  22794. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22795. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22796. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22797. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22798. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22799. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22800. break;
  22801. case Camera.RIG_MODE_VR:
  22802. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22803. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22804. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22805. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22806. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22807. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22808. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22809. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22810. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22811. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22812. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22813. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22814. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22815. if (metrics.compensateDistortion) {
  22816. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22817. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22818. }
  22819. break;
  22820. case Camera.RIG_MODE_WEBVR:
  22821. if (rigParams.vrDisplay) {
  22822. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22823. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22824. //Left eye
  22825. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22826. this._rigCameras[0].setCameraRigParameter("left", true);
  22827. //leaving this for future reference
  22828. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22829. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22830. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22831. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22832. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22833. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22834. this._rigCameras[0].parent = this;
  22835. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22836. //Right eye
  22837. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22838. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22839. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22840. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22841. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22842. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22843. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22844. this._rigCameras[1].parent = this;
  22845. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22846. if (Camera.UseAlternateWebVRRendering) {
  22847. this._rigCameras[1]._skipRendering = true;
  22848. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22849. }
  22850. }
  22851. break;
  22852. }
  22853. this._cascadePostProcessesToRigCams();
  22854. this.update();
  22855. };
  22856. Camera.prototype._getVRProjectionMatrix = function () {
  22857. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22858. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22859. return this._projectionMatrix;
  22860. };
  22861. Camera.prototype._updateCameraRotationMatrix = function () {
  22862. //Here for WebVR
  22863. };
  22864. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22865. //Here for WebVR
  22866. };
  22867. /**
  22868. * This function MUST be overwritten by the different WebVR cameras available.
  22869. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22870. */
  22871. Camera.prototype._getWebVRProjectionMatrix = function () {
  22872. return BABYLON.Matrix.Identity();
  22873. };
  22874. /**
  22875. * This function MUST be overwritten by the different WebVR cameras available.
  22876. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22877. */
  22878. Camera.prototype._getWebVRViewMatrix = function () {
  22879. return BABYLON.Matrix.Identity();
  22880. };
  22881. Camera.prototype.setCameraRigParameter = function (name, value) {
  22882. if (!this._cameraRigParams) {
  22883. this._cameraRigParams = {};
  22884. }
  22885. this._cameraRigParams[name] = value;
  22886. //provisionnally:
  22887. if (name === "interaxialDistance") {
  22888. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22889. }
  22890. };
  22891. /**
  22892. * needs to be overridden by children so sub has required properties to be copied
  22893. */
  22894. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22895. return null;
  22896. };
  22897. /**
  22898. * May need to be overridden by children
  22899. * @hidden
  22900. */
  22901. Camera.prototype._updateRigCameras = function () {
  22902. for (var i = 0; i < this._rigCameras.length; i++) {
  22903. this._rigCameras[i].minZ = this.minZ;
  22904. this._rigCameras[i].maxZ = this.maxZ;
  22905. this._rigCameras[i].fov = this.fov;
  22906. }
  22907. // only update viewport when ANAGLYPH
  22908. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22909. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22910. }
  22911. };
  22912. /** @hidden */
  22913. Camera.prototype._setupInputs = function () {
  22914. };
  22915. Camera.prototype.serialize = function () {
  22916. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22917. // Type
  22918. serializationObject.type = this.getClassName();
  22919. // Parent
  22920. if (this.parent) {
  22921. serializationObject.parentId = this.parent.id;
  22922. }
  22923. if (this.inputs) {
  22924. this.inputs.serialize(serializationObject);
  22925. }
  22926. // Animations
  22927. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22928. serializationObject.ranges = this.serializeAnimationRanges();
  22929. return serializationObject;
  22930. };
  22931. Camera.prototype.clone = function (name) {
  22932. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22933. };
  22934. Camera.prototype.getDirection = function (localAxis) {
  22935. var result = BABYLON.Vector3.Zero();
  22936. this.getDirectionToRef(localAxis, result);
  22937. return result;
  22938. };
  22939. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22940. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22941. };
  22942. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22943. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22944. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22945. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  22946. interaxial_distance: interaxial_distance,
  22947. isStereoscopicSideBySide: isStereoscopicSideBySide
  22948. });
  22949. if (constructorFunc) {
  22950. return constructorFunc;
  22951. }
  22952. // Default to universal camera
  22953. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22954. };
  22955. Camera.prototype.computeWorldMatrix = function () {
  22956. return this.getWorldMatrix();
  22957. };
  22958. Camera.Parse = function (parsedCamera, scene) {
  22959. var type = parsedCamera.type;
  22960. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22961. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22962. // Parent
  22963. if (parsedCamera.parentId) {
  22964. camera._waitingParentId = parsedCamera.parentId;
  22965. }
  22966. //If camera has an input manager, let it parse inputs settings
  22967. if (camera.inputs) {
  22968. camera.inputs.parse(parsedCamera);
  22969. camera._setupInputs();
  22970. }
  22971. if (camera.setPosition) { // need to force position
  22972. camera.position.copyFromFloats(0, 0, 0);
  22973. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22974. }
  22975. // Target
  22976. if (parsedCamera.target) {
  22977. if (camera.setTarget) {
  22978. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22979. }
  22980. }
  22981. // Apply 3d rig, when found
  22982. if (parsedCamera.cameraRigMode) {
  22983. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22984. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22985. }
  22986. // Animations
  22987. if (parsedCamera.animations) {
  22988. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22989. var parsedAnimation = parsedCamera.animations[animationIndex];
  22990. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22991. }
  22992. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22993. }
  22994. if (parsedCamera.autoAnimate) {
  22995. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22996. }
  22997. return camera;
  22998. };
  22999. // Statics
  23000. Camera._PERSPECTIVE_CAMERA = 0;
  23001. Camera._ORTHOGRAPHIC_CAMERA = 1;
  23002. Camera._FOVMODE_VERTICAL_FIXED = 0;
  23003. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  23004. Camera._RIG_MODE_NONE = 0;
  23005. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23006. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23007. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23008. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23009. Camera._RIG_MODE_VR = 20;
  23010. Camera._RIG_MODE_WEBVR = 21;
  23011. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23012. Camera.UseAlternateWebVRRendering = false;
  23013. __decorate([
  23014. BABYLON.serializeAsVector3()
  23015. ], Camera.prototype, "position", void 0);
  23016. __decorate([
  23017. BABYLON.serializeAsVector3()
  23018. ], Camera.prototype, "upVector", void 0);
  23019. __decorate([
  23020. BABYLON.serialize()
  23021. ], Camera.prototype, "orthoLeft", void 0);
  23022. __decorate([
  23023. BABYLON.serialize()
  23024. ], Camera.prototype, "orthoRight", void 0);
  23025. __decorate([
  23026. BABYLON.serialize()
  23027. ], Camera.prototype, "orthoBottom", void 0);
  23028. __decorate([
  23029. BABYLON.serialize()
  23030. ], Camera.prototype, "orthoTop", void 0);
  23031. __decorate([
  23032. BABYLON.serialize()
  23033. ], Camera.prototype, "fov", void 0);
  23034. __decorate([
  23035. BABYLON.serialize()
  23036. ], Camera.prototype, "minZ", void 0);
  23037. __decorate([
  23038. BABYLON.serialize()
  23039. ], Camera.prototype, "maxZ", void 0);
  23040. __decorate([
  23041. BABYLON.serialize()
  23042. ], Camera.prototype, "inertia", void 0);
  23043. __decorate([
  23044. BABYLON.serialize()
  23045. ], Camera.prototype, "mode", void 0);
  23046. __decorate([
  23047. BABYLON.serialize()
  23048. ], Camera.prototype, "layerMask", void 0);
  23049. __decorate([
  23050. BABYLON.serialize()
  23051. ], Camera.prototype, "fovMode", void 0);
  23052. __decorate([
  23053. BABYLON.serialize()
  23054. ], Camera.prototype, "cameraRigMode", void 0);
  23055. __decorate([
  23056. BABYLON.serialize()
  23057. ], Camera.prototype, "interaxialDistance", void 0);
  23058. __decorate([
  23059. BABYLON.serialize()
  23060. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23061. return Camera;
  23062. }(BABYLON.Node));
  23063. BABYLON.Camera = Camera;
  23064. })(BABYLON || (BABYLON = {}));
  23065. //# sourceMappingURL=babylon.camera.js.map
  23066. var BABYLON;
  23067. (function (BABYLON) {
  23068. var RenderingManager = /** @class */ (function () {
  23069. function RenderingManager(scene) {
  23070. /**
  23071. * @hidden
  23072. */
  23073. this._useSceneAutoClearSetup = false;
  23074. this._renderingGroups = new Array();
  23075. this._autoClearDepthStencil = {};
  23076. this._customOpaqueSortCompareFn = {};
  23077. this._customAlphaTestSortCompareFn = {};
  23078. this._customTransparentSortCompareFn = {};
  23079. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  23080. this._scene = scene;
  23081. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23082. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23083. }
  23084. }
  23085. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23086. if (depth === void 0) { depth = true; }
  23087. if (stencil === void 0) { stencil = true; }
  23088. if (this._depthStencilBufferAlreadyCleaned) {
  23089. return;
  23090. }
  23091. this._scene.getEngine().clear(null, false, depth, stencil);
  23092. this._depthStencilBufferAlreadyCleaned = true;
  23093. };
  23094. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23095. // Update the observable context (not null as it only goes away on dispose)
  23096. var info = this._renderingGroupInfo;
  23097. info.scene = this._scene;
  23098. info.camera = this._scene.activeCamera;
  23099. // Dispatch sprites
  23100. if (renderSprites) {
  23101. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23102. var manager = this._scene.spriteManagers[index];
  23103. this.dispatchSprites(manager);
  23104. }
  23105. }
  23106. // Render
  23107. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23108. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23109. var renderingGroup = this._renderingGroups[index];
  23110. if (!renderingGroup)
  23111. continue;
  23112. var renderingGroupMask = Math.pow(2, index);
  23113. info.renderingGroupId = index;
  23114. // Before Observable
  23115. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23116. // Clear depth/stencil if needed
  23117. if (RenderingManager.AUTOCLEAR) {
  23118. var autoClear = this._useSceneAutoClearSetup ?
  23119. this._scene.getAutoClearDepthStencilSetup(index) :
  23120. this._autoClearDepthStencil[index];
  23121. if (autoClear && autoClear.autoClear) {
  23122. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23123. }
  23124. }
  23125. // Render
  23126. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  23127. var step = _a[_i];
  23128. step.action(index);
  23129. }
  23130. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23131. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  23132. var step = _c[_b];
  23133. step.action(index);
  23134. }
  23135. // After Observable
  23136. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  23137. }
  23138. };
  23139. RenderingManager.prototype.reset = function () {
  23140. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23141. var renderingGroup = this._renderingGroups[index];
  23142. if (renderingGroup) {
  23143. renderingGroup.prepare();
  23144. }
  23145. }
  23146. };
  23147. RenderingManager.prototype.dispose = function () {
  23148. this.freeRenderingGroups();
  23149. this._renderingGroups.length = 0;
  23150. this._renderingGroupInfo = null;
  23151. };
  23152. /**
  23153. * Clear the info related to rendering groups preventing retention points during dispose.
  23154. */
  23155. RenderingManager.prototype.freeRenderingGroups = function () {
  23156. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23157. var renderingGroup = this._renderingGroups[index];
  23158. if (renderingGroup) {
  23159. renderingGroup.dispose();
  23160. }
  23161. }
  23162. };
  23163. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23164. if (this._renderingGroups[renderingGroupId] === undefined) {
  23165. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23166. }
  23167. };
  23168. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23169. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23170. this._prepareRenderingGroup(renderingGroupId);
  23171. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23172. };
  23173. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23174. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23175. this._prepareRenderingGroup(renderingGroupId);
  23176. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23177. };
  23178. /**
  23179. * @param subMesh The submesh to dispatch
  23180. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23181. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23182. */
  23183. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23184. if (mesh === undefined) {
  23185. mesh = subMesh.getMesh();
  23186. }
  23187. var renderingGroupId = mesh.renderingGroupId || 0;
  23188. this._prepareRenderingGroup(renderingGroupId);
  23189. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23190. };
  23191. /**
  23192. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23193. * This allowed control for front to back rendering or reversly depending of the special needs.
  23194. *
  23195. * @param renderingGroupId The rendering group id corresponding to its index
  23196. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23197. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23198. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23199. */
  23200. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23201. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23202. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23203. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23204. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23205. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23206. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23207. if (this._renderingGroups[renderingGroupId]) {
  23208. var group = this._renderingGroups[renderingGroupId];
  23209. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23210. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23211. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23212. }
  23213. };
  23214. /**
  23215. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23216. *
  23217. * @param renderingGroupId The rendering group id corresponding to its index
  23218. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23219. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23220. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23221. */
  23222. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23223. if (depth === void 0) { depth = true; }
  23224. if (stencil === void 0) { stencil = true; }
  23225. this._autoClearDepthStencil[renderingGroupId] = {
  23226. autoClear: autoClearDepthStencil,
  23227. depth: depth,
  23228. stencil: stencil
  23229. };
  23230. };
  23231. /**
  23232. * Gets the current auto clear configuration for one rendering group of the rendering
  23233. * manager.
  23234. * @param index the rendering group index to get the information for
  23235. * @returns The auto clear setup for the requested rendering group
  23236. */
  23237. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  23238. return this._autoClearDepthStencil[index];
  23239. };
  23240. /**
  23241. * The max id used for rendering groups (not included)
  23242. */
  23243. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23244. /**
  23245. * The min id used for rendering groups (included)
  23246. */
  23247. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23248. /**
  23249. * Used to globally prevent autoclearing scenes.
  23250. */
  23251. RenderingManager.AUTOCLEAR = true;
  23252. return RenderingManager;
  23253. }());
  23254. BABYLON.RenderingManager = RenderingManager;
  23255. })(BABYLON || (BABYLON = {}));
  23256. //# sourceMappingURL=babylon.renderingManager.js.map
  23257. var BABYLON;
  23258. (function (BABYLON) {
  23259. var RenderingGroup = /** @class */ (function () {
  23260. /**
  23261. * Creates a new rendering group.
  23262. * @param index The rendering group index
  23263. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23264. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23265. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23266. */
  23267. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23268. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23269. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23270. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23271. this.index = index;
  23272. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23273. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23274. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23275. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23276. this._particleSystems = new BABYLON.SmartArray(256);
  23277. this._spriteManagers = new BABYLON.SmartArray(256);
  23278. this._edgesRenderers = new BABYLON.SmartArray(16);
  23279. this._scene = scene;
  23280. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23281. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23282. this.transparentSortCompareFn = transparentSortCompareFn;
  23283. }
  23284. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23285. /**
  23286. * Set the opaque sort comparison function.
  23287. * If null the sub meshes will be render in the order they were created
  23288. */
  23289. set: function (value) {
  23290. this._opaqueSortCompareFn = value;
  23291. if (value) {
  23292. this._renderOpaque = this.renderOpaqueSorted;
  23293. }
  23294. else {
  23295. this._renderOpaque = RenderingGroup.renderUnsorted;
  23296. }
  23297. },
  23298. enumerable: true,
  23299. configurable: true
  23300. });
  23301. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23302. /**
  23303. * Set the alpha test sort comparison function.
  23304. * If null the sub meshes will be render in the order they were created
  23305. */
  23306. set: function (value) {
  23307. this._alphaTestSortCompareFn = value;
  23308. if (value) {
  23309. this._renderAlphaTest = this.renderAlphaTestSorted;
  23310. }
  23311. else {
  23312. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23313. }
  23314. },
  23315. enumerable: true,
  23316. configurable: true
  23317. });
  23318. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23319. /**
  23320. * Set the transparent sort comparison function.
  23321. * If null the sub meshes will be render in the order they were created
  23322. */
  23323. set: function (value) {
  23324. if (value) {
  23325. this._transparentSortCompareFn = value;
  23326. }
  23327. else {
  23328. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23329. }
  23330. this._renderTransparent = this.renderTransparentSorted;
  23331. },
  23332. enumerable: true,
  23333. configurable: true
  23334. });
  23335. /**
  23336. * Render all the sub meshes contained in the group.
  23337. * @param customRenderFunction Used to override the default render behaviour of the group.
  23338. * @returns true if rendered some submeshes.
  23339. */
  23340. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23341. if (customRenderFunction) {
  23342. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23343. return;
  23344. }
  23345. var engine = this._scene.getEngine();
  23346. // Depth only
  23347. if (this._depthOnlySubMeshes.length !== 0) {
  23348. engine.setColorWrite(false);
  23349. this._renderAlphaTest(this._depthOnlySubMeshes);
  23350. engine.setColorWrite(true);
  23351. }
  23352. // Opaque
  23353. if (this._opaqueSubMeshes.length !== 0) {
  23354. this._renderOpaque(this._opaqueSubMeshes);
  23355. }
  23356. // Alpha test
  23357. if (this._alphaTestSubMeshes.length !== 0) {
  23358. this._renderAlphaTest(this._alphaTestSubMeshes);
  23359. }
  23360. var stencilState = engine.getStencilBuffer();
  23361. engine.setStencilBuffer(false);
  23362. // Sprites
  23363. if (renderSprites) {
  23364. this._renderSprites();
  23365. }
  23366. // Particles
  23367. if (renderParticles) {
  23368. this._renderParticles(activeMeshes);
  23369. }
  23370. if (this.onBeforeTransparentRendering) {
  23371. this.onBeforeTransparentRendering();
  23372. }
  23373. // Transparent
  23374. if (this._transparentSubMeshes.length !== 0) {
  23375. this._renderTransparent(this._transparentSubMeshes);
  23376. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23377. }
  23378. // Set back stencil to false in case it changes before the edge renderer.
  23379. engine.setStencilBuffer(false);
  23380. // Edges
  23381. if (this._edgesRenderers.length) {
  23382. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23383. this._edgesRenderers.data[edgesRendererIndex].render();
  23384. }
  23385. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23386. }
  23387. // Restore Stencil state.
  23388. engine.setStencilBuffer(stencilState);
  23389. };
  23390. /**
  23391. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23392. * @param subMeshes The submeshes to render
  23393. */
  23394. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23395. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23396. };
  23397. /**
  23398. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23399. * @param subMeshes The submeshes to render
  23400. */
  23401. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23402. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23403. };
  23404. /**
  23405. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23406. * @param subMeshes The submeshes to render
  23407. */
  23408. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23409. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23410. };
  23411. /**
  23412. * Renders the submeshes in a specified order.
  23413. * @param subMeshes The submeshes to sort before render
  23414. * @param sortCompareFn The comparison function use to sort
  23415. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23416. * @param transparent Specifies to activate blending if true
  23417. */
  23418. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23419. var subIndex = 0;
  23420. var subMesh;
  23421. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23422. for (; subIndex < subMeshes.length; subIndex++) {
  23423. subMesh = subMeshes.data[subIndex];
  23424. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23425. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23426. }
  23427. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23428. if (sortCompareFn) {
  23429. sortedArray.sort(sortCompareFn);
  23430. }
  23431. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23432. subMesh = sortedArray[subIndex];
  23433. if (transparent) {
  23434. var material = subMesh.getMaterial();
  23435. if (material && material.needDepthPrePass) {
  23436. var engine = material.getScene().getEngine();
  23437. engine.setColorWrite(false);
  23438. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23439. subMesh.render(false);
  23440. engine.setColorWrite(true);
  23441. }
  23442. }
  23443. subMesh.render(transparent);
  23444. }
  23445. };
  23446. /**
  23447. * Renders the submeshes in the order they were dispatched (no sort applied).
  23448. * @param subMeshes The submeshes to render
  23449. */
  23450. RenderingGroup.renderUnsorted = function (subMeshes) {
  23451. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23452. var submesh = subMeshes.data[subIndex];
  23453. submesh.render(false);
  23454. }
  23455. };
  23456. /**
  23457. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23458. * are rendered back to front if in the same alpha index.
  23459. *
  23460. * @param a The first submesh
  23461. * @param b The second submesh
  23462. * @returns The result of the comparison
  23463. */
  23464. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23465. // Alpha index first
  23466. if (a._alphaIndex > b._alphaIndex) {
  23467. return 1;
  23468. }
  23469. if (a._alphaIndex < b._alphaIndex) {
  23470. return -1;
  23471. }
  23472. // Then distance to camera
  23473. return RenderingGroup.backToFrontSortCompare(a, b);
  23474. };
  23475. /**
  23476. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23477. * are rendered back to front.
  23478. *
  23479. * @param a The first submesh
  23480. * @param b The second submesh
  23481. * @returns The result of the comparison
  23482. */
  23483. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23484. // Then distance to camera
  23485. if (a._distanceToCamera < b._distanceToCamera) {
  23486. return 1;
  23487. }
  23488. if (a._distanceToCamera > b._distanceToCamera) {
  23489. return -1;
  23490. }
  23491. return 0;
  23492. };
  23493. /**
  23494. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23495. * are rendered front to back (prevent overdraw).
  23496. *
  23497. * @param a The first submesh
  23498. * @param b The second submesh
  23499. * @returns The result of the comparison
  23500. */
  23501. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23502. // Then distance to camera
  23503. if (a._distanceToCamera < b._distanceToCamera) {
  23504. return -1;
  23505. }
  23506. if (a._distanceToCamera > b._distanceToCamera) {
  23507. return 1;
  23508. }
  23509. return 0;
  23510. };
  23511. /**
  23512. * Resets the different lists of submeshes to prepare a new frame.
  23513. */
  23514. RenderingGroup.prototype.prepare = function () {
  23515. this._opaqueSubMeshes.reset();
  23516. this._transparentSubMeshes.reset();
  23517. this._alphaTestSubMeshes.reset();
  23518. this._depthOnlySubMeshes.reset();
  23519. this._particleSystems.reset();
  23520. this._spriteManagers.reset();
  23521. this._edgesRenderers.reset();
  23522. };
  23523. RenderingGroup.prototype.dispose = function () {
  23524. this._opaqueSubMeshes.dispose();
  23525. this._transparentSubMeshes.dispose();
  23526. this._alphaTestSubMeshes.dispose();
  23527. this._depthOnlySubMeshes.dispose();
  23528. this._particleSystems.dispose();
  23529. this._spriteManagers.dispose();
  23530. this._edgesRenderers.dispose();
  23531. };
  23532. /**
  23533. * Inserts the submesh in its correct queue depending on its material.
  23534. * @param subMesh The submesh to dispatch
  23535. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23536. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23537. */
  23538. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23539. // Get mesh and materials if not provided
  23540. if (mesh === undefined) {
  23541. mesh = subMesh.getMesh();
  23542. }
  23543. if (material === undefined) {
  23544. material = subMesh.getMaterial();
  23545. }
  23546. if (material === null || material === undefined) {
  23547. return;
  23548. }
  23549. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23550. this._transparentSubMeshes.push(subMesh);
  23551. }
  23552. else if (material.needAlphaTesting()) { // Alpha test
  23553. if (material.needDepthPrePass) {
  23554. this._depthOnlySubMeshes.push(subMesh);
  23555. }
  23556. this._alphaTestSubMeshes.push(subMesh);
  23557. }
  23558. else {
  23559. if (material.needDepthPrePass) {
  23560. this._depthOnlySubMeshes.push(subMesh);
  23561. }
  23562. this._opaqueSubMeshes.push(subMesh); // Opaque
  23563. }
  23564. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23565. this._edgesRenderers.push(mesh._edgesRenderer);
  23566. }
  23567. };
  23568. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23569. this._spriteManagers.push(spriteManager);
  23570. };
  23571. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23572. this._particleSystems.push(particleSystem);
  23573. };
  23574. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23575. if (this._particleSystems.length === 0) {
  23576. return;
  23577. }
  23578. // Particles
  23579. var activeCamera = this._scene.activeCamera;
  23580. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23581. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23582. var particleSystem = this._particleSystems.data[particleIndex];
  23583. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23584. continue;
  23585. }
  23586. var emitter = particleSystem.emitter;
  23587. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23588. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23589. }
  23590. }
  23591. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23592. };
  23593. RenderingGroup.prototype._renderSprites = function () {
  23594. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23595. return;
  23596. }
  23597. // Sprites
  23598. var activeCamera = this._scene.activeCamera;
  23599. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23600. for (var id = 0; id < this._spriteManagers.length; id++) {
  23601. var spriteManager = this._spriteManagers.data[id];
  23602. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23603. spriteManager.render();
  23604. }
  23605. }
  23606. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23607. };
  23608. return RenderingGroup;
  23609. }());
  23610. BABYLON.RenderingGroup = RenderingGroup;
  23611. })(BABYLON || (BABYLON = {}));
  23612. //# sourceMappingURL=babylon.renderingGroup.js.map
  23613. var BABYLON;
  23614. (function (BABYLON) {
  23615. /**
  23616. * Groups all the scene component constants in one place to ease maintenance.
  23617. * @hidden
  23618. */
  23619. var SceneComponentConstants = /** @class */ (function () {
  23620. function SceneComponentConstants() {
  23621. }
  23622. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23623. SceneComponentConstants.NAME_LAYER = "Layer";
  23624. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23625. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  23626. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  23627. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  23628. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  23629. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23630. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  23631. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  23632. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  23633. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  23634. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  23635. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  23636. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 0;
  23637. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  23638. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  23639. SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER = 2;
  23640. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 3;
  23641. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 4;
  23642. return SceneComponentConstants;
  23643. }());
  23644. BABYLON.SceneComponentConstants = SceneComponentConstants;
  23645. /**
  23646. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  23647. * @hidden
  23648. */
  23649. var Stage = /** @class */ (function (_super) {
  23650. __extends(Stage, _super);
  23651. /**
  23652. * Hide ctor from the rest of the world.
  23653. * @param items The items to add.
  23654. */
  23655. function Stage(items) {
  23656. return _super.apply(this, items) || this;
  23657. }
  23658. /**
  23659. * Creates a new Stage.
  23660. * @returns A new instance of a Stage
  23661. */
  23662. Stage.Create = function () {
  23663. return Object.create(Stage.prototype);
  23664. };
  23665. /**
  23666. * Registers a step in an ordered way in the targeted stage.
  23667. * @param index Defines the position to register the step in
  23668. * @param component Defines the component attached to the step
  23669. * @param action Defines the action to launch during the step
  23670. */
  23671. Stage.prototype.registerStep = function (index, component, action) {
  23672. var i = 0;
  23673. var maxIndex = Number.MAX_VALUE;
  23674. for (; i < this.length && i < maxIndex; i++) {
  23675. var step = this[i];
  23676. maxIndex = step.index;
  23677. }
  23678. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  23679. };
  23680. /**
  23681. * Clears all the steps from the stage.
  23682. */
  23683. Stage.prototype.clear = function () {
  23684. this.length = 0;
  23685. };
  23686. return Stage;
  23687. }(Array));
  23688. BABYLON.Stage = Stage;
  23689. })(BABYLON || (BABYLON = {}));
  23690. //# sourceMappingURL=babylon.sceneComponent.js.map
  23691. var BABYLON;
  23692. (function (BABYLON) {
  23693. /**
  23694. * Base class of the scene acting as a container for the different elements composing a scene.
  23695. * This class is dynamically extended by the different components of the scene increasing
  23696. * flexibility and reducing coupling
  23697. */
  23698. var AbstractScene = /** @class */ (function () {
  23699. function AbstractScene() {
  23700. /** All of the cameras added to this scene
  23701. * @see http://doc.babylonjs.com/babylon101/cameras
  23702. */
  23703. this.cameras = new Array();
  23704. /**
  23705. * All of the lights added to this scene
  23706. * @see http://doc.babylonjs.com/babylon101/lights
  23707. */
  23708. this.lights = new Array();
  23709. /**
  23710. * All of the (abstract) meshes added to this scene
  23711. */
  23712. this.meshes = new Array();
  23713. /**
  23714. * The list of skeletons added to the scene
  23715. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23716. */
  23717. this.skeletons = new Array();
  23718. /**
  23719. * All of the particle systems added to this scene
  23720. * @see http://doc.babylonjs.com/babylon101/particles
  23721. */
  23722. this.particleSystems = new Array();
  23723. /**
  23724. * Gets a list of Animations associated with the scene
  23725. */
  23726. this.animations = [];
  23727. /**
  23728. * All of the animation groups added to this scene
  23729. * @see http://doc.babylonjs.com/how_to/group
  23730. */
  23731. this.animationGroups = new Array();
  23732. /**
  23733. * All of the multi-materials added to this scene
  23734. * @see http://doc.babylonjs.com/how_to/multi_materials
  23735. */
  23736. this.multiMaterials = new Array();
  23737. /**
  23738. * All of the materials added to this scene
  23739. * @see http://doc.babylonjs.com/babylon101/materials
  23740. */
  23741. this.materials = new Array();
  23742. /**
  23743. * The list of morph target managers added to the scene
  23744. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23745. */
  23746. this.morphTargetManagers = new Array();
  23747. /**
  23748. * The list of geometries used in the scene.
  23749. */
  23750. this.geometries = new Array();
  23751. /**
  23752. * All of the tranform nodes added to this scene
  23753. * @see http://doc.babylonjs.com/how_to/transformnode
  23754. */
  23755. this.transformNodes = new Array();
  23756. /**
  23757. * ActionManagers available on the scene.
  23758. */
  23759. this.actionManagers = new Array();
  23760. /**
  23761. * Sounds to keep.
  23762. */
  23763. this.sounds = new Array();
  23764. /**
  23765. * Textures to keep.
  23766. */
  23767. this.textures = new Array();
  23768. }
  23769. /**
  23770. * Adds a parser in the list of available ones
  23771. * @param name Defines the name of the parser
  23772. * @param parser Defines the parser to add
  23773. */
  23774. AbstractScene.AddParser = function (name, parser) {
  23775. this._BabylonFileParsers[name] = parser;
  23776. };
  23777. /**
  23778. * Gets a general parser from the list of avaialble ones
  23779. * @param name Defines the name of the parser
  23780. * @returns the requested parser or null
  23781. */
  23782. AbstractScene.GetParser = function (name) {
  23783. if (this._BabylonFileParsers[name]) {
  23784. return this._BabylonFileParsers[name];
  23785. }
  23786. return null;
  23787. };
  23788. /**
  23789. * Adds n individual parser in the list of available ones
  23790. * @param name Defines the name of the parser
  23791. * @param parser Defines the parser to add
  23792. */
  23793. AbstractScene.AddIndividualParser = function (name, parser) {
  23794. this._IndividualBabylonFileParsers[name] = parser;
  23795. };
  23796. /**
  23797. * Gets an individual parser from the list of avaialble ones
  23798. * @param name Defines the name of the parser
  23799. * @returns the requested parser or null
  23800. */
  23801. AbstractScene.GetIndividualParser = function (name) {
  23802. if (this._IndividualBabylonFileParsers[name]) {
  23803. return this._IndividualBabylonFileParsers[name];
  23804. }
  23805. return null;
  23806. };
  23807. /**
  23808. * Parser json data and populate both a scene and its associated container object
  23809. * @param jsonData Defines the data to parse
  23810. * @param scene Defines the scene to parse the data for
  23811. * @param container Defines the container attached to the parsing sequence
  23812. * @param rootUrl Defines the root url of the data
  23813. */
  23814. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  23815. for (var parserName in this._BabylonFileParsers) {
  23816. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  23817. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  23818. }
  23819. }
  23820. };
  23821. /**
  23822. * Stores the list of available parsers in the application.
  23823. */
  23824. AbstractScene._BabylonFileParsers = {};
  23825. /**
  23826. * Stores the list of available individual parsers in the application.
  23827. */
  23828. AbstractScene._IndividualBabylonFileParsers = {};
  23829. return AbstractScene;
  23830. }());
  23831. BABYLON.AbstractScene = AbstractScene;
  23832. })(BABYLON || (BABYLON = {}));
  23833. //# sourceMappingURL=babylon.abstractScene.js.map
  23834. var BABYLON;
  23835. (function (BABYLON) {
  23836. /** @hidden */
  23837. var ClickInfo = /** @class */ (function () {
  23838. function ClickInfo() {
  23839. this._singleClick = false;
  23840. this._doubleClick = false;
  23841. this._hasSwiped = false;
  23842. this._ignore = false;
  23843. }
  23844. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23845. get: function () {
  23846. return this._singleClick;
  23847. },
  23848. set: function (b) {
  23849. this._singleClick = b;
  23850. },
  23851. enumerable: true,
  23852. configurable: true
  23853. });
  23854. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23855. get: function () {
  23856. return this._doubleClick;
  23857. },
  23858. set: function (b) {
  23859. this._doubleClick = b;
  23860. },
  23861. enumerable: true,
  23862. configurable: true
  23863. });
  23864. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23865. get: function () {
  23866. return this._hasSwiped;
  23867. },
  23868. set: function (b) {
  23869. this._hasSwiped = b;
  23870. },
  23871. enumerable: true,
  23872. configurable: true
  23873. });
  23874. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23875. get: function () {
  23876. return this._ignore;
  23877. },
  23878. set: function (b) {
  23879. this._ignore = b;
  23880. },
  23881. enumerable: true,
  23882. configurable: true
  23883. });
  23884. return ClickInfo;
  23885. }());
  23886. /**
  23887. * This class is used by the onRenderingGroupObservable
  23888. */
  23889. var RenderingGroupInfo = /** @class */ (function () {
  23890. function RenderingGroupInfo() {
  23891. }
  23892. return RenderingGroupInfo;
  23893. }());
  23894. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23895. /**
  23896. * Represents a scene to be rendered by the engine.
  23897. * @see http://doc.babylonjs.com/features/scene
  23898. */
  23899. var Scene = /** @class */ (function (_super) {
  23900. __extends(Scene, _super);
  23901. /**
  23902. * Creates a new Scene
  23903. * @param engine defines the engine to use to render this scene
  23904. */
  23905. function Scene(engine) {
  23906. var _this = _super.call(this) || this;
  23907. // Members
  23908. /**
  23909. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23910. */
  23911. _this.autoClear = true;
  23912. /**
  23913. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23914. */
  23915. _this.autoClearDepthAndStencil = true;
  23916. /**
  23917. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23918. */
  23919. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23920. /**
  23921. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23922. */
  23923. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23924. _this._forceWireframe = false;
  23925. _this._forcePointsCloud = false;
  23926. /**
  23927. * Gets or sets a boolean indicating if animations are enabled
  23928. */
  23929. _this.animationsEnabled = true;
  23930. _this._animationPropertiesOverride = null;
  23931. /**
  23932. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23933. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23934. */
  23935. _this.useConstantAnimationDeltaTime = false;
  23936. /**
  23937. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23938. * Please note that it requires to run a ray cast through the scene on every frame
  23939. */
  23940. _this.constantlyUpdateMeshUnderPointer = false;
  23941. /**
  23942. * Defines the HTML cursor to use when hovering over interactive elements
  23943. */
  23944. _this.hoverCursor = "pointer";
  23945. /**
  23946. * Defines the HTML default cursor to use (empty by default)
  23947. */
  23948. _this.defaultCursor = "";
  23949. /**
  23950. * This is used to call preventDefault() on pointer down
  23951. * in order to block unwanted artifacts like system double clicks
  23952. */
  23953. _this.preventDefaultOnPointerDown = true;
  23954. // Metadata
  23955. /**
  23956. * Gets or sets user defined metadata
  23957. */
  23958. _this.metadata = null;
  23959. /**
  23960. * Use this array to add regular expressions used to disable offline support for specific urls
  23961. */
  23962. _this.disableOfflineSupportExceptionRules = new Array();
  23963. /**
  23964. * An event triggered when the scene is disposed.
  23965. */
  23966. _this.onDisposeObservable = new BABYLON.Observable();
  23967. _this._onDisposeObserver = null;
  23968. /**
  23969. * An event triggered before rendering the scene (right after animations and physics)
  23970. */
  23971. _this.onBeforeRenderObservable = new BABYLON.Observable();
  23972. _this._onBeforeRenderObserver = null;
  23973. /**
  23974. * An event triggered after rendering the scene
  23975. */
  23976. _this.onAfterRenderObservable = new BABYLON.Observable();
  23977. _this._onAfterRenderObserver = null;
  23978. /**
  23979. * An event triggered before animating the scene
  23980. */
  23981. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23982. /**
  23983. * An event triggered after animations processing
  23984. */
  23985. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  23986. /**
  23987. * An event triggered before draw calls are ready to be sent
  23988. */
  23989. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23990. /**
  23991. * An event triggered after draw calls have been sent
  23992. */
  23993. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23994. /**
  23995. * An event triggered when physic simulation is about to be run
  23996. */
  23997. _this.onBeforePhysicsObservable = new BABYLON.Observable();
  23998. /**
  23999. * An event triggered when physic simulation has been done
  24000. */
  24001. _this.onAfterPhysicsObservable = new BABYLON.Observable();
  24002. /**
  24003. * An event triggered when the scene is ready
  24004. */
  24005. _this.onReadyObservable = new BABYLON.Observable();
  24006. /**
  24007. * An event triggered before rendering a camera
  24008. */
  24009. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  24010. _this._onBeforeCameraRenderObserver = null;
  24011. /**
  24012. * An event triggered after rendering a camera
  24013. */
  24014. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  24015. _this._onAfterCameraRenderObserver = null;
  24016. /**
  24017. * An event triggered when active meshes evaluation is about to start
  24018. */
  24019. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24020. /**
  24021. * An event triggered when active meshes evaluation is done
  24022. */
  24023. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24024. /**
  24025. * An event triggered when particles rendering is about to start
  24026. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24027. */
  24028. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24029. /**
  24030. * An event triggered when particles rendering is done
  24031. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24032. */
  24033. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24034. /**
  24035. * An event triggered when sprites rendering is about to start
  24036. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  24037. */
  24038. _this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  24039. /**
  24040. * An event triggered when sprites rendering is done
  24041. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  24042. */
  24043. _this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  24044. /**
  24045. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24046. */
  24047. _this.onDataLoadedObservable = new BABYLON.Observable();
  24048. /**
  24049. * An event triggered when a camera is created
  24050. */
  24051. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  24052. /**
  24053. * An event triggered when a camera is removed
  24054. */
  24055. _this.onCameraRemovedObservable = new BABYLON.Observable();
  24056. /**
  24057. * An event triggered when a light is created
  24058. */
  24059. _this.onNewLightAddedObservable = new BABYLON.Observable();
  24060. /**
  24061. * An event triggered when a light is removed
  24062. */
  24063. _this.onLightRemovedObservable = new BABYLON.Observable();
  24064. /**
  24065. * An event triggered when a geometry is created
  24066. */
  24067. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24068. /**
  24069. * An event triggered when a geometry is removed
  24070. */
  24071. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  24072. /**
  24073. * An event triggered when a transform node is created
  24074. */
  24075. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24076. /**
  24077. * An event triggered when a transform node is removed
  24078. */
  24079. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24080. /**
  24081. * An event triggered when a mesh is created
  24082. */
  24083. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  24084. /**
  24085. * An event triggered when a mesh is removed
  24086. */
  24087. _this.onMeshRemovedObservable = new BABYLON.Observable();
  24088. /**
  24089. * An event triggered when render targets are about to be rendered
  24090. * Can happen multiple times per frame.
  24091. */
  24092. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24093. /**
  24094. * An event triggered when render targets were rendered.
  24095. * Can happen multiple times per frame.
  24096. */
  24097. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24098. /**
  24099. * An event triggered before calculating deterministic simulation step
  24100. */
  24101. _this.onBeforeStepObservable = new BABYLON.Observable();
  24102. /**
  24103. * An event triggered after calculating deterministic simulation step
  24104. */
  24105. _this.onAfterStepObservable = new BABYLON.Observable();
  24106. /**
  24107. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  24108. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24109. * 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)
  24110. */
  24111. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  24112. /**
  24113. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  24114. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24115. * 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)
  24116. */
  24117. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  24118. // Animations
  24119. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24120. /**
  24121. * 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).
  24122. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24123. */
  24124. _this.onPrePointerObservable = new BABYLON.Observable();
  24125. /**
  24126. * Observable event triggered each time an input event is received from the rendering canvas
  24127. */
  24128. _this.onPointerObservable = new BABYLON.Observable();
  24129. _this._meshPickProceed = false;
  24130. _this._currentPickResult = null;
  24131. _this._previousPickResult = null;
  24132. _this._totalPointersPressed = 0;
  24133. _this._doubleClickOccured = false;
  24134. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24135. _this.cameraToUseForPointers = null;
  24136. _this._pointerX = 0;
  24137. _this._pointerY = 0;
  24138. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24139. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24140. _this._startingPointerTime = 0;
  24141. _this._previousStartingPointerTime = 0;
  24142. _this._pointerCaptures = {};
  24143. // Deterministic lockstep
  24144. _this._timeAccumulator = 0;
  24145. _this._currentStepId = 0;
  24146. _this._currentInternalStep = 0;
  24147. // Keyboard
  24148. /**
  24149. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24150. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24151. */
  24152. _this.onPreKeyboardObservable = new BABYLON.Observable();
  24153. /**
  24154. * Observable event triggered each time an keyboard event is received from the hosting window
  24155. */
  24156. _this.onKeyboardObservable = new BABYLON.Observable();
  24157. // Coordinates system
  24158. _this._useRightHandedSystem = false;
  24159. // Fog
  24160. _this._fogEnabled = true;
  24161. _this._fogMode = Scene.FOGMODE_NONE;
  24162. /**
  24163. * Gets or sets the fog color to use
  24164. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24165. */
  24166. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24167. /**
  24168. * Gets or sets the fog density to use
  24169. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24170. */
  24171. _this.fogDensity = 0.1;
  24172. /**
  24173. * Gets or sets the fog start distance to use
  24174. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24175. */
  24176. _this.fogStart = 0;
  24177. /**
  24178. * Gets or sets the fog end distance to use
  24179. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24180. */
  24181. _this.fogEnd = 1000.0;
  24182. // Lights
  24183. _this._shadowsEnabled = true;
  24184. _this._lightsEnabled = true;
  24185. /** All of the active cameras added to this scene. */
  24186. _this.activeCameras = new Array();
  24187. // Textures
  24188. _this._texturesEnabled = true;
  24189. // Particles
  24190. /**
  24191. * Gets or sets a boolean indicating if particles are enabled on this scene
  24192. */
  24193. _this.particlesEnabled = true;
  24194. // Sprites
  24195. /**
  24196. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24197. */
  24198. _this.spritesEnabled = true;
  24199. /**
  24200. * All of the sprite managers added to this scene
  24201. * @see http://doc.babylonjs.com/babylon101/sprites
  24202. */
  24203. _this.spriteManagers = new Array();
  24204. // Skeletons
  24205. _this._skeletonsEnabled = true;
  24206. // Lens flares
  24207. /**
  24208. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24209. */
  24210. _this.lensFlaresEnabled = true;
  24211. // Collisions
  24212. /**
  24213. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24214. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24215. */
  24216. _this.collisionsEnabled = true;
  24217. /**
  24218. * Defines the gravity applied to this scene (used only for collisions)
  24219. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24220. */
  24221. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24222. // Postprocesses
  24223. /**
  24224. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24225. */
  24226. _this.postProcessesEnabled = true;
  24227. /**
  24228. * The list of postprocesses added to the scene
  24229. */
  24230. _this.postProcesses = new Array();
  24231. // Customs render targets
  24232. /**
  24233. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24234. */
  24235. _this.renderTargetsEnabled = true;
  24236. /**
  24237. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24238. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24239. */
  24240. _this.dumpNextRenderTargets = false;
  24241. /**
  24242. * The list of user defined render targets added to the scene
  24243. */
  24244. _this.customRenderTargets = new Array();
  24245. /**
  24246. * Gets the list of meshes imported to the scene through SceneLoader
  24247. */
  24248. _this.importedMeshesFiles = new Array();
  24249. // Probes
  24250. /**
  24251. * Gets or sets a boolean indicating if probes are enabled on this scene
  24252. */
  24253. _this.probesEnabled = true;
  24254. /**
  24255. * The list of reflection probes added to the scene
  24256. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24257. */
  24258. _this.reflectionProbes = new Array();
  24259. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24260. // Procedural textures
  24261. /**
  24262. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24263. */
  24264. _this.proceduralTexturesEnabled = true;
  24265. /**
  24266. * The list of procedural textures added to the scene
  24267. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24268. */
  24269. _this.proceduralTextures = new Array();
  24270. /**
  24271. * The list of sound tracks added to the scene
  24272. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24273. */
  24274. _this.soundTracks = new Array();
  24275. _this._audioEnabled = true;
  24276. _this._headphone = false;
  24277. // Performance counters
  24278. _this._totalVertices = new BABYLON.PerfCounter();
  24279. /** @hidden */
  24280. _this._activeIndices = new BABYLON.PerfCounter();
  24281. /** @hidden */
  24282. _this._activeParticles = new BABYLON.PerfCounter();
  24283. /** @hidden */
  24284. _this._activeBones = new BABYLON.PerfCounter();
  24285. _this._animationTime = 0;
  24286. /**
  24287. * Gets or sets a general scale for animation speed
  24288. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24289. */
  24290. _this.animationTimeScale = 1;
  24291. _this._renderId = 0;
  24292. _this._executeWhenReadyTimeoutId = -1;
  24293. _this._intermediateRendering = false;
  24294. _this._viewUpdateFlag = -1;
  24295. _this._projectionUpdateFlag = -1;
  24296. _this._alternateViewUpdateFlag = -1;
  24297. _this._alternateProjectionUpdateFlag = -1;
  24298. /** @hidden */
  24299. _this._toBeDisposed = new BABYLON.SmartArray(256);
  24300. _this._activeRequests = new Array();
  24301. _this._pendingData = new Array();
  24302. _this._isDisposed = false;
  24303. /**
  24304. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24305. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24306. */
  24307. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24308. _this._activeMeshes = new BABYLON.SmartArray(256);
  24309. _this._processedMaterials = new BABYLON.SmartArray(256);
  24310. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24311. /** @hidden */
  24312. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24313. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24314. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24315. /** @hidden */
  24316. _this._activeAnimatables = new Array();
  24317. _this._transformMatrix = BABYLON.Matrix.Zero();
  24318. _this._useAlternateCameraConfiguration = false;
  24319. _this._alternateRendering = false;
  24320. /**
  24321. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24322. * This is useful if there are more lights that the maximum simulteanous authorized
  24323. */
  24324. _this.requireLightSorting = false;
  24325. _this._depthRenderer = {};
  24326. /**
  24327. * @hidden
  24328. * Backing store of defined scene components.
  24329. */
  24330. _this._components = [];
  24331. /**
  24332. * @hidden
  24333. * Backing store of defined scene components.
  24334. */
  24335. _this._serializableComponents = [];
  24336. /**
  24337. * List of components to register on the next registration step.
  24338. */
  24339. _this._transientComponents = [];
  24340. /**
  24341. * @hidden
  24342. * Defines the actions happening before camera updates.
  24343. */
  24344. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  24345. /**
  24346. * @hidden
  24347. * Defines the actions happening during the per mesh ready checks.
  24348. */
  24349. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24350. /**
  24351. * @hidden
  24352. * Defines the actions happening before evaluate active mesh checks.
  24353. */
  24354. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  24355. /**
  24356. * @hidden
  24357. * Defines the actions happening during the evaluate sub mesh checks.
  24358. */
  24359. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  24360. /**
  24361. * @hidden
  24362. * Defines the actions happening during the active mesh stage.
  24363. */
  24364. _this._activeMeshStage = BABYLON.Stage.Create();
  24365. /**
  24366. * @hidden
  24367. * Defines the actions happening during the per camera render target step.
  24368. */
  24369. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24370. /**
  24371. * @hidden
  24372. * Defines the actions happening just before the active camera is drawing.
  24373. */
  24374. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24375. /**
  24376. * Defines the actions happening just before a rendering group is drawing.
  24377. */
  24378. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  24379. /**
  24380. * @hidden
  24381. * Defines the actions happening just after a rendering group has been drawn.
  24382. */
  24383. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  24384. /**
  24385. * @hidden
  24386. * Defines the actions happening just after the active camera has been drawn.
  24387. */
  24388. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24389. _this._activeMeshesFrozen = false;
  24390. /** @hidden */
  24391. _this._allowPostProcessClear = true;
  24392. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24393. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  24394. _this.blockMaterialDirtyMechanism = false;
  24395. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24396. _this._engine.scenes.push(_this);
  24397. _this._uid = null;
  24398. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24399. if (BABYLON.PostProcessManager) {
  24400. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24401. }
  24402. if (BABYLON.OutlineRenderer) {
  24403. _this._outlineRenderer = new BABYLON.OutlineRenderer(_this);
  24404. }
  24405. if (BABYLON.Tools.IsWindowObjectExist()) {
  24406. _this.attachControl();
  24407. }
  24408. //simplification queue
  24409. if (BABYLON.SimplificationQueue) {
  24410. _this.simplificationQueue = new BABYLON.SimplificationQueue();
  24411. }
  24412. //collision coordinator initialization. For now legacy per default.
  24413. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24414. // Uniform Buffer
  24415. _this._createUbo();
  24416. // Default Image processing definition
  24417. if (BABYLON.ImageProcessingConfiguration) {
  24418. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24419. }
  24420. return _this;
  24421. }
  24422. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24423. /**
  24424. * Texture used in all pbr material as the reflection texture.
  24425. * As in the majority of the scene they are the same (exception for multi room and so on),
  24426. * this is easier to reference from here than from all the materials.
  24427. */
  24428. get: function () {
  24429. return this._environmentTexture;
  24430. },
  24431. /**
  24432. * Texture used in all pbr material as the reflection texture.
  24433. * As in the majority of the scene they are the same (exception for multi room and so on),
  24434. * this is easier to set here than in all the materials.
  24435. */
  24436. set: function (value) {
  24437. if (this._environmentTexture === value) {
  24438. return;
  24439. }
  24440. this._environmentTexture = value;
  24441. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24442. },
  24443. enumerable: true,
  24444. configurable: true
  24445. });
  24446. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24447. /**
  24448. * Default image processing configuration used either in the rendering
  24449. * Forward main pass or through the imageProcessingPostProcess if present.
  24450. * As in the majority of the scene they are the same (exception for multi camera),
  24451. * this is easier to reference from here than from all the materials and post process.
  24452. *
  24453. * No setter as we it is a shared configuration, you can set the values instead.
  24454. */
  24455. get: function () {
  24456. return this._imageProcessingConfiguration;
  24457. },
  24458. enumerable: true,
  24459. configurable: true
  24460. });
  24461. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24462. get: function () {
  24463. return this._forceWireframe;
  24464. },
  24465. /**
  24466. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24467. */
  24468. set: function (value) {
  24469. if (this._forceWireframe === value) {
  24470. return;
  24471. }
  24472. this._forceWireframe = value;
  24473. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24474. },
  24475. enumerable: true,
  24476. configurable: true
  24477. });
  24478. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24479. get: function () {
  24480. return this._forcePointsCloud;
  24481. },
  24482. /**
  24483. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24484. */
  24485. set: function (value) {
  24486. if (this._forcePointsCloud === value) {
  24487. return;
  24488. }
  24489. this._forcePointsCloud = value;
  24490. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24491. },
  24492. enumerable: true,
  24493. configurable: true
  24494. });
  24495. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24496. /**
  24497. * Gets or sets the animation properties override
  24498. */
  24499. get: function () {
  24500. return this._animationPropertiesOverride;
  24501. },
  24502. set: function (value) {
  24503. this._animationPropertiesOverride = value;
  24504. },
  24505. enumerable: true,
  24506. configurable: true
  24507. });
  24508. Object.defineProperty(Scene.prototype, "onDispose", {
  24509. /** Sets a function to be executed when this scene is disposed. */
  24510. set: function (callback) {
  24511. if (this._onDisposeObserver) {
  24512. this.onDisposeObservable.remove(this._onDisposeObserver);
  24513. }
  24514. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24515. },
  24516. enumerable: true,
  24517. configurable: true
  24518. });
  24519. Object.defineProperty(Scene.prototype, "beforeRender", {
  24520. /** Sets a function to be executed before rendering this scene */
  24521. set: function (callback) {
  24522. if (this._onBeforeRenderObserver) {
  24523. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24524. }
  24525. if (callback) {
  24526. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24527. }
  24528. },
  24529. enumerable: true,
  24530. configurable: true
  24531. });
  24532. Object.defineProperty(Scene.prototype, "afterRender", {
  24533. /** Sets a function to be executed after rendering this scene */
  24534. set: function (callback) {
  24535. if (this._onAfterRenderObserver) {
  24536. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24537. }
  24538. if (callback) {
  24539. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24540. }
  24541. },
  24542. enumerable: true,
  24543. configurable: true
  24544. });
  24545. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24546. /** Sets a function to be executed before rendering a camera*/
  24547. set: function (callback) {
  24548. if (this._onBeforeCameraRenderObserver) {
  24549. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24550. }
  24551. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24552. },
  24553. enumerable: true,
  24554. configurable: true
  24555. });
  24556. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24557. /** Sets a function to be executed after rendering a camera*/
  24558. set: function (callback) {
  24559. if (this._onAfterCameraRenderObserver) {
  24560. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24561. }
  24562. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24563. },
  24564. enumerable: true,
  24565. configurable: true
  24566. });
  24567. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24568. /**
  24569. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24570. */
  24571. get: function () {
  24572. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24573. },
  24574. enumerable: true,
  24575. configurable: true
  24576. });
  24577. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24578. get: function () {
  24579. return this._useRightHandedSystem;
  24580. },
  24581. /**
  24582. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24583. */
  24584. set: function (value) {
  24585. if (this._useRightHandedSystem === value) {
  24586. return;
  24587. }
  24588. this._useRightHandedSystem = value;
  24589. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24590. },
  24591. enumerable: true,
  24592. configurable: true
  24593. });
  24594. /**
  24595. * Sets the step Id used by deterministic lock step
  24596. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24597. * @param newStepId defines the step Id
  24598. */
  24599. Scene.prototype.setStepId = function (newStepId) {
  24600. this._currentStepId = newStepId;
  24601. };
  24602. ;
  24603. /**
  24604. * Gets the step Id used by deterministic lock step
  24605. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24606. * @returns the step Id
  24607. */
  24608. Scene.prototype.getStepId = function () {
  24609. return this._currentStepId;
  24610. };
  24611. ;
  24612. /**
  24613. * Gets the internal step used by deterministic lock step
  24614. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24615. * @returns the internal step
  24616. */
  24617. Scene.prototype.getInternalStep = function () {
  24618. return this._currentInternalStep;
  24619. };
  24620. ;
  24621. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24622. get: function () {
  24623. return this._fogEnabled;
  24624. },
  24625. /**
  24626. * Gets or sets a boolean indicating if fog is enabled on this scene
  24627. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24628. */
  24629. set: function (value) {
  24630. if (this._fogEnabled === value) {
  24631. return;
  24632. }
  24633. this._fogEnabled = value;
  24634. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24635. },
  24636. enumerable: true,
  24637. configurable: true
  24638. });
  24639. Object.defineProperty(Scene.prototype, "fogMode", {
  24640. get: function () {
  24641. return this._fogMode;
  24642. },
  24643. /**
  24644. * Gets or sets the fog mode to use
  24645. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24646. */
  24647. set: function (value) {
  24648. if (this._fogMode === value) {
  24649. return;
  24650. }
  24651. this._fogMode = value;
  24652. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24653. },
  24654. enumerable: true,
  24655. configurable: true
  24656. });
  24657. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24658. get: function () {
  24659. return this._shadowsEnabled;
  24660. },
  24661. /**
  24662. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24663. */
  24664. set: function (value) {
  24665. if (this._shadowsEnabled === value) {
  24666. return;
  24667. }
  24668. this._shadowsEnabled = value;
  24669. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24670. },
  24671. enumerable: true,
  24672. configurable: true
  24673. });
  24674. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24675. get: function () {
  24676. return this._lightsEnabled;
  24677. },
  24678. /**
  24679. * Gets or sets a boolean indicating if lights are enabled on this scene
  24680. */
  24681. set: function (value) {
  24682. if (this._lightsEnabled === value) {
  24683. return;
  24684. }
  24685. this._lightsEnabled = value;
  24686. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24687. },
  24688. enumerable: true,
  24689. configurable: true
  24690. });
  24691. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24692. /** The default material used on meshes when no material is affected */
  24693. get: function () {
  24694. if (!this._defaultMaterial) {
  24695. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24696. }
  24697. return this._defaultMaterial;
  24698. },
  24699. /** The default material used on meshes when no material is affected */
  24700. set: function (value) {
  24701. this._defaultMaterial = value;
  24702. },
  24703. enumerable: true,
  24704. configurable: true
  24705. });
  24706. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24707. get: function () {
  24708. return this._texturesEnabled;
  24709. },
  24710. /**
  24711. * Gets or sets a boolean indicating if textures are enabled on this scene
  24712. */
  24713. set: function (value) {
  24714. if (this._texturesEnabled === value) {
  24715. return;
  24716. }
  24717. this._texturesEnabled = value;
  24718. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24719. },
  24720. enumerable: true,
  24721. configurable: true
  24722. });
  24723. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24724. get: function () {
  24725. return this._skeletonsEnabled;
  24726. },
  24727. /**
  24728. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24729. */
  24730. set: function (value) {
  24731. if (this._skeletonsEnabled === value) {
  24732. return;
  24733. }
  24734. this._skeletonsEnabled = value;
  24735. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24736. },
  24737. enumerable: true,
  24738. configurable: true
  24739. });
  24740. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24741. /**
  24742. * Gets the postprocess render pipeline manager
  24743. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24744. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24745. */
  24746. get: function () {
  24747. if (!this._postProcessRenderPipelineManager) {
  24748. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24749. }
  24750. return this._postProcessRenderPipelineManager;
  24751. },
  24752. enumerable: true,
  24753. configurable: true
  24754. });
  24755. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24756. /**
  24757. * Gets the main soundtrack associated with the scene
  24758. */
  24759. get: function () {
  24760. if (!this._mainSoundTrack) {
  24761. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24762. }
  24763. return this._mainSoundTrack;
  24764. },
  24765. enumerable: true,
  24766. configurable: true
  24767. });
  24768. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24769. /** @hidden */
  24770. get: function () {
  24771. return this._alternateRendering;
  24772. },
  24773. enumerable: true,
  24774. configurable: true
  24775. });
  24776. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24777. /**
  24778. * Gets the list of frustum planes (built from the active camera)
  24779. */
  24780. get: function () {
  24781. return this._frustumPlanes;
  24782. },
  24783. enumerable: true,
  24784. configurable: true
  24785. });
  24786. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24787. /**
  24788. * Gets the current geometry buffer associated to the scene.
  24789. */
  24790. get: function () {
  24791. return this._geometryBufferRenderer;
  24792. },
  24793. /**
  24794. * Sets the current geometry buffer for the scene.
  24795. */
  24796. set: function (geometryBufferRenderer) {
  24797. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24798. this._geometryBufferRenderer = geometryBufferRenderer;
  24799. }
  24800. },
  24801. enumerable: true,
  24802. configurable: true
  24803. });
  24804. /**
  24805. * Registers the transient components if needed.
  24806. */
  24807. Scene.prototype._registerTransientComponents = function () {
  24808. // Register components that have been associated lately to the scene.
  24809. if (this._transientComponents.length > 0) {
  24810. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  24811. var component = _a[_i];
  24812. component.register();
  24813. }
  24814. this._transientComponents = [];
  24815. }
  24816. };
  24817. /**
  24818. * @hidden
  24819. * Add a component to the scene.
  24820. * Note that the ccomponent could be registered on th next frame if this is called after
  24821. * the register component stage.
  24822. * @param component Defines the component to add to the scene
  24823. */
  24824. Scene.prototype._addComponent = function (component) {
  24825. this._components.push(component);
  24826. this._transientComponents.push(component);
  24827. var serializableComponent = component;
  24828. if (serializableComponent.addFromContainer) {
  24829. this._serializableComponents.push(serializableComponent);
  24830. }
  24831. };
  24832. /**
  24833. * @hidden
  24834. * Gets a component from the scene.
  24835. * @param name defines the name of the component to retrieve
  24836. * @returns the component or null if not present
  24837. */
  24838. Scene.prototype._getComponent = function (name) {
  24839. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  24840. var component = _a[_i];
  24841. if (component.name === name) {
  24842. return component;
  24843. }
  24844. }
  24845. return null;
  24846. };
  24847. Object.defineProperty(Scene.prototype, "debugLayer", {
  24848. /**
  24849. * Gets the debug layer (aka Inspector) associated with the scene
  24850. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24851. */
  24852. get: function () {
  24853. if (!this._debugLayer) {
  24854. this._debugLayer = new BABYLON.DebugLayer(this);
  24855. }
  24856. return this._debugLayer;
  24857. },
  24858. enumerable: true,
  24859. configurable: true
  24860. });
  24861. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24862. /**
  24863. * Gets a boolean indicating if collisions are processed on a web worker
  24864. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24865. */
  24866. get: function () {
  24867. return this._workerCollisions;
  24868. },
  24869. set: function (enabled) {
  24870. if (!BABYLON.CollisionCoordinatorLegacy) {
  24871. return;
  24872. }
  24873. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24874. this._workerCollisions = enabled;
  24875. if (this.collisionCoordinator) {
  24876. this.collisionCoordinator.destroy();
  24877. }
  24878. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24879. this.collisionCoordinator.init(this);
  24880. },
  24881. enumerable: true,
  24882. configurable: true
  24883. });
  24884. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24885. /**
  24886. * Gets the octree used to boost mesh selection (picking)
  24887. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24888. */
  24889. get: function () {
  24890. return this._selectionOctree;
  24891. },
  24892. enumerable: true,
  24893. configurable: true
  24894. });
  24895. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24896. /**
  24897. * Gets the mesh that is currently under the pointer
  24898. */
  24899. get: function () {
  24900. return this._pointerOverMesh;
  24901. },
  24902. enumerable: true,
  24903. configurable: true
  24904. });
  24905. Object.defineProperty(Scene.prototype, "pointerX", {
  24906. /**
  24907. * Gets the current on-screen X position of the pointer
  24908. */
  24909. get: function () {
  24910. return this._pointerX;
  24911. },
  24912. enumerable: true,
  24913. configurable: true
  24914. });
  24915. Object.defineProperty(Scene.prototype, "pointerY", {
  24916. /**
  24917. * Gets the current on-screen Y position of the pointer
  24918. */
  24919. get: function () {
  24920. return this._pointerY;
  24921. },
  24922. enumerable: true,
  24923. configurable: true
  24924. });
  24925. /**
  24926. * Gets the cached material (ie. the latest rendered one)
  24927. * @returns the cached material
  24928. */
  24929. Scene.prototype.getCachedMaterial = function () {
  24930. return this._cachedMaterial;
  24931. };
  24932. /**
  24933. * Gets the cached effect (ie. the latest rendered one)
  24934. * @returns the cached effect
  24935. */
  24936. Scene.prototype.getCachedEffect = function () {
  24937. return this._cachedEffect;
  24938. };
  24939. /**
  24940. * Gets the cached visibility state (ie. the latest rendered one)
  24941. * @returns the cached visibility state
  24942. */
  24943. Scene.prototype.getCachedVisibility = function () {
  24944. return this._cachedVisibility;
  24945. };
  24946. /**
  24947. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24948. * @param material defines the current material
  24949. * @param effect defines the current effect
  24950. * @param visibility defines the current visibility state
  24951. * @returns true if one parameter is not cached
  24952. */
  24953. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24954. if (visibility === void 0) { visibility = 1; }
  24955. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24956. };
  24957. /**
  24958. * Gets the outline renderer associated with the scene
  24959. * @returns a OutlineRenderer
  24960. */
  24961. Scene.prototype.getOutlineRenderer = function () {
  24962. return this._outlineRenderer;
  24963. };
  24964. /**
  24965. * Gets the engine associated with the scene
  24966. * @returns an Engine
  24967. */
  24968. Scene.prototype.getEngine = function () {
  24969. return this._engine;
  24970. };
  24971. /**
  24972. * Gets the total number of vertices rendered per frame
  24973. * @returns the total number of vertices rendered per frame
  24974. */
  24975. Scene.prototype.getTotalVertices = function () {
  24976. return this._totalVertices.current;
  24977. };
  24978. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24979. /**
  24980. * Gets the performance counter for total vertices
  24981. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24982. */
  24983. get: function () {
  24984. return this._totalVertices;
  24985. },
  24986. enumerable: true,
  24987. configurable: true
  24988. });
  24989. /**
  24990. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24991. * @returns the total number of active indices rendered per frame
  24992. */
  24993. Scene.prototype.getActiveIndices = function () {
  24994. return this._activeIndices.current;
  24995. };
  24996. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24997. /**
  24998. * Gets the performance counter for active indices
  24999. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25000. */
  25001. get: function () {
  25002. return this._activeIndices;
  25003. },
  25004. enumerable: true,
  25005. configurable: true
  25006. });
  25007. /**
  25008. * Gets the total number of active particles rendered per frame
  25009. * @returns the total number of active particles rendered per frame
  25010. */
  25011. Scene.prototype.getActiveParticles = function () {
  25012. return this._activeParticles.current;
  25013. };
  25014. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  25015. /**
  25016. * Gets the performance counter for active particles
  25017. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25018. */
  25019. get: function () {
  25020. return this._activeParticles;
  25021. },
  25022. enumerable: true,
  25023. configurable: true
  25024. });
  25025. /**
  25026. * Gets the total number of active bones rendered per frame
  25027. * @returns the total number of active bones rendered per frame
  25028. */
  25029. Scene.prototype.getActiveBones = function () {
  25030. return this._activeBones.current;
  25031. };
  25032. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25033. /**
  25034. * Gets the performance counter for active bones
  25035. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25036. */
  25037. get: function () {
  25038. return this._activeBones;
  25039. },
  25040. enumerable: true,
  25041. configurable: true
  25042. });
  25043. /** @hidden */
  25044. Scene.prototype.getInterFramePerfCounter = function () {
  25045. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25046. return 0;
  25047. };
  25048. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25049. /** @hidden */
  25050. get: function () {
  25051. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25052. return null;
  25053. },
  25054. enumerable: true,
  25055. configurable: true
  25056. });
  25057. /** @hidden */
  25058. Scene.prototype.getLastFrameDuration = function () {
  25059. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25060. return 0;
  25061. };
  25062. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25063. /** @hidden */
  25064. get: function () {
  25065. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25066. return null;
  25067. },
  25068. enumerable: true,
  25069. configurable: true
  25070. });
  25071. /** @hidden */
  25072. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25073. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25074. return 0;
  25075. };
  25076. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25077. /** @hidden */
  25078. get: function () {
  25079. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25080. return null;
  25081. },
  25082. enumerable: true,
  25083. configurable: true
  25084. });
  25085. /**
  25086. * Gets the array of active meshes
  25087. * @returns an array of AbstractMesh
  25088. */
  25089. Scene.prototype.getActiveMeshes = function () {
  25090. return this._activeMeshes;
  25091. };
  25092. /** @hidden */
  25093. Scene.prototype.getRenderTargetsDuration = function () {
  25094. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25095. return 0;
  25096. };
  25097. /** @hidden */
  25098. Scene.prototype.getRenderDuration = function () {
  25099. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25100. return 0;
  25101. };
  25102. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25103. /** @hidden */
  25104. get: function () {
  25105. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25106. return null;
  25107. },
  25108. enumerable: true,
  25109. configurable: true
  25110. });
  25111. /** @hidden */
  25112. Scene.prototype.getParticlesDuration = function () {
  25113. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25114. return 0;
  25115. };
  25116. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25117. /** @hidden */
  25118. get: function () {
  25119. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25120. return null;
  25121. },
  25122. enumerable: true,
  25123. configurable: true
  25124. });
  25125. /** @hidden */
  25126. Scene.prototype.getSpritesDuration = function () {
  25127. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25128. return 0;
  25129. };
  25130. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25131. /** @hidden */
  25132. get: function () {
  25133. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25134. return null;
  25135. },
  25136. enumerable: true,
  25137. configurable: true
  25138. });
  25139. /**
  25140. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25141. * @returns a number
  25142. */
  25143. Scene.prototype.getAnimationRatio = function () {
  25144. return this._animationRatio !== undefined ? this._animationRatio : 1;
  25145. };
  25146. /**
  25147. * Gets an unique Id for the current frame
  25148. * @returns a number
  25149. */
  25150. Scene.prototype.getRenderId = function () {
  25151. return this._renderId;
  25152. };
  25153. /** Call this function if you want to manually increment the render Id*/
  25154. Scene.prototype.incrementRenderId = function () {
  25155. this._renderId++;
  25156. };
  25157. Scene.prototype._updatePointerPosition = function (evt) {
  25158. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25159. if (!canvasRect) {
  25160. return;
  25161. }
  25162. this._pointerX = evt.clientX - canvasRect.left;
  25163. this._pointerY = evt.clientY - canvasRect.top;
  25164. this._unTranslatedPointerX = this._pointerX;
  25165. this._unTranslatedPointerY = this._pointerY;
  25166. };
  25167. Scene.prototype._createUbo = function () {
  25168. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25169. this._sceneUbo.addUniform("viewProjection", 16);
  25170. this._sceneUbo.addUniform("view", 16);
  25171. };
  25172. Scene.prototype._createAlternateUbo = function () {
  25173. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25174. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25175. this._alternateSceneUbo.addUniform("view", 16);
  25176. };
  25177. // Pointers handling
  25178. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  25179. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  25180. if (result) {
  25181. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  25182. }
  25183. return result;
  25184. };
  25185. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25186. if (pointerInfo.pickInfo) {
  25187. if (!pointerInfo.pickInfo.ray) {
  25188. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25189. }
  25190. }
  25191. };
  25192. /**
  25193. * Use this method to simulate a pointer move on a mesh
  25194. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25195. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25196. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25197. * @returns the current scene
  25198. */
  25199. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25200. var evt = new PointerEvent("pointermove", pointerEventInit);
  25201. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25202. return this;
  25203. }
  25204. return this._processPointerMove(pickResult, evt);
  25205. };
  25206. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25207. var canvas = this._engine.getRenderingCanvas();
  25208. if (!canvas) {
  25209. return this;
  25210. }
  25211. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25212. this.setPointerOverSprite(null);
  25213. this.setPointerOverMesh(pickResult.pickedMesh);
  25214. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25215. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25216. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25217. }
  25218. else {
  25219. canvas.style.cursor = this.hoverCursor;
  25220. }
  25221. }
  25222. else {
  25223. canvas.style.cursor = this.defaultCursor;
  25224. }
  25225. }
  25226. else {
  25227. this.setPointerOverMesh(null);
  25228. // Sprites
  25229. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  25230. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25231. this.setPointerOverSprite(pickResult.pickedSprite);
  25232. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  25233. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  25234. }
  25235. else {
  25236. canvas.style.cursor = this.hoverCursor;
  25237. }
  25238. }
  25239. else {
  25240. this.setPointerOverSprite(null);
  25241. // Restore pointer
  25242. canvas.style.cursor = this.defaultCursor;
  25243. }
  25244. }
  25245. if (pickResult) {
  25246. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25247. if (this.onPointerMove) {
  25248. this.onPointerMove(evt, pickResult, type);
  25249. }
  25250. if (this.onPointerObservable.hasObservers()) {
  25251. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25252. this._setRayOnPointerInfo(pi);
  25253. this.onPointerObservable.notifyObservers(pi, type);
  25254. }
  25255. }
  25256. return this;
  25257. };
  25258. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25259. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25260. if (pickResult) {
  25261. pi.ray = pickResult.ray;
  25262. }
  25263. this.onPrePointerObservable.notifyObservers(pi, type);
  25264. if (pi.skipOnPointerObservable) {
  25265. return true;
  25266. }
  25267. else {
  25268. return false;
  25269. }
  25270. };
  25271. /**
  25272. * Use this method to simulate a pointer down on a mesh
  25273. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25274. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25275. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25276. * @returns the current scene
  25277. */
  25278. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25279. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25280. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25281. return this;
  25282. }
  25283. return this._processPointerDown(pickResult, evt);
  25284. };
  25285. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25286. var _this = this;
  25287. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25288. this._pickedDownMesh = pickResult.pickedMesh;
  25289. var actionManager = pickResult.pickedMesh.actionManager;
  25290. if (actionManager) {
  25291. if (actionManager.hasPickTriggers) {
  25292. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25293. switch (evt.button) {
  25294. case 0:
  25295. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25296. break;
  25297. case 1:
  25298. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25299. break;
  25300. case 2:
  25301. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25302. break;
  25303. }
  25304. }
  25305. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25306. window.setTimeout(function () {
  25307. 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);
  25308. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25309. if (_this._totalPointersPressed !== 0 &&
  25310. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25311. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25312. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25313. _this._startingPointerTime = 0;
  25314. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25315. }
  25316. }
  25317. }, Scene.LongPressDelay);
  25318. }
  25319. }
  25320. }
  25321. if (pickResult) {
  25322. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25323. if (this.onPointerDown) {
  25324. this.onPointerDown(evt, pickResult, type);
  25325. }
  25326. if (this.onPointerObservable.hasObservers()) {
  25327. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25328. this._setRayOnPointerInfo(pi);
  25329. this.onPointerObservable.notifyObservers(pi, type);
  25330. }
  25331. }
  25332. return this;
  25333. };
  25334. /**
  25335. * Use this method to simulate a pointer up on a mesh
  25336. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25337. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25338. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25339. * @returns the current scene
  25340. */
  25341. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25342. var evt = new PointerEvent("pointerup", pointerEventInit);
  25343. var clickInfo = new ClickInfo();
  25344. clickInfo.singleClick = true;
  25345. clickInfo.ignore = true;
  25346. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25347. return this;
  25348. }
  25349. return this._processPointerUp(pickResult, evt, clickInfo);
  25350. };
  25351. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25352. if (pickResult && pickResult && pickResult.pickedMesh) {
  25353. this._pickedUpMesh = pickResult.pickedMesh;
  25354. if (this._pickedDownMesh === this._pickedUpMesh) {
  25355. if (this.onPointerPick) {
  25356. this.onPointerPick(evt, pickResult);
  25357. }
  25358. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25359. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25360. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25361. this._setRayOnPointerInfo(pi);
  25362. this.onPointerObservable.notifyObservers(pi, type_1);
  25363. }
  25364. }
  25365. if (pickResult.pickedMesh.actionManager) {
  25366. if (clickInfo.ignore) {
  25367. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25368. }
  25369. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25370. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25371. }
  25372. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25373. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25374. }
  25375. }
  25376. }
  25377. if (this._pickedDownMesh &&
  25378. this._pickedDownMesh.actionManager &&
  25379. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25380. this._pickedDownMesh !== this._pickedUpMesh) {
  25381. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25382. }
  25383. var type = BABYLON.PointerEventTypes.POINTERUP;
  25384. if (this.onPointerObservable.hasObservers()) {
  25385. if (!clickInfo.ignore) {
  25386. if (!clickInfo.hasSwiped) {
  25387. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25388. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25389. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25390. this._setRayOnPointerInfo(pi);
  25391. this.onPointerObservable.notifyObservers(pi, type_2);
  25392. }
  25393. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25394. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25395. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25396. this._setRayOnPointerInfo(pi);
  25397. this.onPointerObservable.notifyObservers(pi, type_3);
  25398. }
  25399. }
  25400. }
  25401. else {
  25402. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25403. this._setRayOnPointerInfo(pi);
  25404. this.onPointerObservable.notifyObservers(pi, type);
  25405. }
  25406. }
  25407. if (this.onPointerUp) {
  25408. this.onPointerUp(evt, pickResult, type);
  25409. }
  25410. return this;
  25411. };
  25412. /**
  25413. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25414. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25415. * @returns true if the pointer was captured
  25416. */
  25417. Scene.prototype.isPointerCaptured = function (pointerId) {
  25418. if (pointerId === void 0) { pointerId = 0; }
  25419. return this._pointerCaptures[pointerId];
  25420. };
  25421. /**
  25422. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25423. * @param attachUp defines if you want to attach events to pointerup
  25424. * @param attachDown defines if you want to attach events to pointerdown
  25425. * @param attachMove defines if you want to attach events to pointermove
  25426. */
  25427. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25428. var _this = this;
  25429. if (attachUp === void 0) { attachUp = true; }
  25430. if (attachDown === void 0) { attachDown = true; }
  25431. if (attachMove === void 0) { attachMove = true; }
  25432. this._initActionManager = function (act, clickInfo) {
  25433. if (!_this._meshPickProceed) {
  25434. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25435. _this._currentPickResult = pickResult;
  25436. if (pickResult) {
  25437. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25438. }
  25439. _this._meshPickProceed = true;
  25440. }
  25441. return act;
  25442. };
  25443. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25444. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25445. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25446. btn !== _this._previousButtonPressed) {
  25447. _this._doubleClickOccured = false;
  25448. clickInfo.singleClick = true;
  25449. clickInfo.ignore = false;
  25450. cb(clickInfo, _this._currentPickResult);
  25451. }
  25452. };
  25453. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25454. var clickInfo = new ClickInfo();
  25455. _this._currentPickResult = null;
  25456. var act = null;
  25457. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25458. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25459. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25460. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25461. act = _this._initActionManager(act, clickInfo);
  25462. if (act)
  25463. checkPicking = act.hasPickTriggers;
  25464. }
  25465. if (checkPicking) {
  25466. var btn = evt.button;
  25467. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25468. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25469. if (!clickInfo.hasSwiped) {
  25470. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25471. if (!checkSingleClickImmediately) {
  25472. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25473. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25474. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25475. act = _this._initActionManager(act, clickInfo);
  25476. if (act)
  25477. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25478. }
  25479. }
  25480. if (checkSingleClickImmediately) {
  25481. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25482. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25483. btn !== _this._previousButtonPressed) {
  25484. clickInfo.singleClick = true;
  25485. cb(clickInfo, _this._currentPickResult);
  25486. }
  25487. }
  25488. // at least one double click is required to be check and exclusive double click is enabled
  25489. else {
  25490. // wait that no double click has been raised during the double click delay
  25491. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25492. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25493. }
  25494. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25495. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25496. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25497. act = _this._initActionManager(act, clickInfo);
  25498. if (act)
  25499. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25500. }
  25501. if (checkDoubleClick) {
  25502. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25503. if (btn === _this._previousButtonPressed &&
  25504. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25505. !_this._doubleClickOccured) {
  25506. // pointer has not moved for 2 clicks, it's a double click
  25507. if (!clickInfo.hasSwiped &&
  25508. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25509. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25510. _this._previousStartingPointerTime = 0;
  25511. _this._doubleClickOccured = true;
  25512. clickInfo.doubleClick = true;
  25513. clickInfo.ignore = false;
  25514. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25515. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25516. }
  25517. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25518. cb(clickInfo, _this._currentPickResult);
  25519. }
  25520. // if the two successive clicks are too far, it's just two simple clicks
  25521. else {
  25522. _this._doubleClickOccured = false;
  25523. _this._previousStartingPointerTime = _this._startingPointerTime;
  25524. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25525. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25526. _this._previousButtonPressed = btn;
  25527. if (Scene.ExclusiveDoubleClickMode) {
  25528. if (_this._previousDelayedSimpleClickTimeout) {
  25529. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25530. }
  25531. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25532. cb(clickInfo, _this._previousPickResult);
  25533. }
  25534. else {
  25535. cb(clickInfo, _this._currentPickResult);
  25536. }
  25537. }
  25538. }
  25539. // just the first click of the double has been raised
  25540. else {
  25541. _this._doubleClickOccured = false;
  25542. _this._previousStartingPointerTime = _this._startingPointerTime;
  25543. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25544. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25545. _this._previousButtonPressed = btn;
  25546. }
  25547. }
  25548. }
  25549. }
  25550. clickInfo.ignore = true;
  25551. cb(clickInfo, _this._currentPickResult);
  25552. };
  25553. this._spritePredicate = function (sprite) {
  25554. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25555. };
  25556. this._onPointerMove = function (evt) {
  25557. _this._updatePointerPosition(evt);
  25558. // PreObservable support
  25559. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25560. return;
  25561. }
  25562. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25563. return;
  25564. }
  25565. if (!_this.pointerMovePredicate) {
  25566. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25567. }
  25568. // Meshes
  25569. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25570. _this._processPointerMove(pickResult, evt);
  25571. };
  25572. this._onPointerDown = function (evt) {
  25573. _this._totalPointersPressed++;
  25574. _this._pickedDownMesh = null;
  25575. _this._meshPickProceed = false;
  25576. _this._updatePointerPosition(evt);
  25577. if (_this.preventDefaultOnPointerDown && canvas) {
  25578. evt.preventDefault();
  25579. canvas.focus();
  25580. }
  25581. // PreObservable support
  25582. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25583. return;
  25584. }
  25585. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25586. return;
  25587. }
  25588. _this._pointerCaptures[evt.pointerId] = true;
  25589. _this._startingPointerPosition.x = _this._pointerX;
  25590. _this._startingPointerPosition.y = _this._pointerY;
  25591. _this._startingPointerTime = Date.now();
  25592. if (!_this.pointerDownPredicate) {
  25593. _this.pointerDownPredicate = function (mesh) {
  25594. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25595. };
  25596. }
  25597. // Meshes
  25598. _this._pickedDownMesh = null;
  25599. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25600. _this._processPointerDown(pickResult, evt);
  25601. // Sprites
  25602. _this._pickedDownSprite = null;
  25603. if (_this.spriteManagers.length > 0) {
  25604. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25605. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25606. if (pickResult.pickedSprite.actionManager) {
  25607. _this._pickedDownSprite = pickResult.pickedSprite;
  25608. switch (evt.button) {
  25609. case 0:
  25610. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25611. break;
  25612. case 1:
  25613. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25614. break;
  25615. case 2:
  25616. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25617. break;
  25618. }
  25619. if (pickResult.pickedSprite.actionManager) {
  25620. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25621. }
  25622. }
  25623. }
  25624. }
  25625. };
  25626. this._onPointerUp = function (evt) {
  25627. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25628. return; // So we need to test it the pointer down was pressed before.
  25629. }
  25630. _this._totalPointersPressed--;
  25631. _this._pickedUpMesh = null;
  25632. _this._meshPickProceed = false;
  25633. _this._updatePointerPosition(evt);
  25634. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25635. // PreObservable support
  25636. if (_this.onPrePointerObservable.hasObservers()) {
  25637. if (!clickInfo.ignore) {
  25638. if (!clickInfo.hasSwiped) {
  25639. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25640. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25641. return;
  25642. }
  25643. }
  25644. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25645. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25646. return;
  25647. }
  25648. }
  25649. }
  25650. }
  25651. else {
  25652. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25653. return;
  25654. }
  25655. }
  25656. }
  25657. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25658. return;
  25659. }
  25660. _this._pointerCaptures[evt.pointerId] = false;
  25661. if (!_this.pointerUpPredicate) {
  25662. _this.pointerUpPredicate = function (mesh) {
  25663. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25664. };
  25665. }
  25666. // Meshes
  25667. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25668. _this._initActionManager(null, clickInfo);
  25669. }
  25670. if (!pickResult) {
  25671. pickResult = _this._currentPickResult;
  25672. }
  25673. _this._processPointerUp(pickResult, evt, clickInfo);
  25674. // Sprites
  25675. if (!clickInfo.ignore) {
  25676. if (_this.spriteManagers.length > 0) {
  25677. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25678. if (spritePickResult) {
  25679. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25680. if (spritePickResult.pickedSprite.actionManager) {
  25681. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25682. if (spritePickResult.pickedSprite.actionManager) {
  25683. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25684. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25685. }
  25686. }
  25687. }
  25688. }
  25689. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25690. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25691. }
  25692. }
  25693. }
  25694. }
  25695. _this._previousPickResult = _this._currentPickResult;
  25696. });
  25697. };
  25698. this._onKeyDown = function (evt) {
  25699. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25700. if (_this.onPreKeyboardObservable.hasObservers()) {
  25701. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25702. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25703. if (pi.skipOnPointerObservable) {
  25704. return;
  25705. }
  25706. }
  25707. if (_this.onKeyboardObservable.hasObservers()) {
  25708. var pi = new BABYLON.KeyboardInfo(type, evt);
  25709. _this.onKeyboardObservable.notifyObservers(pi, type);
  25710. }
  25711. if (_this.actionManager) {
  25712. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25713. }
  25714. };
  25715. this._onKeyUp = function (evt) {
  25716. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25717. if (_this.onPreKeyboardObservable.hasObservers()) {
  25718. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25719. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25720. if (pi.skipOnPointerObservable) {
  25721. return;
  25722. }
  25723. }
  25724. if (_this.onKeyboardObservable.hasObservers()) {
  25725. var pi = new BABYLON.KeyboardInfo(type, evt);
  25726. _this.onKeyboardObservable.notifyObservers(pi, type);
  25727. }
  25728. if (_this.actionManager) {
  25729. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25730. }
  25731. };
  25732. var engine = this.getEngine();
  25733. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25734. if (!canvas) {
  25735. return;
  25736. }
  25737. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25738. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25739. });
  25740. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25741. if (!canvas) {
  25742. return;
  25743. }
  25744. canvas.removeEventListener("keydown", _this._onKeyDown);
  25745. canvas.removeEventListener("keyup", _this._onKeyUp);
  25746. });
  25747. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25748. var canvas = this._engine.getRenderingCanvas();
  25749. if (!canvas) {
  25750. return;
  25751. }
  25752. if (attachMove) {
  25753. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25754. // Wheel
  25755. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25756. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25757. }
  25758. if (attachDown) {
  25759. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25760. }
  25761. if (attachUp) {
  25762. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25763. }
  25764. canvas.tabIndex = 1;
  25765. };
  25766. /** Detaches all event handlers*/
  25767. Scene.prototype.detachControl = function () {
  25768. var engine = this.getEngine();
  25769. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25770. var canvas = engine.getRenderingCanvas();
  25771. if (!canvas) {
  25772. return;
  25773. }
  25774. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25775. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25776. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25777. if (this._onCanvasBlurObserver) {
  25778. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25779. }
  25780. if (this._onCanvasFocusObserver) {
  25781. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25782. }
  25783. // Wheel
  25784. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25785. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25786. // Keyboard
  25787. canvas.removeEventListener("keydown", this._onKeyDown);
  25788. canvas.removeEventListener("keyup", this._onKeyUp);
  25789. // Observables
  25790. this.onKeyboardObservable.clear();
  25791. this.onPreKeyboardObservable.clear();
  25792. this.onPointerObservable.clear();
  25793. this.onPrePointerObservable.clear();
  25794. };
  25795. /**
  25796. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25797. * Delay loaded resources are not taking in account
  25798. * @return true if all required resources are ready
  25799. */
  25800. Scene.prototype.isReady = function () {
  25801. if (this._isDisposed) {
  25802. return false;
  25803. }
  25804. if (this._pendingData.length > 0) {
  25805. return false;
  25806. }
  25807. var index;
  25808. var engine = this.getEngine();
  25809. // Geometries
  25810. for (index = 0; index < this.geometries.length; index++) {
  25811. var geometry = this.geometries[index];
  25812. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25813. return false;
  25814. }
  25815. }
  25816. // Meshes
  25817. for (index = 0; index < this.meshes.length; index++) {
  25818. var mesh = this.meshes[index];
  25819. if (!mesh.isEnabled()) {
  25820. continue;
  25821. }
  25822. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25823. continue;
  25824. }
  25825. if (!mesh.isReady(true)) {
  25826. return false;
  25827. }
  25828. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25829. // Is Ready For Mesh
  25830. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  25831. var step = _a[_i];
  25832. if (!step.action(mesh, hardwareInstancedRendering)) {
  25833. return false;
  25834. }
  25835. }
  25836. }
  25837. // Post-processes
  25838. if (this.activeCameras && this.activeCameras.length > 0) {
  25839. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  25840. var camera = _c[_b];
  25841. if (!camera.isReady(true)) {
  25842. return false;
  25843. }
  25844. }
  25845. }
  25846. else if (this.activeCamera) {
  25847. if (!this.activeCamera.isReady(true)) {
  25848. return false;
  25849. }
  25850. }
  25851. // Particles
  25852. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  25853. var particleSystem = _e[_d];
  25854. if (!particleSystem.isReady()) {
  25855. return false;
  25856. }
  25857. }
  25858. return true;
  25859. };
  25860. /** Resets all cached information relative to material (including effect and visibility) */
  25861. Scene.prototype.resetCachedMaterial = function () {
  25862. this._cachedMaterial = null;
  25863. this._cachedEffect = null;
  25864. this._cachedVisibility = null;
  25865. };
  25866. /**
  25867. * Registers a function to be called before every frame render
  25868. * @param func defines the function to register
  25869. */
  25870. Scene.prototype.registerBeforeRender = function (func) {
  25871. this.onBeforeRenderObservable.add(func);
  25872. };
  25873. /**
  25874. * Unregisters a function called before every frame render
  25875. * @param func defines the function to unregister
  25876. */
  25877. Scene.prototype.unregisterBeforeRender = function (func) {
  25878. this.onBeforeRenderObservable.removeCallback(func);
  25879. };
  25880. /**
  25881. * Registers a function to be called after every frame render
  25882. * @param func defines the function to register
  25883. */
  25884. Scene.prototype.registerAfterRender = function (func) {
  25885. this.onAfterRenderObservable.add(func);
  25886. };
  25887. /**
  25888. * Unregisters a function called after every frame render
  25889. * @param func defines the function to unregister
  25890. */
  25891. Scene.prototype.unregisterAfterRender = function (func) {
  25892. this.onAfterRenderObservable.removeCallback(func);
  25893. };
  25894. Scene.prototype._executeOnceBeforeRender = function (func) {
  25895. var _this = this;
  25896. var execFunc = function () {
  25897. func();
  25898. setTimeout(function () {
  25899. _this.unregisterBeforeRender(execFunc);
  25900. });
  25901. };
  25902. this.registerBeforeRender(execFunc);
  25903. };
  25904. /**
  25905. * The provided function will run before render once and will be disposed afterwards.
  25906. * A timeout delay can be provided so that the function will be executed in N ms.
  25907. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25908. * @param func The function to be executed.
  25909. * @param timeout optional delay in ms
  25910. */
  25911. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25912. var _this = this;
  25913. if (timeout !== undefined) {
  25914. setTimeout(function () {
  25915. _this._executeOnceBeforeRender(func);
  25916. }, timeout);
  25917. }
  25918. else {
  25919. this._executeOnceBeforeRender(func);
  25920. }
  25921. };
  25922. /** @hidden */
  25923. Scene.prototype._addPendingData = function (data) {
  25924. this._pendingData.push(data);
  25925. };
  25926. /** @hidden */
  25927. Scene.prototype._removePendingData = function (data) {
  25928. var wasLoading = this.isLoading;
  25929. var index = this._pendingData.indexOf(data);
  25930. if (index !== -1) {
  25931. this._pendingData.splice(index, 1);
  25932. }
  25933. if (wasLoading && !this.isLoading) {
  25934. this.onDataLoadedObservable.notifyObservers(this);
  25935. }
  25936. };
  25937. /**
  25938. * Returns the number of items waiting to be loaded
  25939. * @returns the number of items waiting to be loaded
  25940. */
  25941. Scene.prototype.getWaitingItemsCount = function () {
  25942. return this._pendingData.length;
  25943. };
  25944. Object.defineProperty(Scene.prototype, "isLoading", {
  25945. /**
  25946. * Returns a boolean indicating if the scene is still loading data
  25947. */
  25948. get: function () {
  25949. return this._pendingData.length > 0;
  25950. },
  25951. enumerable: true,
  25952. configurable: true
  25953. });
  25954. /**
  25955. * Registers a function to be executed when the scene is ready
  25956. * @param {Function} func - the function to be executed
  25957. */
  25958. Scene.prototype.executeWhenReady = function (func) {
  25959. var _this = this;
  25960. this.onReadyObservable.add(func);
  25961. if (this._executeWhenReadyTimeoutId !== -1) {
  25962. return;
  25963. }
  25964. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25965. _this._checkIsReady();
  25966. }, 150);
  25967. };
  25968. /**
  25969. * Returns a promise that resolves when the scene is ready
  25970. * @returns A promise that resolves when the scene is ready
  25971. */
  25972. Scene.prototype.whenReadyAsync = function () {
  25973. var _this = this;
  25974. return new Promise(function (resolve) {
  25975. _this.executeWhenReady(function () {
  25976. resolve();
  25977. });
  25978. });
  25979. };
  25980. /** @hidden */
  25981. Scene.prototype._checkIsReady = function () {
  25982. var _this = this;
  25983. this._registerTransientComponents();
  25984. if (this.isReady()) {
  25985. this.onReadyObservable.notifyObservers(this);
  25986. this.onReadyObservable.clear();
  25987. this._executeWhenReadyTimeoutId = -1;
  25988. return;
  25989. }
  25990. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25991. _this._checkIsReady();
  25992. }, 150);
  25993. };
  25994. // Animations
  25995. /**
  25996. * Will start the animation sequence of a given target
  25997. * @param target defines the target
  25998. * @param from defines from which frame should animation start
  25999. * @param to defines until which frame should animation run.
  26000. * @param weight defines the weight to apply to the animation (1.0 by default)
  26001. * @param loop defines if the animation loops
  26002. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26003. * @param onAnimationEnd defines the function to be executed when the animation ends
  26004. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26005. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  26006. * @returns the animatable object created for this animation
  26007. */
  26008. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  26009. if (weight === void 0) { weight = 1.0; }
  26010. if (speedRatio === void 0) { speedRatio = 1.0; }
  26011. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  26012. returnedAnimatable.weight = weight;
  26013. return returnedAnimatable;
  26014. };
  26015. /**
  26016. * Will start the animation sequence of a given target
  26017. * @param target defines the target
  26018. * @param from defines from which frame should animation start
  26019. * @param to defines until which frame should animation run.
  26020. * @param loop defines if the animation loops
  26021. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26022. * @param onAnimationEnd defines the function to be executed when the animation ends
  26023. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26024. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  26025. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  26026. * @returns the animatable object created for this animation
  26027. */
  26028. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  26029. if (speedRatio === void 0) { speedRatio = 1.0; }
  26030. if (stopCurrent === void 0) { stopCurrent = true; }
  26031. if (from > to && speedRatio > 0) {
  26032. speedRatio *= -1;
  26033. }
  26034. if (stopCurrent) {
  26035. this.stopAnimation(target, undefined, targetMask);
  26036. }
  26037. if (!animatable) {
  26038. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  26039. }
  26040. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  26041. // Local animations
  26042. if (target.animations && shouldRunTargetAnimations) {
  26043. animatable.appendAnimations(target, target.animations);
  26044. }
  26045. // Children animations
  26046. if (target.getAnimatables) {
  26047. var animatables = target.getAnimatables();
  26048. for (var index = 0; index < animatables.length; index++) {
  26049. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  26050. }
  26051. }
  26052. animatable.reset();
  26053. return animatable;
  26054. };
  26055. /**
  26056. * Begin a new animation on a given node
  26057. * @param target defines the target where the animation will take place
  26058. * @param animations defines the list of animations to start
  26059. * @param from defines the initial value
  26060. * @param to defines the final value
  26061. * @param loop defines if you want animation to loop (off by default)
  26062. * @param speedRatio defines the speed ratio to apply to all animations
  26063. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26064. * @returns the list of created animatables
  26065. */
  26066. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26067. if (speedRatio === undefined) {
  26068. speedRatio = 1.0;
  26069. }
  26070. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26071. return animatable;
  26072. };
  26073. /**
  26074. * Begin a new animation on a given node and its hierarchy
  26075. * @param target defines the root node where the animation will take place
  26076. * @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.
  26077. * @param animations defines the list of animations to start
  26078. * @param from defines the initial value
  26079. * @param to defines the final value
  26080. * @param loop defines if you want animation to loop (off by default)
  26081. * @param speedRatio defines the speed ratio to apply to all animations
  26082. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26083. * @returns the list of animatables created for all nodes
  26084. */
  26085. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26086. var children = target.getDescendants(directDescendantsOnly);
  26087. var result = [];
  26088. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26089. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26090. var child = children_1[_i];
  26091. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26092. }
  26093. return result;
  26094. };
  26095. /**
  26096. * Gets the animatable associated with a specific target
  26097. * @param target defines the target of the animatable
  26098. * @returns the required animatable if found
  26099. */
  26100. Scene.prototype.getAnimatableByTarget = function (target) {
  26101. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26102. if (this._activeAnimatables[index].target === target) {
  26103. return this._activeAnimatables[index];
  26104. }
  26105. }
  26106. return null;
  26107. };
  26108. /**
  26109. * Gets all animatables associated with a given target
  26110. * @param target defines the target to look animatables for
  26111. * @returns an array of Animatables
  26112. */
  26113. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26114. var result = [];
  26115. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26116. if (this._activeAnimatables[index].target === target) {
  26117. result.push(this._activeAnimatables[index]);
  26118. }
  26119. }
  26120. return result;
  26121. };
  26122. Object.defineProperty(Scene.prototype, "animatables", {
  26123. /**
  26124. * Gets all animatable attached to the scene
  26125. */
  26126. get: function () {
  26127. return this._activeAnimatables;
  26128. },
  26129. enumerable: true,
  26130. configurable: true
  26131. });
  26132. /**
  26133. * Will stop the animation of the given target
  26134. * @param target - the target
  26135. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  26136. * @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)
  26137. */
  26138. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  26139. var animatables = this.getAllAnimatablesByTarget(target);
  26140. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26141. var animatable = animatables_1[_i];
  26142. animatable.stop(animationName, targetMask);
  26143. }
  26144. };
  26145. /**
  26146. * Stops and removes all animations that have been applied to the scene
  26147. */
  26148. Scene.prototype.stopAllAnimations = function () {
  26149. if (this._activeAnimatables) {
  26150. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26151. this._activeAnimatables[i].stop();
  26152. }
  26153. this._activeAnimatables = [];
  26154. }
  26155. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26156. var group = _a[_i];
  26157. group.stop();
  26158. }
  26159. };
  26160. Scene.prototype._animate = function () {
  26161. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26162. return;
  26163. }
  26164. // Getting time
  26165. var now = BABYLON.Tools.Now;
  26166. if (!this._animationTimeLast) {
  26167. if (this._pendingData.length > 0) {
  26168. return;
  26169. }
  26170. this._animationTimeLast = now;
  26171. }
  26172. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26173. this._animationTime += deltaTime;
  26174. this._animationTimeLast = now;
  26175. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26176. this._activeAnimatables[index]._animate(this._animationTime);
  26177. }
  26178. // Late animation bindings
  26179. this._processLateAnimationBindings();
  26180. };
  26181. /** @hidden */
  26182. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26183. var target = runtimeAnimation.target;
  26184. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26185. if (!target._lateAnimationHolders) {
  26186. target._lateAnimationHolders = {};
  26187. }
  26188. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26189. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26190. totalWeight: 0,
  26191. animations: [],
  26192. originalValue: originalValue
  26193. };
  26194. }
  26195. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26196. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26197. };
  26198. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26199. var normalizer = 1.0;
  26200. var finalPosition = BABYLON.Tmp.Vector3[0];
  26201. var finalScaling = BABYLON.Tmp.Vector3[1];
  26202. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26203. var startIndex = 0;
  26204. var originalAnimation = holder.animations[0];
  26205. var originalValue = holder.originalValue;
  26206. var scale = 1;
  26207. if (holder.totalWeight < 1.0) {
  26208. // We need to mix the original value in
  26209. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26210. scale = 1.0 - holder.totalWeight;
  26211. }
  26212. else {
  26213. startIndex = 1;
  26214. // We need to normalize the weights
  26215. normalizer = holder.totalWeight;
  26216. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26217. scale = originalAnimation.weight / normalizer;
  26218. if (scale == 1) {
  26219. return originalAnimation.currentValue;
  26220. }
  26221. }
  26222. finalScaling.scaleInPlace(scale);
  26223. finalPosition.scaleInPlace(scale);
  26224. finalQuaternion.scaleInPlace(scale);
  26225. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26226. var runtimeAnimation = holder.animations[animIndex];
  26227. var scale = runtimeAnimation.weight / normalizer;
  26228. var currentPosition = BABYLON.Tmp.Vector3[2];
  26229. var currentScaling = BABYLON.Tmp.Vector3[3];
  26230. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26231. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26232. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26233. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26234. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26235. }
  26236. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26237. return originalAnimation._workValue;
  26238. };
  26239. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  26240. var originalAnimation = holder.animations[0];
  26241. var originalValue = holder.originalValue;
  26242. if (holder.animations.length === 1) {
  26243. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  26244. }
  26245. var normalizer = 1.0;
  26246. var quaternions;
  26247. var weights;
  26248. if (holder.totalWeight < 1.0) {
  26249. var scale = 1.0 - holder.totalWeight;
  26250. quaternions = [];
  26251. weights = [];
  26252. quaternions.push(originalValue);
  26253. weights.push(scale);
  26254. }
  26255. else {
  26256. if (holder.animations.length === 2) { // Slerp as soon as we can
  26257. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26258. }
  26259. quaternions = [];
  26260. weights = [];
  26261. normalizer = holder.totalWeight;
  26262. }
  26263. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26264. var runtimeAnimation = holder.animations[animIndex];
  26265. quaternions.push(runtimeAnimation.currentValue);
  26266. weights.push(runtimeAnimation.weight / normalizer);
  26267. }
  26268. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26269. var cumulativeAmount = 0;
  26270. var cumulativeQuaternion = null;
  26271. for (var index = 0; index < quaternions.length;) {
  26272. if (!cumulativeQuaternion) {
  26273. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26274. cumulativeAmount = weights[index] + weights[index + 1];
  26275. index += 2;
  26276. continue;
  26277. }
  26278. cumulativeAmount += weights[index];
  26279. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26280. index++;
  26281. }
  26282. return cumulativeQuaternion;
  26283. };
  26284. Scene.prototype._processLateAnimationBindings = function () {
  26285. if (!this._registeredForLateAnimationBindings.length) {
  26286. return;
  26287. }
  26288. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26289. var target = this._registeredForLateAnimationBindings.data[index];
  26290. for (var path in target._lateAnimationHolders) {
  26291. var holder = target._lateAnimationHolders[path];
  26292. var originalAnimation = holder.animations[0];
  26293. var originalValue = holder.originalValue;
  26294. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26295. var finalValue = void 0;
  26296. if (matrixDecomposeMode) {
  26297. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26298. }
  26299. else {
  26300. var quaternionMode = originalValue.w !== undefined;
  26301. if (quaternionMode) {
  26302. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26303. }
  26304. else {
  26305. var startIndex = 0;
  26306. var normalizer = 1.0;
  26307. if (holder.totalWeight < 1.0) {
  26308. // We need to mix the original value in
  26309. if (originalValue.scale) {
  26310. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26311. }
  26312. else {
  26313. finalValue = originalValue * (1.0 - holder.totalWeight);
  26314. }
  26315. }
  26316. else {
  26317. // We need to normalize the weights
  26318. normalizer = holder.totalWeight;
  26319. var scale_1 = originalAnimation.weight / normalizer;
  26320. if (scale_1 !== 1) {
  26321. if (originalAnimation.currentValue.scale) {
  26322. finalValue = originalAnimation.currentValue.scale(scale_1);
  26323. }
  26324. else {
  26325. finalValue = originalAnimation.currentValue * scale_1;
  26326. }
  26327. }
  26328. else {
  26329. finalValue = originalAnimation.currentValue;
  26330. }
  26331. startIndex = 1;
  26332. }
  26333. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26334. var runtimeAnimation = holder.animations[animIndex];
  26335. var scale = runtimeAnimation.weight / normalizer;
  26336. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26337. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26338. }
  26339. else {
  26340. finalValue += runtimeAnimation.currentValue * scale;
  26341. }
  26342. }
  26343. }
  26344. }
  26345. target[path] = finalValue;
  26346. }
  26347. target._lateAnimationHolders = {};
  26348. }
  26349. this._registeredForLateAnimationBindings.reset();
  26350. };
  26351. // Matrix
  26352. /** @hidden */
  26353. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26354. this._useAlternateCameraConfiguration = active;
  26355. };
  26356. /**
  26357. * Gets the current view matrix
  26358. * @returns a Matrix
  26359. */
  26360. Scene.prototype.getViewMatrix = function () {
  26361. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26362. };
  26363. /**
  26364. * Gets the current projection matrix
  26365. * @returns a Matrix
  26366. */
  26367. Scene.prototype.getProjectionMatrix = function () {
  26368. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26369. };
  26370. /**
  26371. * Gets the current transform matrix
  26372. * @returns a Matrix made of View * Projection
  26373. */
  26374. Scene.prototype.getTransformMatrix = function () {
  26375. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26376. };
  26377. /**
  26378. * Sets the current transform matrix
  26379. * @param view defines the View matrix to use
  26380. * @param projection defines the Projection matrix to use
  26381. */
  26382. Scene.prototype.setTransformMatrix = function (view, projection) {
  26383. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26384. return;
  26385. }
  26386. this._viewUpdateFlag = view.updateFlag;
  26387. this._projectionUpdateFlag = projection.updateFlag;
  26388. this._viewMatrix = view;
  26389. this._projectionMatrix = projection;
  26390. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26391. // Update frustum
  26392. if (!this._frustumPlanes) {
  26393. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26394. }
  26395. else {
  26396. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26397. }
  26398. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26399. var otherCamera = this.activeCamera._alternateCamera;
  26400. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26401. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26402. }
  26403. if (this._sceneUbo.useUbo) {
  26404. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26405. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26406. this._sceneUbo.update();
  26407. }
  26408. };
  26409. /** @hidden */
  26410. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26411. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26412. return;
  26413. }
  26414. this._alternateViewUpdateFlag = view.updateFlag;
  26415. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26416. this._alternateViewMatrix = view;
  26417. this._alternateProjectionMatrix = projection;
  26418. if (!this._alternateTransformMatrix) {
  26419. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26420. }
  26421. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26422. if (!this._alternateSceneUbo) {
  26423. this._createAlternateUbo();
  26424. }
  26425. if (this._alternateSceneUbo.useUbo) {
  26426. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26427. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26428. this._alternateSceneUbo.update();
  26429. }
  26430. };
  26431. /**
  26432. * Gets the uniform buffer used to store scene data
  26433. * @returns a UniformBuffer
  26434. */
  26435. Scene.prototype.getSceneUniformBuffer = function () {
  26436. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26437. };
  26438. /**
  26439. * Gets an unique (relatively to the current scene) Id
  26440. * @returns an unique number for the scene
  26441. */
  26442. Scene.prototype.getUniqueId = function () {
  26443. var result = Scene._uniqueIdCounter;
  26444. Scene._uniqueIdCounter++;
  26445. return result;
  26446. };
  26447. /**
  26448. * Add a mesh to the list of scene's meshes
  26449. * @param newMesh defines the mesh to add
  26450. * @param recursive if all child meshes should also be added to the scene
  26451. */
  26452. Scene.prototype.addMesh = function (newMesh, recursive) {
  26453. var _this = this;
  26454. if (recursive === void 0) { recursive = false; }
  26455. this.meshes.push(newMesh);
  26456. //notify the collision coordinator
  26457. if (this.collisionCoordinator) {
  26458. this.collisionCoordinator.onMeshAdded(newMesh);
  26459. }
  26460. newMesh._resyncLightSources();
  26461. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26462. if (recursive) {
  26463. newMesh.getChildMeshes().forEach(function (m) {
  26464. _this.addMesh(m);
  26465. });
  26466. }
  26467. };
  26468. /**
  26469. * Remove a mesh for the list of scene's meshes
  26470. * @param toRemove defines the mesh to remove
  26471. * @param recursive if all child meshes should also be removed from the scene
  26472. * @returns the index where the mesh was in the mesh list
  26473. */
  26474. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26475. var _this = this;
  26476. if (recursive === void 0) { recursive = false; }
  26477. var index = this.meshes.indexOf(toRemove);
  26478. if (index !== -1) {
  26479. // Remove from the scene if mesh found
  26480. this.meshes.splice(index, 1);
  26481. }
  26482. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26483. if (recursive) {
  26484. toRemove.getChildMeshes().forEach(function (m) {
  26485. _this.removeMesh(m);
  26486. });
  26487. }
  26488. return index;
  26489. };
  26490. /**
  26491. * Add a transform node to the list of scene's transform nodes
  26492. * @param newTransformNode defines the transform node to add
  26493. */
  26494. Scene.prototype.addTransformNode = function (newTransformNode) {
  26495. this.transformNodes.push(newTransformNode);
  26496. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26497. };
  26498. /**
  26499. * Remove a transform node for the list of scene's transform nodes
  26500. * @param toRemove defines the transform node to remove
  26501. * @returns the index where the transform node was in the transform node list
  26502. */
  26503. Scene.prototype.removeTransformNode = function (toRemove) {
  26504. var index = this.transformNodes.indexOf(toRemove);
  26505. if (index !== -1) {
  26506. // Remove from the scene if found
  26507. this.transformNodes.splice(index, 1);
  26508. }
  26509. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26510. return index;
  26511. };
  26512. /**
  26513. * Remove a skeleton for the list of scene's skeletons
  26514. * @param toRemove defines the skeleton to remove
  26515. * @returns the index where the skeleton was in the skeleton list
  26516. */
  26517. Scene.prototype.removeSkeleton = function (toRemove) {
  26518. var index = this.skeletons.indexOf(toRemove);
  26519. if (index !== -1) {
  26520. // Remove from the scene if found
  26521. this.skeletons.splice(index, 1);
  26522. }
  26523. return index;
  26524. };
  26525. /**
  26526. * Remove a morph target for the list of scene's morph targets
  26527. * @param toRemove defines the morph target to remove
  26528. * @returns the index where the morph target was in the morph target list
  26529. */
  26530. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26531. var index = this.morphTargetManagers.indexOf(toRemove);
  26532. if (index !== -1) {
  26533. // Remove from the scene if found
  26534. this.morphTargetManagers.splice(index, 1);
  26535. }
  26536. return index;
  26537. };
  26538. /**
  26539. * Remove a light for the list of scene's lights
  26540. * @param toRemove defines the light to remove
  26541. * @returns the index where the light was in the light list
  26542. */
  26543. Scene.prototype.removeLight = function (toRemove) {
  26544. var index = this.lights.indexOf(toRemove);
  26545. if (index !== -1) {
  26546. // Remove from meshes
  26547. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26548. var mesh = _a[_i];
  26549. mesh._removeLightSource(toRemove);
  26550. }
  26551. // Remove from the scene if mesh found
  26552. this.lights.splice(index, 1);
  26553. this.sortLightsByPriority();
  26554. }
  26555. this.onLightRemovedObservable.notifyObservers(toRemove);
  26556. return index;
  26557. };
  26558. /**
  26559. * Remove a camera for the list of scene's cameras
  26560. * @param toRemove defines the camera to remove
  26561. * @returns the index where the camera was in the camera list
  26562. */
  26563. Scene.prototype.removeCamera = function (toRemove) {
  26564. var index = this.cameras.indexOf(toRemove);
  26565. if (index !== -1) {
  26566. // Remove from the scene if mesh found
  26567. this.cameras.splice(index, 1);
  26568. }
  26569. // Remove from activeCameras
  26570. var index2 = this.activeCameras.indexOf(toRemove);
  26571. if (index2 !== -1) {
  26572. // Remove from the scene if mesh found
  26573. this.activeCameras.splice(index2, 1);
  26574. }
  26575. // Reset the activeCamera
  26576. if (this.activeCamera === toRemove) {
  26577. if (this.cameras.length > 0) {
  26578. this.activeCamera = this.cameras[0];
  26579. }
  26580. else {
  26581. this.activeCamera = null;
  26582. }
  26583. }
  26584. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26585. return index;
  26586. };
  26587. /**
  26588. * Remove a particle system for the list of scene's particle systems
  26589. * @param toRemove defines the particle system to remove
  26590. * @returns the index where the particle system was in the particle system list
  26591. */
  26592. Scene.prototype.removeParticleSystem = function (toRemove) {
  26593. var index = this.particleSystems.indexOf(toRemove);
  26594. if (index !== -1) {
  26595. this.particleSystems.splice(index, 1);
  26596. }
  26597. return index;
  26598. };
  26599. /**
  26600. * Remove a animation for the list of scene's animations
  26601. * @param toRemove defines the animation to remove
  26602. * @returns the index where the animation was in the animation list
  26603. */
  26604. Scene.prototype.removeAnimation = function (toRemove) {
  26605. var index = this.animations.indexOf(toRemove);
  26606. if (index !== -1) {
  26607. this.animations.splice(index, 1);
  26608. }
  26609. return index;
  26610. };
  26611. /**
  26612. * Removes the given animation group from this scene.
  26613. * @param toRemove The animation group to remove
  26614. * @returns The index of the removed animation group
  26615. */
  26616. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26617. var index = this.animationGroups.indexOf(toRemove);
  26618. if (index !== -1) {
  26619. this.animationGroups.splice(index, 1);
  26620. }
  26621. return index;
  26622. };
  26623. /**
  26624. * Removes the given multi-material from this scene.
  26625. * @param toRemove The multi-material to remove
  26626. * @returns The index of the removed multi-material
  26627. */
  26628. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26629. var index = this.multiMaterials.indexOf(toRemove);
  26630. if (index !== -1) {
  26631. this.multiMaterials.splice(index, 1);
  26632. }
  26633. return index;
  26634. };
  26635. /**
  26636. * Removes the given material from this scene.
  26637. * @param toRemove The material to remove
  26638. * @returns The index of the removed material
  26639. */
  26640. Scene.prototype.removeMaterial = function (toRemove) {
  26641. var index = this.materials.indexOf(toRemove);
  26642. if (index !== -1) {
  26643. this.materials.splice(index, 1);
  26644. }
  26645. return index;
  26646. };
  26647. /**
  26648. * Removes the given action manager from this scene.
  26649. * @param toRemove The action manager to remove
  26650. * @returns The index of the removed action manager
  26651. */
  26652. Scene.prototype.removeActionManager = function (toRemove) {
  26653. var index = this.actionManagers.indexOf(toRemove);
  26654. if (index !== -1) {
  26655. this.actionManagers.splice(index, 1);
  26656. }
  26657. return index;
  26658. };
  26659. /**
  26660. * Removes the given texture from this scene.
  26661. * @param toRemove The texture to remove
  26662. * @returns The index of the removed texture
  26663. */
  26664. Scene.prototype.removeTexture = function (toRemove) {
  26665. var index = this.textures.indexOf(toRemove);
  26666. if (index !== -1) {
  26667. this.textures.splice(index, 1);
  26668. }
  26669. return index;
  26670. };
  26671. /**
  26672. * Adds the given light to this scene
  26673. * @param newLight The light to add
  26674. */
  26675. Scene.prototype.addLight = function (newLight) {
  26676. this.lights.push(newLight);
  26677. this.sortLightsByPriority();
  26678. // Add light to all meshes (To support if the light is removed and then readded)
  26679. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26680. var mesh = _a[_i];
  26681. if (mesh._lightSources.indexOf(newLight) === -1) {
  26682. mesh._lightSources.push(newLight);
  26683. mesh._resyncLightSources();
  26684. }
  26685. }
  26686. this.onNewLightAddedObservable.notifyObservers(newLight);
  26687. };
  26688. /**
  26689. * Sorts the list list based on light priorities
  26690. */
  26691. Scene.prototype.sortLightsByPriority = function () {
  26692. if (this.requireLightSorting) {
  26693. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26694. }
  26695. };
  26696. /**
  26697. * Adds the given camera to this scene
  26698. * @param newCamera The camera to add
  26699. */
  26700. Scene.prototype.addCamera = function (newCamera) {
  26701. this.cameras.push(newCamera);
  26702. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26703. };
  26704. /**
  26705. * Adds the given skeleton to this scene
  26706. * @param newSkeleton The skeleton to add
  26707. */
  26708. Scene.prototype.addSkeleton = function (newSkeleton) {
  26709. this.skeletons.push(newSkeleton);
  26710. };
  26711. /**
  26712. * Adds the given particle system to this scene
  26713. * @param newParticleSystem The particle system to add
  26714. */
  26715. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26716. this.particleSystems.push(newParticleSystem);
  26717. };
  26718. /**
  26719. * Adds the given animation to this scene
  26720. * @param newAnimation The animation to add
  26721. */
  26722. Scene.prototype.addAnimation = function (newAnimation) {
  26723. this.animations.push(newAnimation);
  26724. };
  26725. /**
  26726. * Adds the given animation group to this scene.
  26727. * @param newAnimationGroup The animation group to add
  26728. */
  26729. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26730. this.animationGroups.push(newAnimationGroup);
  26731. };
  26732. /**
  26733. * Adds the given multi-material to this scene
  26734. * @param newMultiMaterial The multi-material to add
  26735. */
  26736. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26737. this.multiMaterials.push(newMultiMaterial);
  26738. };
  26739. /**
  26740. * Adds the given material to this scene
  26741. * @param newMaterial The material to add
  26742. */
  26743. Scene.prototype.addMaterial = function (newMaterial) {
  26744. this.materials.push(newMaterial);
  26745. };
  26746. /**
  26747. * Adds the given morph target to this scene
  26748. * @param newMorphTargetManager The morph target to add
  26749. */
  26750. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26751. this.morphTargetManagers.push(newMorphTargetManager);
  26752. };
  26753. /**
  26754. * Adds the given geometry to this scene
  26755. * @param newGeometry The geometry to add
  26756. */
  26757. Scene.prototype.addGeometry = function (newGeometry) {
  26758. this.geometries.push(newGeometry);
  26759. };
  26760. /**
  26761. * Adds the given action manager to this scene
  26762. * @param newActionManager The action manager to add
  26763. */
  26764. Scene.prototype.addActionManager = function (newActionManager) {
  26765. this.actionManagers.push(newActionManager);
  26766. };
  26767. /**
  26768. * Adds the given texture to this scene.
  26769. * @param newTexture The texture to add
  26770. */
  26771. Scene.prototype.addTexture = function (newTexture) {
  26772. this.textures.push(newTexture);
  26773. };
  26774. /**
  26775. * Switch active camera
  26776. * @param newCamera defines the new active camera
  26777. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26778. */
  26779. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26780. if (attachControl === void 0) { attachControl = true; }
  26781. var canvas = this._engine.getRenderingCanvas();
  26782. if (!canvas) {
  26783. return;
  26784. }
  26785. if (this.activeCamera) {
  26786. this.activeCamera.detachControl(canvas);
  26787. }
  26788. this.activeCamera = newCamera;
  26789. if (attachControl) {
  26790. newCamera.attachControl(canvas);
  26791. }
  26792. };
  26793. /**
  26794. * sets the active camera of the scene using its ID
  26795. * @param id defines the camera's ID
  26796. * @return the new active camera or null if none found.
  26797. */
  26798. Scene.prototype.setActiveCameraByID = function (id) {
  26799. var camera = this.getCameraByID(id);
  26800. if (camera) {
  26801. this.activeCamera = camera;
  26802. return camera;
  26803. }
  26804. return null;
  26805. };
  26806. /**
  26807. * sets the active camera of the scene using its name
  26808. * @param name defines the camera's name
  26809. * @returns the new active camera or null if none found.
  26810. */
  26811. Scene.prototype.setActiveCameraByName = function (name) {
  26812. var camera = this.getCameraByName(name);
  26813. if (camera) {
  26814. this.activeCamera = camera;
  26815. return camera;
  26816. }
  26817. return null;
  26818. };
  26819. /**
  26820. * get an animation group using its name
  26821. * @param name defines the material's name
  26822. * @return the animation group or null if none found.
  26823. */
  26824. Scene.prototype.getAnimationGroupByName = function (name) {
  26825. for (var index = 0; index < this.animationGroups.length; index++) {
  26826. if (this.animationGroups[index].name === name) {
  26827. return this.animationGroups[index];
  26828. }
  26829. }
  26830. return null;
  26831. };
  26832. /**
  26833. * get a material using its id
  26834. * @param id defines the material's ID
  26835. * @return the material or null if none found.
  26836. */
  26837. Scene.prototype.getMaterialByID = function (id) {
  26838. for (var index = 0; index < this.materials.length; index++) {
  26839. if (this.materials[index].id === id) {
  26840. return this.materials[index];
  26841. }
  26842. }
  26843. return null;
  26844. };
  26845. /**
  26846. * Gets a material using its name
  26847. * @param name defines the material's name
  26848. * @return the material or null if none found.
  26849. */
  26850. Scene.prototype.getMaterialByName = function (name) {
  26851. for (var index = 0; index < this.materials.length; index++) {
  26852. if (this.materials[index].name === name) {
  26853. return this.materials[index];
  26854. }
  26855. }
  26856. return null;
  26857. };
  26858. /**
  26859. * Gets a camera using its id
  26860. * @param id defines the id to look for
  26861. * @returns the camera or null if not found
  26862. */
  26863. Scene.prototype.getCameraByID = function (id) {
  26864. for (var index = 0; index < this.cameras.length; index++) {
  26865. if (this.cameras[index].id === id) {
  26866. return this.cameras[index];
  26867. }
  26868. }
  26869. return null;
  26870. };
  26871. /**
  26872. * Gets a camera using its unique id
  26873. * @param uniqueId defines the unique id to look for
  26874. * @returns the camera or null if not found
  26875. */
  26876. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26877. for (var index = 0; index < this.cameras.length; index++) {
  26878. if (this.cameras[index].uniqueId === uniqueId) {
  26879. return this.cameras[index];
  26880. }
  26881. }
  26882. return null;
  26883. };
  26884. /**
  26885. * Gets a camera using its name
  26886. * @param name defines the camera's name
  26887. * @return the camera or null if none found.
  26888. */
  26889. Scene.prototype.getCameraByName = function (name) {
  26890. for (var index = 0; index < this.cameras.length; index++) {
  26891. if (this.cameras[index].name === name) {
  26892. return this.cameras[index];
  26893. }
  26894. }
  26895. return null;
  26896. };
  26897. /**
  26898. * Gets a bone using its id
  26899. * @param id defines the bone's id
  26900. * @return the bone or null if not found
  26901. */
  26902. Scene.prototype.getBoneByID = function (id) {
  26903. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26904. var skeleton = this.skeletons[skeletonIndex];
  26905. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26906. if (skeleton.bones[boneIndex].id === id) {
  26907. return skeleton.bones[boneIndex];
  26908. }
  26909. }
  26910. }
  26911. return null;
  26912. };
  26913. /**
  26914. * Gets a bone using its id
  26915. * @param name defines the bone's name
  26916. * @return the bone or null if not found
  26917. */
  26918. Scene.prototype.getBoneByName = function (name) {
  26919. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26920. var skeleton = this.skeletons[skeletonIndex];
  26921. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26922. if (skeleton.bones[boneIndex].name === name) {
  26923. return skeleton.bones[boneIndex];
  26924. }
  26925. }
  26926. }
  26927. return null;
  26928. };
  26929. /**
  26930. * Gets a light node using its name
  26931. * @param name defines the the light's name
  26932. * @return the light or null if none found.
  26933. */
  26934. Scene.prototype.getLightByName = function (name) {
  26935. for (var index = 0; index < this.lights.length; index++) {
  26936. if (this.lights[index].name === name) {
  26937. return this.lights[index];
  26938. }
  26939. }
  26940. return null;
  26941. };
  26942. /**
  26943. * Gets a light node using its id
  26944. * @param id defines the light's id
  26945. * @return the light or null if none found.
  26946. */
  26947. Scene.prototype.getLightByID = function (id) {
  26948. for (var index = 0; index < this.lights.length; index++) {
  26949. if (this.lights[index].id === id) {
  26950. return this.lights[index];
  26951. }
  26952. }
  26953. return null;
  26954. };
  26955. /**
  26956. * Gets a light node using its scene-generated unique ID
  26957. * @param uniqueId defines the light's unique id
  26958. * @return the light or null if none found.
  26959. */
  26960. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26961. for (var index = 0; index < this.lights.length; index++) {
  26962. if (this.lights[index].uniqueId === uniqueId) {
  26963. return this.lights[index];
  26964. }
  26965. }
  26966. return null;
  26967. };
  26968. /**
  26969. * Gets a particle system by id
  26970. * @param id defines the particle system id
  26971. * @return the corresponding system or null if none found
  26972. */
  26973. Scene.prototype.getParticleSystemByID = function (id) {
  26974. for (var index = 0; index < this.particleSystems.length; index++) {
  26975. if (this.particleSystems[index].id === id) {
  26976. return this.particleSystems[index];
  26977. }
  26978. }
  26979. return null;
  26980. };
  26981. /**
  26982. * Gets a geometry using its ID
  26983. * @param id defines the geometry's id
  26984. * @return the geometry or null if none found.
  26985. */
  26986. Scene.prototype.getGeometryByID = function (id) {
  26987. for (var index = 0; index < this.geometries.length; index++) {
  26988. if (this.geometries[index].id === id) {
  26989. return this.geometries[index];
  26990. }
  26991. }
  26992. return null;
  26993. };
  26994. /**
  26995. * Add a new geometry to this scene
  26996. * @param geometry defines the geometry to be added to the scene.
  26997. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26998. * @return a boolean defining if the geometry was added or not
  26999. */
  27000. Scene.prototype.pushGeometry = function (geometry, force) {
  27001. if (!force && this.getGeometryByID(geometry.id)) {
  27002. return false;
  27003. }
  27004. this.geometries.push(geometry);
  27005. //notify the collision coordinator
  27006. if (this.collisionCoordinator) {
  27007. this.collisionCoordinator.onGeometryAdded(geometry);
  27008. }
  27009. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  27010. return true;
  27011. };
  27012. /**
  27013. * Removes an existing geometry
  27014. * @param geometry defines the geometry to be removed from the scene
  27015. * @return a boolean defining if the geometry was removed or not
  27016. */
  27017. Scene.prototype.removeGeometry = function (geometry) {
  27018. var index = this.geometries.indexOf(geometry);
  27019. if (index > -1) {
  27020. this.geometries.splice(index, 1);
  27021. //notify the collision coordinator
  27022. if (this.collisionCoordinator) {
  27023. this.collisionCoordinator.onGeometryDeleted(geometry);
  27024. }
  27025. this.onGeometryRemovedObservable.notifyObservers(geometry);
  27026. return true;
  27027. }
  27028. return false;
  27029. };
  27030. /**
  27031. * Gets the list of geometries attached to the scene
  27032. * @returns an array of Geometry
  27033. */
  27034. Scene.prototype.getGeometries = function () {
  27035. return this.geometries;
  27036. };
  27037. /**
  27038. * Gets the first added mesh found of a given ID
  27039. * @param id defines the id to search for
  27040. * @return the mesh found or null if not found at all
  27041. */
  27042. Scene.prototype.getMeshByID = function (id) {
  27043. for (var index = 0; index < this.meshes.length; index++) {
  27044. if (this.meshes[index].id === id) {
  27045. return this.meshes[index];
  27046. }
  27047. }
  27048. return null;
  27049. };
  27050. /**
  27051. * Gets a list of meshes using their id
  27052. * @param id defines the id to search for
  27053. * @returns a list of meshes
  27054. */
  27055. Scene.prototype.getMeshesByID = function (id) {
  27056. return this.meshes.filter(function (m) {
  27057. return m.id === id;
  27058. });
  27059. };
  27060. /**
  27061. * Gets the first added transform node found of a given ID
  27062. * @param id defines the id to search for
  27063. * @return the found transform node or null if not found at all.
  27064. */
  27065. Scene.prototype.getTransformNodeByID = function (id) {
  27066. for (var index = 0; index < this.transformNodes.length; index++) {
  27067. if (this.transformNodes[index].id === id) {
  27068. return this.transformNodes[index];
  27069. }
  27070. }
  27071. return null;
  27072. };
  27073. /**
  27074. * Gets a list of transform nodes using their id
  27075. * @param id defines the id to search for
  27076. * @returns a list of transform nodes
  27077. */
  27078. Scene.prototype.getTransformNodesByID = function (id) {
  27079. return this.transformNodes.filter(function (m) {
  27080. return m.id === id;
  27081. });
  27082. };
  27083. /**
  27084. * Gets a mesh with its auto-generated unique id
  27085. * @param uniqueId defines the unique id to search for
  27086. * @return the found mesh or null if not found at all.
  27087. */
  27088. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27089. for (var index = 0; index < this.meshes.length; index++) {
  27090. if (this.meshes[index].uniqueId === uniqueId) {
  27091. return this.meshes[index];
  27092. }
  27093. }
  27094. return null;
  27095. };
  27096. /**
  27097. * Gets a the last added mesh using a given id
  27098. * @param id defines the id to search for
  27099. * @return the found mesh or null if not found at all.
  27100. */
  27101. Scene.prototype.getLastMeshByID = function (id) {
  27102. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27103. if (this.meshes[index].id === id) {
  27104. return this.meshes[index];
  27105. }
  27106. }
  27107. return null;
  27108. };
  27109. /**
  27110. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27111. * @param id defines the id to search for
  27112. * @return the found node or null if not found at all
  27113. */
  27114. Scene.prototype.getLastEntryByID = function (id) {
  27115. var index;
  27116. for (index = this.meshes.length - 1; index >= 0; index--) {
  27117. if (this.meshes[index].id === id) {
  27118. return this.meshes[index];
  27119. }
  27120. }
  27121. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27122. if (this.transformNodes[index].id === id) {
  27123. return this.transformNodes[index];
  27124. }
  27125. }
  27126. for (index = this.cameras.length - 1; index >= 0; index--) {
  27127. if (this.cameras[index].id === id) {
  27128. return this.cameras[index];
  27129. }
  27130. }
  27131. for (index = this.lights.length - 1; index >= 0; index--) {
  27132. if (this.lights[index].id === id) {
  27133. return this.lights[index];
  27134. }
  27135. }
  27136. return null;
  27137. };
  27138. /**
  27139. * Gets a node (Mesh, Camera, Light) using a given id
  27140. * @param id defines the id to search for
  27141. * @return the found node or null if not found at all
  27142. */
  27143. Scene.prototype.getNodeByID = function (id) {
  27144. var mesh = this.getMeshByID(id);
  27145. if (mesh) {
  27146. return mesh;
  27147. }
  27148. var light = this.getLightByID(id);
  27149. if (light) {
  27150. return light;
  27151. }
  27152. var camera = this.getCameraByID(id);
  27153. if (camera) {
  27154. return camera;
  27155. }
  27156. var bone = this.getBoneByID(id);
  27157. return bone;
  27158. };
  27159. /**
  27160. * Gets a node (Mesh, Camera, Light) using a given name
  27161. * @param name defines the name to search for
  27162. * @return the found node or null if not found at all.
  27163. */
  27164. Scene.prototype.getNodeByName = function (name) {
  27165. var mesh = this.getMeshByName(name);
  27166. if (mesh) {
  27167. return mesh;
  27168. }
  27169. var light = this.getLightByName(name);
  27170. if (light) {
  27171. return light;
  27172. }
  27173. var camera = this.getCameraByName(name);
  27174. if (camera) {
  27175. return camera;
  27176. }
  27177. var bone = this.getBoneByName(name);
  27178. return bone;
  27179. };
  27180. /**
  27181. * Gets a mesh using a given name
  27182. * @param name defines the name to search for
  27183. * @return the found mesh or null if not found at all.
  27184. */
  27185. Scene.prototype.getMeshByName = function (name) {
  27186. for (var index = 0; index < this.meshes.length; index++) {
  27187. if (this.meshes[index].name === name) {
  27188. return this.meshes[index];
  27189. }
  27190. }
  27191. return null;
  27192. };
  27193. /**
  27194. * Gets a transform node using a given name
  27195. * @param name defines the name to search for
  27196. * @return the found transform node or null if not found at all.
  27197. */
  27198. Scene.prototype.getTransformNodeByName = function (name) {
  27199. for (var index = 0; index < this.transformNodes.length; index++) {
  27200. if (this.transformNodes[index].name === name) {
  27201. return this.transformNodes[index];
  27202. }
  27203. }
  27204. return null;
  27205. };
  27206. /**
  27207. * Gets a sound using a given name
  27208. * @param name defines the name to search for
  27209. * @return the found sound or null if not found at all.
  27210. */
  27211. Scene.prototype.getSoundByName = function (name) {
  27212. var index;
  27213. if (BABYLON.AudioEngine) {
  27214. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27215. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27216. return this.mainSoundTrack.soundCollection[index];
  27217. }
  27218. }
  27219. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27220. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27221. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27222. return this.soundTracks[sdIndex].soundCollection[index];
  27223. }
  27224. }
  27225. }
  27226. }
  27227. return null;
  27228. };
  27229. /**
  27230. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27231. * @param id defines the id to search for
  27232. * @return the found skeleton or null if not found at all.
  27233. */
  27234. Scene.prototype.getLastSkeletonByID = function (id) {
  27235. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27236. if (this.skeletons[index].id === id) {
  27237. return this.skeletons[index];
  27238. }
  27239. }
  27240. return null;
  27241. };
  27242. /**
  27243. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27244. * @param id defines the id to search for
  27245. * @return the found skeleton or null if not found at all.
  27246. */
  27247. Scene.prototype.getSkeletonById = function (id) {
  27248. for (var index = 0; index < this.skeletons.length; index++) {
  27249. if (this.skeletons[index].id === id) {
  27250. return this.skeletons[index];
  27251. }
  27252. }
  27253. return null;
  27254. };
  27255. /**
  27256. * Gets a skeleton using a given name
  27257. * @param name defines the name to search for
  27258. * @return the found skeleton or null if not found at all.
  27259. */
  27260. Scene.prototype.getSkeletonByName = function (name) {
  27261. for (var index = 0; index < this.skeletons.length; index++) {
  27262. if (this.skeletons[index].name === name) {
  27263. return this.skeletons[index];
  27264. }
  27265. }
  27266. return null;
  27267. };
  27268. /**
  27269. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27270. * @param id defines the id to search for
  27271. * @return the found morph target manager or null if not found at all.
  27272. */
  27273. Scene.prototype.getMorphTargetManagerById = function (id) {
  27274. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27275. if (this.morphTargetManagers[index].uniqueId === id) {
  27276. return this.morphTargetManagers[index];
  27277. }
  27278. }
  27279. return null;
  27280. };
  27281. /**
  27282. * Gets a boolean indicating if the given mesh is active
  27283. * @param mesh defines the mesh to look for
  27284. * @returns true if the mesh is in the active list
  27285. */
  27286. Scene.prototype.isActiveMesh = function (mesh) {
  27287. return (this._activeMeshes.indexOf(mesh) !== -1);
  27288. };
  27289. Object.defineProperty(Scene.prototype, "uid", {
  27290. /**
  27291. * Return a unique id as a string which can serve as an identifier for the scene
  27292. */
  27293. get: function () {
  27294. if (!this._uid) {
  27295. this._uid = BABYLON.Tools.RandomId();
  27296. }
  27297. return this._uid;
  27298. },
  27299. enumerable: true,
  27300. configurable: true
  27301. });
  27302. /**
  27303. * Add an externaly attached data from its key.
  27304. * This method call will fail and return false, if such key already exists.
  27305. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27306. * @param key the unique key that identifies the data
  27307. * @param data the data object to associate to the key for this Engine instance
  27308. * @return true if no such key were already present and the data was added successfully, false otherwise
  27309. */
  27310. Scene.prototype.addExternalData = function (key, data) {
  27311. if (!this._externalData) {
  27312. this._externalData = new BABYLON.StringDictionary();
  27313. }
  27314. return this._externalData.add(key, data);
  27315. };
  27316. /**
  27317. * Get an externaly attached data from its key
  27318. * @param key the unique key that identifies the data
  27319. * @return the associated data, if present (can be null), or undefined if not present
  27320. */
  27321. Scene.prototype.getExternalData = function (key) {
  27322. if (!this._externalData) {
  27323. return null;
  27324. }
  27325. return this._externalData.get(key);
  27326. };
  27327. /**
  27328. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27329. * @param key the unique key that identifies the data
  27330. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27331. * @return the associated data, can be null if the factory returned null.
  27332. */
  27333. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27334. if (!this._externalData) {
  27335. this._externalData = new BABYLON.StringDictionary();
  27336. }
  27337. return this._externalData.getOrAddWithFactory(key, factory);
  27338. };
  27339. /**
  27340. * Remove an externaly attached data from the Engine instance
  27341. * @param key the unique key that identifies the data
  27342. * @return true if the data was successfully removed, false if it doesn't exist
  27343. */
  27344. Scene.prototype.removeExternalData = function (key) {
  27345. return this._externalData.remove(key);
  27346. };
  27347. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27348. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27349. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  27350. var step = _a[_i];
  27351. step.action(mesh, subMesh);
  27352. }
  27353. var material = subMesh.getMaterial();
  27354. if (material !== null && material !== undefined) {
  27355. // Render targets
  27356. if (material.getRenderTargetTextures !== undefined) {
  27357. if (this._processedMaterials.indexOf(material) === -1) {
  27358. this._processedMaterials.push(material);
  27359. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27360. }
  27361. }
  27362. // Dispatch
  27363. this._activeIndices.addCount(subMesh.indexCount, false);
  27364. this._renderingManager.dispatch(subMesh, mesh, material);
  27365. }
  27366. }
  27367. };
  27368. /**
  27369. * Clear the processed materials smart array preventing retention point in material dispose.
  27370. */
  27371. Scene.prototype.freeProcessedMaterials = function () {
  27372. this._processedMaterials.dispose();
  27373. };
  27374. /**
  27375. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27376. */
  27377. Scene.prototype.freeActiveMeshes = function () {
  27378. this._activeMeshes.dispose();
  27379. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27380. this.activeCamera._activeMeshes.dispose();
  27381. }
  27382. if (this.activeCameras) {
  27383. for (var i = 0; i < this.activeCameras.length; i++) {
  27384. var activeCamera = this.activeCameras[i];
  27385. if (activeCamera && activeCamera._activeMeshes) {
  27386. activeCamera._activeMeshes.dispose();
  27387. }
  27388. }
  27389. }
  27390. };
  27391. /**
  27392. * Clear the info related to rendering groups preventing retention points during dispose.
  27393. */
  27394. Scene.prototype.freeRenderingGroups = function () {
  27395. if (this._renderingManager) {
  27396. this._renderingManager.freeRenderingGroups();
  27397. }
  27398. if (this.textures) {
  27399. for (var i = 0; i < this.textures.length; i++) {
  27400. var texture = this.textures[i];
  27401. if (texture && texture.renderList) {
  27402. texture.freeRenderingGroups();
  27403. }
  27404. }
  27405. }
  27406. };
  27407. /** @hidden */
  27408. Scene.prototype._isInIntermediateRendering = function () {
  27409. return this._intermediateRendering;
  27410. };
  27411. /**
  27412. * Defines the current active mesh candidate provider
  27413. * @param provider defines the provider to use
  27414. */
  27415. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27416. this._activeMeshCandidateProvider = provider;
  27417. };
  27418. /**
  27419. * Gets the current active mesh candidate provider
  27420. * @returns the current active mesh candidate provider
  27421. */
  27422. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27423. return this._activeMeshCandidateProvider;
  27424. };
  27425. /**
  27426. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27427. * @returns the current scene
  27428. */
  27429. Scene.prototype.freezeActiveMeshes = function () {
  27430. if (!this.activeCamera) {
  27431. return this;
  27432. }
  27433. if (!this._frustumPlanes) {
  27434. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27435. }
  27436. this._evaluateActiveMeshes();
  27437. this._activeMeshesFrozen = true;
  27438. return this;
  27439. };
  27440. /**
  27441. * Use this function to restart evaluating active meshes on every frame
  27442. * @returns the current scene
  27443. */
  27444. Scene.prototype.unfreezeActiveMeshes = function () {
  27445. this._activeMeshesFrozen = false;
  27446. return this;
  27447. };
  27448. Scene.prototype._evaluateActiveMeshes = function () {
  27449. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27450. return;
  27451. }
  27452. if (!this.activeCamera) {
  27453. return;
  27454. }
  27455. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27456. this.activeCamera._activeMeshes.reset();
  27457. this._activeMeshes.reset();
  27458. this._renderingManager.reset();
  27459. this._processedMaterials.reset();
  27460. this._activeParticleSystems.reset();
  27461. this._activeSkeletons.reset();
  27462. this._softwareSkinnedMeshes.reset();
  27463. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  27464. var step = _a[_i];
  27465. step.action();
  27466. }
  27467. // Meshes
  27468. var meshes;
  27469. var len;
  27470. var checkIsEnabled = true;
  27471. // Determine mesh candidates
  27472. if (this._activeMeshCandidateProvider !== undefined) {
  27473. // Use _activeMeshCandidateProvider
  27474. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27475. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27476. if (meshes !== undefined) {
  27477. len = meshes.length;
  27478. }
  27479. else {
  27480. len = 0;
  27481. }
  27482. }
  27483. else if (this._selectionOctree !== undefined) {
  27484. // Octree
  27485. var selection = this._selectionOctree.select(this._frustumPlanes);
  27486. meshes = selection.data;
  27487. len = selection.length;
  27488. }
  27489. else {
  27490. // Full scene traversal
  27491. len = this.meshes.length;
  27492. meshes = this.meshes;
  27493. }
  27494. // Check each mesh
  27495. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27496. mesh = meshes[meshIndex];
  27497. if (mesh.isBlocked) {
  27498. continue;
  27499. }
  27500. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27501. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27502. continue;
  27503. }
  27504. mesh.computeWorldMatrix();
  27505. // Intersections
  27506. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27507. this._meshesForIntersections.pushNoDuplicate(mesh);
  27508. }
  27509. // Switch to current LOD
  27510. meshLOD = mesh.getLOD(this.activeCamera);
  27511. if (meshLOD === undefined || meshLOD === null) {
  27512. continue;
  27513. }
  27514. mesh._preActivate();
  27515. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  27516. this._activeMeshes.push(mesh);
  27517. this.activeCamera._activeMeshes.push(mesh);
  27518. mesh._activate(this._renderId);
  27519. if (meshLOD !== mesh) {
  27520. meshLOD._activate(this._renderId);
  27521. }
  27522. this._activeMesh(mesh, meshLOD);
  27523. }
  27524. }
  27525. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27526. // Particle systems
  27527. if (this.particlesEnabled) {
  27528. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27529. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27530. var particleSystem = this.particleSystems[particleIndex];
  27531. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27532. continue;
  27533. }
  27534. var emitter = particleSystem.emitter;
  27535. if (!emitter.position || emitter.isEnabled()) {
  27536. this._activeParticleSystems.push(particleSystem);
  27537. particleSystem.animate();
  27538. this._renderingManager.dispatchParticles(particleSystem);
  27539. }
  27540. }
  27541. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27542. }
  27543. };
  27544. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27545. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27546. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27547. mesh.skeleton.prepare();
  27548. }
  27549. if (!mesh.computeBonesUsingShaders) {
  27550. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27551. }
  27552. }
  27553. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  27554. var step = _a[_i];
  27555. step.action(sourceMesh, mesh);
  27556. }
  27557. if (mesh !== undefined && mesh !== null
  27558. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27559. // Submeshes Octrees
  27560. var len;
  27561. var subMeshes;
  27562. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27563. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27564. len = intersections.length;
  27565. subMeshes = intersections.data;
  27566. }
  27567. else {
  27568. subMeshes = mesh.subMeshes;
  27569. len = subMeshes.length;
  27570. }
  27571. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27572. subMesh = subMeshes[subIndex];
  27573. this._evaluateSubMesh(subMesh, mesh);
  27574. }
  27575. }
  27576. };
  27577. /**
  27578. * Update the transform matrix to update from the current active camera
  27579. * @param force defines a boolean used to force the update even if cache is up to date
  27580. */
  27581. Scene.prototype.updateTransformMatrix = function (force) {
  27582. if (!this.activeCamera) {
  27583. return;
  27584. }
  27585. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27586. };
  27587. /**
  27588. * 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)
  27589. * @param alternateCamera defines the camera to use
  27590. */
  27591. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27592. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27593. };
  27594. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27595. if (camera && camera._skipRendering) {
  27596. return;
  27597. }
  27598. var engine = this._engine;
  27599. this.activeCamera = camera;
  27600. if (!this.activeCamera)
  27601. throw new Error("Active camera not set");
  27602. // Viewport
  27603. engine.setViewport(this.activeCamera.viewport);
  27604. // Camera
  27605. this.resetCachedMaterial();
  27606. this._renderId++;
  27607. this.updateTransformMatrix();
  27608. if (camera._alternateCamera) {
  27609. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27610. this._alternateRendering = true;
  27611. }
  27612. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27613. // Meshes
  27614. this._evaluateActiveMeshes();
  27615. // Software skinning
  27616. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27617. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27618. mesh.applySkeleton(mesh.skeleton);
  27619. }
  27620. // Render targets
  27621. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27622. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27623. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27624. }
  27625. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27626. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27627. }
  27628. if (this.renderTargetsEnabled) {
  27629. this._intermediateRendering = true;
  27630. if (this._renderTargets.length > 0) {
  27631. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27632. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27633. var renderTarget = this._renderTargets.data[renderIndex];
  27634. if (renderTarget._shouldRender()) {
  27635. this._renderId++;
  27636. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27637. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27638. }
  27639. }
  27640. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27641. this._renderId++;
  27642. }
  27643. for (var _i = 0, _a = this._cameraDrawRenderTargetStage; _i < _a.length; _i++) {
  27644. var step = _a[_i];
  27645. step.action(this.activeCamera);
  27646. }
  27647. this._intermediateRendering = false;
  27648. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27649. }
  27650. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27651. // Prepare Frame
  27652. if (this.postProcessManager) {
  27653. this.postProcessManager._prepareFrame();
  27654. }
  27655. // Before Camera Draw
  27656. for (var _b = 0, _c = this._beforeCameraDrawStage; _b < _c.length; _b++) {
  27657. var step = _c[_b];
  27658. step.action(this.activeCamera);
  27659. }
  27660. // Render
  27661. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27662. this._renderingManager.render(null, null, true, true);
  27663. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27664. // After Camera Draw
  27665. for (var _d = 0, _e = this._afterCameraDrawStage; _d < _e.length; _d++) {
  27666. var step = _e[_d];
  27667. step.action(this.activeCamera);
  27668. }
  27669. // Finalize frame
  27670. if (this.postProcessManager) {
  27671. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27672. }
  27673. // Reset some special arrays
  27674. this._renderTargets.reset();
  27675. this._alternateRendering = false;
  27676. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27677. };
  27678. Scene.prototype._processSubCameras = function (camera) {
  27679. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27680. this._renderForCamera(camera);
  27681. return;
  27682. }
  27683. // rig cameras
  27684. for (var index = 0; index < camera._rigCameras.length; index++) {
  27685. this._renderForCamera(camera._rigCameras[index], camera);
  27686. }
  27687. this.activeCamera = camera;
  27688. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27689. };
  27690. Scene.prototype._checkIntersections = function () {
  27691. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27692. var sourceMesh = this._meshesForIntersections.data[index];
  27693. if (!sourceMesh.actionManager) {
  27694. continue;
  27695. }
  27696. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27697. var action = sourceMesh.actionManager.actions[actionIndex];
  27698. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27699. var parameters = action.getTriggerParameter();
  27700. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27701. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27702. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27703. if (areIntersecting && currentIntersectionInProgress === -1) {
  27704. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27705. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27706. sourceMesh._intersectionsInProgress.push(otherMesh);
  27707. }
  27708. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27709. sourceMesh._intersectionsInProgress.push(otherMesh);
  27710. }
  27711. }
  27712. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27713. //They intersected, and now they don't.
  27714. //is this trigger an exit trigger? execute an event.
  27715. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27716. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27717. }
  27718. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27719. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27720. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27721. return otherMesh === parameterMesh;
  27722. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27723. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27724. }
  27725. }
  27726. }
  27727. }
  27728. }
  27729. };
  27730. /**
  27731. * Render the scene
  27732. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27733. */
  27734. Scene.prototype.render = function (updateCameras) {
  27735. if (updateCameras === void 0) { updateCameras = true; }
  27736. if (this.isDisposed) {
  27737. return;
  27738. }
  27739. // Register components that have been associated lately to the scene.
  27740. this._registerTransientComponents();
  27741. this._activeParticles.fetchNewFrame();
  27742. this._totalVertices.fetchNewFrame();
  27743. this._activeIndices.fetchNewFrame();
  27744. this._activeBones.fetchNewFrame();
  27745. this._meshesForIntersections.reset();
  27746. this.resetCachedMaterial();
  27747. this.onBeforeAnimationsObservable.notifyObservers(this);
  27748. // Actions
  27749. if (this.actionManager) {
  27750. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27751. }
  27752. //Simplification Queue
  27753. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27754. this.simplificationQueue.executeNext();
  27755. }
  27756. if (this._engine.isDeterministicLockStep()) {
  27757. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27758. var defaultFPS = (60.0 / 1000.0);
  27759. var defaultFrameTime = 1000 / 60; // frame time in MS
  27760. if (this._physicsEngine) {
  27761. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27762. }
  27763. var stepsTaken = 0;
  27764. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27765. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27766. internalSteps = Math.min(internalSteps, maxSubSteps);
  27767. do {
  27768. this.onBeforeStepObservable.notifyObservers(this);
  27769. // Animations
  27770. this._animationRatio = defaultFrameTime * defaultFPS;
  27771. this._animate();
  27772. this.onAfterAnimationsObservable.notifyObservers(this);
  27773. // Physics
  27774. if (this._physicsEngine) {
  27775. this.onBeforePhysicsObservable.notifyObservers(this);
  27776. this._physicsEngine._step(defaultFrameTime / 1000);
  27777. this.onAfterPhysicsObservable.notifyObservers(this);
  27778. }
  27779. this.onAfterStepObservable.notifyObservers(this);
  27780. this._currentStepId++;
  27781. stepsTaken++;
  27782. deltaTime -= defaultFrameTime;
  27783. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27784. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27785. }
  27786. else {
  27787. // Animations
  27788. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27789. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27790. this._animate();
  27791. this.onAfterAnimationsObservable.notifyObservers(this);
  27792. // Physics
  27793. if (this._physicsEngine) {
  27794. this.onBeforePhysicsObservable.notifyObservers(this);
  27795. this._physicsEngine._step(deltaTime / 1000.0);
  27796. this.onAfterPhysicsObservable.notifyObservers(this);
  27797. }
  27798. }
  27799. // Before camera update steps
  27800. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  27801. var step = _a[_i];
  27802. step.action();
  27803. }
  27804. // Update Cameras
  27805. if (updateCameras) {
  27806. if (this.activeCameras.length > 0) {
  27807. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27808. var camera = this.activeCameras[cameraIndex];
  27809. camera.update();
  27810. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27811. // rig cameras
  27812. for (var index = 0; index < camera._rigCameras.length; index++) {
  27813. camera._rigCameras[index].update();
  27814. }
  27815. }
  27816. }
  27817. }
  27818. else if (this.activeCamera) {
  27819. this.activeCamera.update();
  27820. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27821. // rig cameras
  27822. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27823. this.activeCamera._rigCameras[index].update();
  27824. }
  27825. }
  27826. }
  27827. }
  27828. // Before render
  27829. this.onBeforeRenderObservable.notifyObservers(this);
  27830. // Customs render targets
  27831. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27832. var engine = this.getEngine();
  27833. var currentActiveCamera = this.activeCamera;
  27834. if (this.renderTargetsEnabled) {
  27835. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27836. this._intermediateRendering = true;
  27837. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27838. var renderTarget = this.customRenderTargets[customIndex];
  27839. if (renderTarget._shouldRender()) {
  27840. this._renderId++;
  27841. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27842. if (!this.activeCamera)
  27843. throw new Error("Active camera not set");
  27844. // Viewport
  27845. engine.setViewport(this.activeCamera.viewport);
  27846. // Camera
  27847. this.updateTransformMatrix();
  27848. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27849. }
  27850. }
  27851. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27852. this._intermediateRendering = false;
  27853. this._renderId++;
  27854. }
  27855. // Restore back buffer
  27856. if (this.customRenderTargets.length > 0) {
  27857. engine.restoreDefaultFramebuffer();
  27858. }
  27859. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27860. this.activeCamera = currentActiveCamera;
  27861. // Procedural textures
  27862. if (this.proceduralTexturesEnabled) {
  27863. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27864. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27865. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27866. if (proceduralTexture._shouldRender()) {
  27867. proceduralTexture.render();
  27868. }
  27869. }
  27870. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27871. }
  27872. // Clear
  27873. if (this.autoClearDepthAndStencil || this.autoClear) {
  27874. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27875. }
  27876. // Shadows
  27877. if (this.shadowsEnabled) {
  27878. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27879. var light = this.lights[lightIndex];
  27880. var shadowGenerator = light.getShadowGenerator();
  27881. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27882. var shadowMap = (shadowGenerator.getShadowMap());
  27883. if (this.textures.indexOf(shadowMap) !== -1) {
  27884. this._renderTargets.push(shadowMap);
  27885. }
  27886. }
  27887. }
  27888. }
  27889. // Depth renderer
  27890. for (var key in this._depthRenderer) {
  27891. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27892. }
  27893. // Geometry renderer
  27894. if (this._geometryBufferRenderer) {
  27895. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27896. }
  27897. // RenderPipeline
  27898. if (this._postProcessRenderPipelineManager) {
  27899. this._postProcessRenderPipelineManager.update();
  27900. }
  27901. // Multi-cameras?
  27902. if (this.activeCameras.length > 0) {
  27903. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27904. if (cameraIndex > 0) {
  27905. this._engine.clear(null, false, true, true);
  27906. }
  27907. this._processSubCameras(this.activeCameras[cameraIndex]);
  27908. }
  27909. }
  27910. else {
  27911. if (!this.activeCamera) {
  27912. throw new Error("No camera defined");
  27913. }
  27914. this._processSubCameras(this.activeCamera);
  27915. }
  27916. // Intersection checks
  27917. this._checkIntersections();
  27918. // Update the audio listener attached to the camera
  27919. if (BABYLON.AudioEngine) {
  27920. this._updateAudioParameters();
  27921. }
  27922. // After render
  27923. if (this.afterRender) {
  27924. this.afterRender();
  27925. }
  27926. this.onAfterRenderObservable.notifyObservers(this);
  27927. // Cleaning
  27928. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27929. var data = this._toBeDisposed.data[index];
  27930. if (data) {
  27931. data.dispose();
  27932. }
  27933. this._toBeDisposed[index] = null;
  27934. }
  27935. this._toBeDisposed.reset();
  27936. if (this.dumpNextRenderTargets) {
  27937. this.dumpNextRenderTargets = false;
  27938. }
  27939. this._activeBones.addCount(0, true);
  27940. this._activeIndices.addCount(0, true);
  27941. this._activeParticles.addCount(0, true);
  27942. };
  27943. Scene.prototype._updateAudioParameters = function () {
  27944. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27945. return;
  27946. }
  27947. var listeningCamera;
  27948. var audioEngine = BABYLON.Engine.audioEngine;
  27949. if (this.activeCameras.length > 0) {
  27950. listeningCamera = this.activeCameras[0];
  27951. }
  27952. else {
  27953. listeningCamera = this.activeCamera;
  27954. }
  27955. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27956. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27957. // for VR cameras
  27958. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27959. listeningCamera = listeningCamera.rigCameras[0];
  27960. }
  27961. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27962. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27963. cameraDirection.normalize();
  27964. // To avoid some errors on GearVR
  27965. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27966. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27967. }
  27968. var i;
  27969. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27970. var sound = this.mainSoundTrack.soundCollection[i];
  27971. if (sound.useCustomAttenuation) {
  27972. sound.updateDistanceFromListener();
  27973. }
  27974. }
  27975. for (i = 0; i < this.soundTracks.length; i++) {
  27976. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27977. sound = this.soundTracks[i].soundCollection[j];
  27978. if (sound.useCustomAttenuation) {
  27979. sound.updateDistanceFromListener();
  27980. }
  27981. }
  27982. }
  27983. }
  27984. };
  27985. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27986. // Audio
  27987. /**
  27988. * Gets or sets if audio support is enabled
  27989. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27990. */
  27991. get: function () {
  27992. return this._audioEnabled;
  27993. },
  27994. set: function (value) {
  27995. this._audioEnabled = value;
  27996. if (BABYLON.AudioEngine) {
  27997. if (this._audioEnabled) {
  27998. this._enableAudio();
  27999. }
  28000. else {
  28001. this._disableAudio();
  28002. }
  28003. }
  28004. },
  28005. enumerable: true,
  28006. configurable: true
  28007. });
  28008. Scene.prototype._disableAudio = function () {
  28009. var i;
  28010. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28011. this.mainSoundTrack.soundCollection[i].pause();
  28012. }
  28013. for (i = 0; i < this.soundTracks.length; i++) {
  28014. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28015. this.soundTracks[i].soundCollection[j].pause();
  28016. }
  28017. }
  28018. };
  28019. Scene.prototype._enableAudio = function () {
  28020. var i;
  28021. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28022. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  28023. this.mainSoundTrack.soundCollection[i].play();
  28024. }
  28025. }
  28026. for (i = 0; i < this.soundTracks.length; i++) {
  28027. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28028. if (this.soundTracks[i].soundCollection[j].isPaused) {
  28029. this.soundTracks[i].soundCollection[j].play();
  28030. }
  28031. }
  28032. }
  28033. };
  28034. Object.defineProperty(Scene.prototype, "headphone", {
  28035. /**
  28036. * Gets or sets if audio will be output to headphones
  28037. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28038. */
  28039. get: function () {
  28040. return this._headphone;
  28041. },
  28042. set: function (value) {
  28043. this._headphone = value;
  28044. if (BABYLON.AudioEngine) {
  28045. if (this._headphone) {
  28046. this._switchAudioModeForHeadphones();
  28047. }
  28048. else {
  28049. this._switchAudioModeForNormalSpeakers();
  28050. }
  28051. }
  28052. },
  28053. enumerable: true,
  28054. configurable: true
  28055. });
  28056. Scene.prototype._switchAudioModeForHeadphones = function () {
  28057. this.mainSoundTrack.switchPanningModelToHRTF();
  28058. for (var i = 0; i < this.soundTracks.length; i++) {
  28059. this.soundTracks[i].switchPanningModelToHRTF();
  28060. }
  28061. };
  28062. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  28063. this.mainSoundTrack.switchPanningModelToEqualPower();
  28064. for (var i = 0; i < this.soundTracks.length; i++) {
  28065. this.soundTracks[i].switchPanningModelToEqualPower();
  28066. }
  28067. };
  28068. /**
  28069. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  28070. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  28071. * @returns the created depth renderer
  28072. */
  28073. Scene.prototype.enableDepthRenderer = function (camera) {
  28074. camera = camera || this.activeCamera;
  28075. if (!camera) {
  28076. throw "No camera available to enable depth renderer";
  28077. }
  28078. if (!this._depthRenderer[camera.id]) {
  28079. var textureType = 0;
  28080. if (this._engine.getCaps().textureHalfFloatRender) {
  28081. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  28082. }
  28083. else if (this._engine.getCaps().textureFloatRender) {
  28084. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  28085. }
  28086. else {
  28087. throw "Depth renderer does not support int texture type";
  28088. }
  28089. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  28090. }
  28091. return this._depthRenderer[camera.id];
  28092. };
  28093. /**
  28094. * Disables a depth renderer for a given camera
  28095. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  28096. */
  28097. Scene.prototype.disableDepthRenderer = function (camera) {
  28098. camera = camera || this.activeCamera;
  28099. if (!camera || !this._depthRenderer[camera.id]) {
  28100. return;
  28101. }
  28102. this._depthRenderer[camera.id].dispose();
  28103. delete this._depthRenderer[camera.id];
  28104. };
  28105. /**
  28106. * Enables a GeometryBufferRender and associates it with the scene
  28107. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  28108. * @returns the GeometryBufferRenderer
  28109. */
  28110. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  28111. if (ratio === void 0) { ratio = 1; }
  28112. if (this._geometryBufferRenderer) {
  28113. return this._geometryBufferRenderer;
  28114. }
  28115. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  28116. if (!this._geometryBufferRenderer.isSupported) {
  28117. this._geometryBufferRenderer = null;
  28118. }
  28119. return this._geometryBufferRenderer;
  28120. };
  28121. /**
  28122. * Disables the GeometryBufferRender associated with the scene
  28123. */
  28124. Scene.prototype.disableGeometryBufferRenderer = function () {
  28125. if (!this._geometryBufferRenderer) {
  28126. return;
  28127. }
  28128. this._geometryBufferRenderer.dispose();
  28129. this._geometryBufferRenderer = null;
  28130. };
  28131. /**
  28132. * Freeze all materials
  28133. * A frozen material will not be updatable but should be faster to render
  28134. */
  28135. Scene.prototype.freezeMaterials = function () {
  28136. for (var i = 0; i < this.materials.length; i++) {
  28137. this.materials[i].freeze();
  28138. }
  28139. };
  28140. /**
  28141. * Unfreeze all materials
  28142. * A frozen material will not be updatable but should be faster to render
  28143. */
  28144. Scene.prototype.unfreezeMaterials = function () {
  28145. for (var i = 0; i < this.materials.length; i++) {
  28146. this.materials[i].unfreeze();
  28147. }
  28148. };
  28149. /**
  28150. * Releases all held ressources
  28151. */
  28152. Scene.prototype.dispose = function () {
  28153. this.beforeRender = null;
  28154. this.afterRender = null;
  28155. this.skeletons = [];
  28156. this.morphTargetManagers = [];
  28157. this._transientComponents = [];
  28158. this._isReadyForMeshStage.clear();
  28159. this._beforeEvaluateActiveMeshStage.clear();
  28160. this._evaluateSubMeshStage.clear();
  28161. this._activeMeshStage.clear();
  28162. this._cameraDrawRenderTargetStage.clear();
  28163. this._beforeCameraDrawStage.clear();
  28164. this._beforeRenderingGroupDrawStage.clear();
  28165. this._afterRenderingGroupDrawStage.clear();
  28166. this._afterCameraDrawStage.clear();
  28167. this._beforeCameraUpdateStage.clear();
  28168. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  28169. var component = _a[_i];
  28170. component.dispose();
  28171. }
  28172. this.importedMeshesFiles = new Array();
  28173. this.stopAllAnimations();
  28174. this.resetCachedMaterial();
  28175. for (var key in this._depthRenderer) {
  28176. this._depthRenderer[key].dispose();
  28177. }
  28178. // Smart arrays
  28179. if (this.activeCamera) {
  28180. this.activeCamera._activeMeshes.dispose();
  28181. this.activeCamera = null;
  28182. }
  28183. this._activeMeshes.dispose();
  28184. this._renderingManager.dispose();
  28185. this._processedMaterials.dispose();
  28186. this._activeParticleSystems.dispose();
  28187. this._activeSkeletons.dispose();
  28188. this._softwareSkinnedMeshes.dispose();
  28189. this._renderTargets.dispose();
  28190. this._registeredForLateAnimationBindings.dispose();
  28191. this._meshesForIntersections.dispose();
  28192. this._toBeDisposed.dispose();
  28193. // Abort active requests
  28194. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  28195. var request = _c[_b];
  28196. request.abort();
  28197. }
  28198. // Debug layer
  28199. if (this._debugLayer) {
  28200. this._debugLayer.hide();
  28201. }
  28202. // Events
  28203. this.onDisposeObservable.notifyObservers(this);
  28204. this.onDisposeObservable.clear();
  28205. this.onBeforeRenderObservable.clear();
  28206. this.onAfterRenderObservable.clear();
  28207. this.onBeforeRenderTargetsRenderObservable.clear();
  28208. this.onAfterRenderTargetsRenderObservable.clear();
  28209. this.onAfterStepObservable.clear();
  28210. this.onBeforeStepObservable.clear();
  28211. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28212. this.onAfterActiveMeshesEvaluationObservable.clear();
  28213. this.onBeforeParticlesRenderingObservable.clear();
  28214. this.onAfterParticlesRenderingObservable.clear();
  28215. this.onBeforeSpritesRenderingObservable.clear();
  28216. this.onAfterSpritesRenderingObservable.clear();
  28217. this.onBeforeDrawPhaseObservable.clear();
  28218. this.onAfterDrawPhaseObservable.clear();
  28219. this.onBeforePhysicsObservable.clear();
  28220. this.onAfterPhysicsObservable.clear();
  28221. this.onBeforeAnimationsObservable.clear();
  28222. this.onAfterAnimationsObservable.clear();
  28223. this.onDataLoadedObservable.clear();
  28224. this.onBeforeRenderingGroupObservable.clear();
  28225. this.onAfterRenderingGroupObservable.clear();
  28226. this.detachControl();
  28227. // Release sounds & sounds tracks
  28228. if (BABYLON.AudioEngine) {
  28229. this.disposeSounds();
  28230. }
  28231. // VR Helper
  28232. if (this.VRHelper) {
  28233. this.VRHelper.dispose();
  28234. }
  28235. // Detach cameras
  28236. var canvas = this._engine.getRenderingCanvas();
  28237. if (canvas) {
  28238. var index;
  28239. for (index = 0; index < this.cameras.length; index++) {
  28240. this.cameras[index].detachControl(canvas);
  28241. }
  28242. }
  28243. // Release animation groups
  28244. while (this.animationGroups.length) {
  28245. this.animationGroups[0].dispose();
  28246. }
  28247. // Release lights
  28248. while (this.lights.length) {
  28249. this.lights[0].dispose();
  28250. }
  28251. // Release meshes
  28252. while (this.meshes.length) {
  28253. this.meshes[0].dispose(true);
  28254. }
  28255. while (this.transformNodes.length) {
  28256. this.removeTransformNode(this.transformNodes[0]);
  28257. }
  28258. // Release cameras
  28259. while (this.cameras.length) {
  28260. this.cameras[0].dispose();
  28261. }
  28262. // Release materials
  28263. if (this.defaultMaterial) {
  28264. this.defaultMaterial.dispose();
  28265. }
  28266. while (this.multiMaterials.length) {
  28267. this.multiMaterials[0].dispose();
  28268. }
  28269. while (this.materials.length) {
  28270. this.materials[0].dispose();
  28271. }
  28272. // Release particles
  28273. while (this.particleSystems.length) {
  28274. this.particleSystems[0].dispose();
  28275. }
  28276. // Release sprites
  28277. while (this.spriteManagers.length) {
  28278. this.spriteManagers[0].dispose();
  28279. }
  28280. // Release postProcesses
  28281. while (this.postProcesses.length) {
  28282. this.postProcesses[0].dispose();
  28283. }
  28284. // Release textures
  28285. while (this.textures.length) {
  28286. this.textures[0].dispose();
  28287. }
  28288. // Release UBO
  28289. this._sceneUbo.dispose();
  28290. if (this._alternateSceneUbo) {
  28291. this._alternateSceneUbo.dispose();
  28292. }
  28293. // Post-processes
  28294. this.postProcessManager.dispose();
  28295. if (this._postProcessRenderPipelineManager) {
  28296. this._postProcessRenderPipelineManager.dispose();
  28297. }
  28298. // Physics
  28299. if (this._physicsEngine) {
  28300. this.disablePhysicsEngine();
  28301. }
  28302. // Remove from engine
  28303. index = this._engine.scenes.indexOf(this);
  28304. if (index > -1) {
  28305. this._engine.scenes.splice(index, 1);
  28306. }
  28307. this._engine.wipeCaches(true);
  28308. this._isDisposed = true;
  28309. };
  28310. Object.defineProperty(Scene.prototype, "isDisposed", {
  28311. /**
  28312. * Gets if the scene is already disposed
  28313. */
  28314. get: function () {
  28315. return this._isDisposed;
  28316. },
  28317. enumerable: true,
  28318. configurable: true
  28319. });
  28320. /**
  28321. * Releases sounds & soundtracks
  28322. */
  28323. Scene.prototype.disposeSounds = function () {
  28324. if (!this._mainSoundTrack) {
  28325. return;
  28326. }
  28327. this.mainSoundTrack.dispose();
  28328. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28329. this.soundTracks[scIndex].dispose();
  28330. }
  28331. };
  28332. /**
  28333. * Call this function to reduce memory footprint of the scene.
  28334. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28335. */
  28336. Scene.prototype.clearCachedVertexData = function () {
  28337. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28338. var mesh = this.meshes[meshIndex];
  28339. var geometry = mesh.geometry;
  28340. if (geometry) {
  28341. geometry._indices = [];
  28342. for (var vbName in geometry._vertexBuffers) {
  28343. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28344. continue;
  28345. }
  28346. geometry._vertexBuffers[vbName]._buffer._data = null;
  28347. }
  28348. }
  28349. }
  28350. };
  28351. /**
  28352. * This function will remove the local cached buffer data from texture.
  28353. * It will save memory but will prevent the texture from being rebuilt
  28354. */
  28355. Scene.prototype.cleanCachedTextureBuffer = function () {
  28356. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28357. var baseTexture = _a[_i];
  28358. var buffer = baseTexture._buffer;
  28359. if (buffer) {
  28360. baseTexture._buffer = null;
  28361. }
  28362. }
  28363. };
  28364. // Octrees
  28365. /**
  28366. * Get the world extend vectors with an optional filter
  28367. *
  28368. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28369. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28370. */
  28371. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28372. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28373. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28374. filterPredicate = filterPredicate || (function () { return true; });
  28375. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28376. mesh.computeWorldMatrix(true);
  28377. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28378. return;
  28379. }
  28380. var boundingInfo = mesh.getBoundingInfo();
  28381. var minBox = boundingInfo.boundingBox.minimumWorld;
  28382. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28383. BABYLON.Tools.CheckExtends(minBox, min, max);
  28384. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28385. });
  28386. return {
  28387. min: min,
  28388. max: max
  28389. };
  28390. };
  28391. /**
  28392. * Creates or updates the octree used to boost selection (picking)
  28393. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28394. * @param maxCapacity defines the maximum capacity per leaf
  28395. * @param maxDepth defines the maximum depth of the octree
  28396. * @returns an octree of AbstractMesh
  28397. */
  28398. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28399. if (maxCapacity === void 0) { maxCapacity = 64; }
  28400. if (maxDepth === void 0) { maxDepth = 2; }
  28401. if (!this._selectionOctree) {
  28402. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28403. }
  28404. var worldExtends = this.getWorldExtends();
  28405. // Update octree
  28406. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28407. return this._selectionOctree;
  28408. };
  28409. // Picking
  28410. /**
  28411. * Creates a ray that can be used to pick in the scene
  28412. * @param x defines the x coordinate of the origin (on-screen)
  28413. * @param y defines the y coordinate of the origin (on-screen)
  28414. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28415. * @param camera defines the camera to use for the picking
  28416. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28417. * @returns a Ray
  28418. */
  28419. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28420. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28421. var result = BABYLON.Ray.Zero();
  28422. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28423. return result;
  28424. };
  28425. /**
  28426. * Creates a ray that can be used to pick in the scene
  28427. * @param x defines the x coordinate of the origin (on-screen)
  28428. * @param y defines the y coordinate of the origin (on-screen)
  28429. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28430. * @param result defines the ray where to store the picking ray
  28431. * @param camera defines the camera to use for the picking
  28432. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28433. * @returns the current scene
  28434. */
  28435. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28436. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28437. var engine = this._engine;
  28438. if (!camera) {
  28439. if (!this.activeCamera)
  28440. throw new Error("Active camera not set");
  28441. camera = this.activeCamera;
  28442. }
  28443. var cameraViewport = camera.viewport;
  28444. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28445. // Moving coordinates to local viewport world
  28446. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28447. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28448. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28449. return this;
  28450. };
  28451. /**
  28452. * Creates a ray that can be used to pick in the scene
  28453. * @param x defines the x coordinate of the origin (on-screen)
  28454. * @param y defines the y coordinate of the origin (on-screen)
  28455. * @param camera defines the camera to use for the picking
  28456. * @returns a Ray
  28457. */
  28458. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28459. var result = BABYLON.Ray.Zero();
  28460. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28461. return result;
  28462. };
  28463. /**
  28464. * Creates a ray that can be used to pick in the scene
  28465. * @param x defines the x coordinate of the origin (on-screen)
  28466. * @param y defines the y coordinate of the origin (on-screen)
  28467. * @param result defines the ray where to store the picking ray
  28468. * @param camera defines the camera to use for the picking
  28469. * @returns the current scene
  28470. */
  28471. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28472. if (!BABYLON.PickingInfo) {
  28473. return this;
  28474. }
  28475. var engine = this._engine;
  28476. if (!camera) {
  28477. if (!this.activeCamera)
  28478. throw new Error("Active camera not set");
  28479. camera = this.activeCamera;
  28480. }
  28481. var cameraViewport = camera.viewport;
  28482. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28483. var identity = BABYLON.Matrix.Identity();
  28484. // Moving coordinates to local viewport world
  28485. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28486. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28487. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28488. return this;
  28489. };
  28490. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28491. if (!BABYLON.PickingInfo) {
  28492. return null;
  28493. }
  28494. var pickingInfo = null;
  28495. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28496. var mesh = this.meshes[meshIndex];
  28497. if (predicate) {
  28498. if (!predicate(mesh)) {
  28499. continue;
  28500. }
  28501. }
  28502. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28503. continue;
  28504. }
  28505. var world = mesh.getWorldMatrix();
  28506. var ray = rayFunction(world);
  28507. var result = mesh.intersects(ray, fastCheck);
  28508. if (!result || !result.hit)
  28509. continue;
  28510. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28511. continue;
  28512. pickingInfo = result;
  28513. if (fastCheck) {
  28514. break;
  28515. }
  28516. }
  28517. return pickingInfo || new BABYLON.PickingInfo();
  28518. };
  28519. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28520. if (!BABYLON.PickingInfo) {
  28521. return null;
  28522. }
  28523. var pickingInfos = new Array();
  28524. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28525. var mesh = this.meshes[meshIndex];
  28526. if (predicate) {
  28527. if (!predicate(mesh)) {
  28528. continue;
  28529. }
  28530. }
  28531. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28532. continue;
  28533. }
  28534. var world = mesh.getWorldMatrix();
  28535. var ray = rayFunction(world);
  28536. var result = mesh.intersects(ray, false);
  28537. if (!result || !result.hit)
  28538. continue;
  28539. pickingInfos.push(result);
  28540. }
  28541. return pickingInfos;
  28542. };
  28543. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28544. if (!BABYLON.PickingInfo) {
  28545. return null;
  28546. }
  28547. var pickingInfo = null;
  28548. if (!camera) {
  28549. if (!this.activeCamera) {
  28550. return null;
  28551. }
  28552. camera = this.activeCamera;
  28553. }
  28554. if (this.spriteManagers.length > 0) {
  28555. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28556. var spriteManager = this.spriteManagers[spriteIndex];
  28557. if (!spriteManager.isPickable) {
  28558. continue;
  28559. }
  28560. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28561. if (!result || !result.hit)
  28562. continue;
  28563. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28564. continue;
  28565. pickingInfo = result;
  28566. if (fastCheck) {
  28567. break;
  28568. }
  28569. }
  28570. }
  28571. return pickingInfo || new BABYLON.PickingInfo();
  28572. };
  28573. /** Launch a ray to try to pick a mesh in the scene
  28574. * @param x position on screen
  28575. * @param y position on screen
  28576. * @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
  28577. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28578. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28579. * @returns a PickingInfo
  28580. */
  28581. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28582. var _this = this;
  28583. if (!BABYLON.PickingInfo) {
  28584. return null;
  28585. }
  28586. var result = this._internalPick(function (world) {
  28587. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28588. return _this._tempPickingRay;
  28589. }, predicate, fastCheck);
  28590. if (result) {
  28591. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28592. }
  28593. return result;
  28594. };
  28595. /** Launch a ray to try to pick a sprite in the scene
  28596. * @param x position on screen
  28597. * @param y position on screen
  28598. * @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
  28599. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28600. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28601. * @returns a PickingInfo
  28602. */
  28603. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28604. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28605. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28606. };
  28607. /** Use the given ray to pick a mesh in the scene
  28608. * @param ray The ray to use to pick meshes
  28609. * @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
  28610. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28611. * @returns a PickingInfo
  28612. */
  28613. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28614. var _this = this;
  28615. var result = this._internalPick(function (world) {
  28616. if (!_this._pickWithRayInverseMatrix) {
  28617. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28618. }
  28619. world.invertToRef(_this._pickWithRayInverseMatrix);
  28620. if (!_this._cachedRayForTransform) {
  28621. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28622. }
  28623. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28624. return _this._cachedRayForTransform;
  28625. }, predicate, fastCheck);
  28626. if (result) {
  28627. result.ray = ray;
  28628. }
  28629. return result;
  28630. };
  28631. /**
  28632. * Launch a ray to try to pick a mesh in the scene
  28633. * @param x X position on screen
  28634. * @param y Y position on screen
  28635. * @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
  28636. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28637. * @returns an array of PickingInfo
  28638. */
  28639. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28640. var _this = this;
  28641. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28642. };
  28643. /**
  28644. * Launch a ray to try to pick a mesh in the scene
  28645. * @param ray Ray to use
  28646. * @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
  28647. * @returns an array of PickingInfo
  28648. */
  28649. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28650. var _this = this;
  28651. return this._internalMultiPick(function (world) {
  28652. if (!_this._pickWithRayInverseMatrix) {
  28653. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28654. }
  28655. world.invertToRef(_this._pickWithRayInverseMatrix);
  28656. if (!_this._cachedRayForTransform) {
  28657. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28658. }
  28659. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28660. return _this._cachedRayForTransform;
  28661. }, predicate);
  28662. };
  28663. /**
  28664. * Force the value of meshUnderPointer
  28665. * @param mesh defines the mesh to use
  28666. */
  28667. Scene.prototype.setPointerOverMesh = function (mesh) {
  28668. if (this._pointerOverMesh === mesh) {
  28669. return;
  28670. }
  28671. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28672. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28673. }
  28674. this._pointerOverMesh = mesh;
  28675. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28676. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28677. }
  28678. };
  28679. /**
  28680. * Gets the mesh under the pointer
  28681. * @returns a Mesh or null if no mesh is under the pointer
  28682. */
  28683. Scene.prototype.getPointerOverMesh = function () {
  28684. return this._pointerOverMesh;
  28685. };
  28686. /**
  28687. * Force the sprite under the pointer
  28688. * @param sprite defines the sprite to use
  28689. */
  28690. Scene.prototype.setPointerOverSprite = function (sprite) {
  28691. if (this._pointerOverSprite === sprite) {
  28692. return;
  28693. }
  28694. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28695. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28696. }
  28697. this._pointerOverSprite = sprite;
  28698. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28699. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28700. }
  28701. };
  28702. /**
  28703. * Gets the sprite under the pointer
  28704. * @returns a Sprite or null if no sprite is under the pointer
  28705. */
  28706. Scene.prototype.getPointerOverSprite = function () {
  28707. return this._pointerOverSprite;
  28708. };
  28709. // Physics
  28710. /**
  28711. * Gets the current physics engine
  28712. * @returns a PhysicsEngine or null if none attached
  28713. */
  28714. Scene.prototype.getPhysicsEngine = function () {
  28715. return this._physicsEngine;
  28716. };
  28717. /**
  28718. * Enables physics to the current scene
  28719. * @param gravity defines the scene's gravity for the physics engine
  28720. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28721. * @return a boolean indicating if the physics engine was initialized
  28722. */
  28723. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28724. if (gravity === void 0) { gravity = null; }
  28725. if (this._physicsEngine) {
  28726. return true;
  28727. }
  28728. try {
  28729. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28730. return true;
  28731. }
  28732. catch (e) {
  28733. BABYLON.Tools.Error(e.message);
  28734. return false;
  28735. }
  28736. };
  28737. /**
  28738. * Disables and disposes the physics engine associated with the scene
  28739. */
  28740. Scene.prototype.disablePhysicsEngine = function () {
  28741. if (!this._physicsEngine) {
  28742. return;
  28743. }
  28744. this._physicsEngine.dispose();
  28745. this._physicsEngine = null;
  28746. };
  28747. /**
  28748. * Gets a boolean indicating if there is an active physics engine
  28749. * @returns a boolean indicating if there is an active physics engine
  28750. */
  28751. Scene.prototype.isPhysicsEnabled = function () {
  28752. return this._physicsEngine !== undefined;
  28753. };
  28754. /**
  28755. * Deletes a physics compound impostor
  28756. * @param compound defines the compound to delete
  28757. */
  28758. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28759. var mesh = compound.parts[0].mesh;
  28760. if (mesh.physicsImpostor) {
  28761. mesh.physicsImpostor.dispose( /*true*/);
  28762. mesh.physicsImpostor = null;
  28763. }
  28764. };
  28765. // Misc.
  28766. /** @hidden */
  28767. Scene.prototype._rebuildGeometries = function () {
  28768. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28769. var geometry = _a[_i];
  28770. geometry._rebuild();
  28771. }
  28772. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28773. var mesh = _c[_b];
  28774. mesh._rebuild();
  28775. }
  28776. if (this.postProcessManager) {
  28777. this.postProcessManager._rebuild();
  28778. }
  28779. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28780. var component = _e[_d];
  28781. component.rebuild();
  28782. }
  28783. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28784. var system = _g[_f];
  28785. system.rebuild();
  28786. }
  28787. if (this._postProcessRenderPipelineManager) {
  28788. this._postProcessRenderPipelineManager._rebuild();
  28789. }
  28790. };
  28791. /** @hidden */
  28792. Scene.prototype._rebuildTextures = function () {
  28793. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28794. var texture = _a[_i];
  28795. texture._rebuild();
  28796. }
  28797. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28798. };
  28799. /**
  28800. * Creates a default light for the scene.
  28801. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-light
  28802. * @param replace has the default false, when true replaces the existing lights in the scene with a hemispheric light
  28803. */
  28804. Scene.prototype.createDefaultLight = function (replace) {
  28805. if (replace === void 0) { replace = false; }
  28806. // Dispose existing light in replace mode.
  28807. if (replace) {
  28808. if (this.lights) {
  28809. for (var i = 0; i < this.lights.length; i++) {
  28810. this.lights[i].dispose();
  28811. }
  28812. }
  28813. }
  28814. // Light
  28815. if (this.lights.length === 0) {
  28816. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28817. }
  28818. };
  28819. /**
  28820. * Creates a default camera for the scene.
  28821. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-camera
  28822. * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera
  28823. * @param replace has default false, when true replaces the active camera in the scene
  28824. * @param attachCameraControls has default false, when true attaches camera controls to the canvas.
  28825. */
  28826. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28827. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28828. if (replace === void 0) { replace = false; }
  28829. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28830. // Dispose existing camera in replace mode.
  28831. if (replace) {
  28832. if (this.activeCamera) {
  28833. this.activeCamera.dispose();
  28834. this.activeCamera = null;
  28835. }
  28836. }
  28837. // Camera
  28838. if (!this.activeCamera) {
  28839. var worldExtends = this.getWorldExtends();
  28840. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28841. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28842. var camera;
  28843. var radius = worldSize.length() * 1.5;
  28844. // empty scene scenario!
  28845. if (!isFinite(radius)) {
  28846. radius = 1;
  28847. worldCenter.copyFromFloats(0, 0, 0);
  28848. }
  28849. if (createArcRotateCamera) {
  28850. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28851. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28852. arcRotateCamera.wheelPrecision = 100 / radius;
  28853. camera = arcRotateCamera;
  28854. }
  28855. else {
  28856. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28857. freeCamera.setTarget(worldCenter);
  28858. camera = freeCamera;
  28859. }
  28860. camera.minZ = radius * 0.01;
  28861. camera.maxZ = radius * 1000;
  28862. camera.speed = radius * 0.2;
  28863. this.activeCamera = camera;
  28864. var canvas = this.getEngine().getRenderingCanvas();
  28865. if (attachCameraControls && canvas) {
  28866. camera.attachControl(canvas);
  28867. }
  28868. }
  28869. };
  28870. /**
  28871. * Creates a default camera and a default light.
  28872. * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-camera-or-light
  28873. * @param createArcRotateCamera has the default false which creates a free camera, when true creates an arc rotate camera
  28874. * @param replace has the default false, when true replaces the active camera/light in the scene
  28875. * @param attachCameraControls has the default false, when true attaches camera controls to the canvas.
  28876. */
  28877. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28878. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28879. if (replace === void 0) { replace = false; }
  28880. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28881. this.createDefaultLight(replace);
  28882. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28883. };
  28884. /**
  28885. * Creates a new sky box
  28886. * @see http://doc.babylonjs.com/how_to/Fast_Build#create-default-skybox
  28887. * @param environmentTexture defines the texture to use as environment texture
  28888. * @param pbr has default false which requires the StandardMaterial to be used, when true PBRMaterial must be used
  28889. * @param scale defines the overall scale of the skybox
  28890. * @param blur is only available when pbr is true, default is 0, no blur, maximum value is 1
  28891. * @param setGlobalEnvTexture has default true indicating that scene.environmentTexture must match the current skybox texture
  28892. * @returns a new mesh holding the sky box
  28893. */
  28894. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28895. if (pbr === void 0) { pbr = false; }
  28896. if (scale === void 0) { scale = 1000; }
  28897. if (blur === void 0) { blur = 0; }
  28898. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28899. if (!environmentTexture) {
  28900. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28901. return null;
  28902. }
  28903. if (setGlobalEnvTexture) {
  28904. if (environmentTexture) {
  28905. this.environmentTexture = environmentTexture;
  28906. }
  28907. }
  28908. // Skybox
  28909. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28910. if (pbr) {
  28911. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28912. hdrSkyboxMaterial.backFaceCulling = false;
  28913. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28914. if (hdrSkyboxMaterial.reflectionTexture) {
  28915. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28916. }
  28917. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28918. hdrSkyboxMaterial.disableLighting = true;
  28919. hdrSkyboxMaterial.twoSidedLighting = true;
  28920. hdrSkybox.infiniteDistance = true;
  28921. hdrSkybox.material = hdrSkyboxMaterial;
  28922. }
  28923. else {
  28924. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28925. skyboxMaterial.backFaceCulling = false;
  28926. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28927. if (skyboxMaterial.reflectionTexture) {
  28928. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28929. }
  28930. skyboxMaterial.disableLighting = true;
  28931. hdrSkybox.infiniteDistance = true;
  28932. hdrSkybox.material = skyboxMaterial;
  28933. }
  28934. return hdrSkybox;
  28935. };
  28936. /**
  28937. * Creates a new environment
  28938. * @see http://doc.babylonjs.com/How_To/Fast_Build#create-default-environment
  28939. * @param options defines the options you can use to configure the environment
  28940. * @returns the new EnvironmentHelper
  28941. */
  28942. Scene.prototype.createDefaultEnvironment = function (options) {
  28943. if (BABYLON.EnvironmentHelper) {
  28944. return new BABYLON.EnvironmentHelper(options, this);
  28945. }
  28946. return null;
  28947. };
  28948. /**
  28949. * Creates a new VREXperienceHelper
  28950. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28951. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28952. * @returns a new VREXperienceHelper
  28953. */
  28954. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28955. if (webVROptions === void 0) { webVROptions = {}; }
  28956. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28957. };
  28958. // Tags
  28959. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28960. if (tagsQuery === undefined) {
  28961. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28962. return list;
  28963. }
  28964. var listByTags = [];
  28965. forEach = forEach || (function (item) { return; });
  28966. for (var i in list) {
  28967. var item = list[i];
  28968. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28969. listByTags.push(item);
  28970. forEach(item);
  28971. }
  28972. }
  28973. return listByTags;
  28974. };
  28975. /**
  28976. * Get a list of meshes by tags
  28977. * @param tagsQuery defines the tags query to use
  28978. * @param forEach defines a predicate used to filter results
  28979. * @returns an array of Mesh
  28980. */
  28981. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28982. return this._getByTags(this.meshes, tagsQuery, forEach);
  28983. };
  28984. /**
  28985. * Get a list of cameras by tags
  28986. * @param tagsQuery defines the tags query to use
  28987. * @param forEach defines a predicate used to filter results
  28988. * @returns an array of Camera
  28989. */
  28990. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28991. return this._getByTags(this.cameras, tagsQuery, forEach);
  28992. };
  28993. /**
  28994. * Get a list of lights by tags
  28995. * @param tagsQuery defines the tags query to use
  28996. * @param forEach defines a predicate used to filter results
  28997. * @returns an array of Light
  28998. */
  28999. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29000. return this._getByTags(this.lights, tagsQuery, forEach);
  29001. };
  29002. /**
  29003. * Get a list of materials by tags
  29004. * @param tagsQuery defines the tags query to use
  29005. * @param forEach defines a predicate used to filter results
  29006. * @returns an array of Material
  29007. */
  29008. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29009. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29010. };
  29011. /**
  29012. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29013. * This allowed control for front to back rendering or reversly depending of the special needs.
  29014. *
  29015. * @param renderingGroupId The rendering group id corresponding to its index
  29016. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29017. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29018. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29019. */
  29020. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29021. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29022. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29023. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29024. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29025. };
  29026. /**
  29027. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29028. *
  29029. * @param renderingGroupId The rendering group id corresponding to its index
  29030. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29031. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29032. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29033. */
  29034. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29035. if (depth === void 0) { depth = true; }
  29036. if (stencil === void 0) { stencil = true; }
  29037. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29038. };
  29039. /**
  29040. * Gets the current auto clear configuration for one rendering group of the rendering
  29041. * manager.
  29042. * @param index the rendering group index to get the information for
  29043. * @returns The auto clear setup for the requested rendering group
  29044. */
  29045. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  29046. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  29047. };
  29048. /**
  29049. * Will flag all materials as dirty to trigger new shader compilation
  29050. * @param flag defines the flag used to specify which material part must be marked as dirty
  29051. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29052. */
  29053. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29054. if (this.blockMaterialDirtyMechanism) {
  29055. return;
  29056. }
  29057. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29058. var material = _a[_i];
  29059. if (predicate && !predicate(material)) {
  29060. continue;
  29061. }
  29062. material.markAsDirty(flag);
  29063. }
  29064. };
  29065. /** @hidden */
  29066. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29067. var _this = this;
  29068. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29069. this._activeRequests.push(request);
  29070. request.onCompleteObservable.add(function (request) {
  29071. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29072. });
  29073. return request;
  29074. };
  29075. /** @hidden */
  29076. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29077. var _this = this;
  29078. return new Promise(function (resolve, reject) {
  29079. _this._loadFile(url, function (data) {
  29080. resolve(data);
  29081. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29082. reject(exception);
  29083. });
  29084. });
  29085. };
  29086. // Statics
  29087. Scene._uniqueIdCounter = 0;
  29088. /** The fog is deactivated */
  29089. Scene.FOGMODE_NONE = 0;
  29090. /** The fog density is following an exponential function */
  29091. Scene.FOGMODE_EXP = 1;
  29092. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  29093. Scene.FOGMODE_EXP2 = 2;
  29094. /** The fog density is following a linear function. */
  29095. Scene.FOGMODE_LINEAR = 3;
  29096. /**
  29097. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29098. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29099. */
  29100. Scene.MinDeltaTime = 1.0;
  29101. /**
  29102. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29103. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29104. */
  29105. Scene.MaxDeltaTime = 1000.0;
  29106. /** The distance in pixel that you have to move to prevent some events */
  29107. Scene.DragMovementThreshold = 10; // in pixels
  29108. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29109. Scene.LongPressDelay = 500; // in milliseconds
  29110. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29111. Scene.DoubleClickDelay = 300; // in milliseconds
  29112. /** If you need to check double click without raising a single click at first click, enable this flag */
  29113. Scene.ExclusiveDoubleClickMode = false;
  29114. return Scene;
  29115. }(BABYLON.AbstractScene));
  29116. BABYLON.Scene = Scene;
  29117. })(BABYLON || (BABYLON = {}));
  29118. //# sourceMappingURL=babylon.scene.js.map
  29119. var BABYLON;
  29120. (function (BABYLON) {
  29121. /**
  29122. * Set of assets to keep when moving a scene into an asset container.
  29123. */
  29124. var KeepAssets = /** @class */ (function (_super) {
  29125. __extends(KeepAssets, _super);
  29126. function KeepAssets() {
  29127. return _super !== null && _super.apply(this, arguments) || this;
  29128. }
  29129. return KeepAssets;
  29130. }(BABYLON.AbstractScene));
  29131. BABYLON.KeepAssets = KeepAssets;
  29132. /**
  29133. * Container with a set of assets that can be added or removed from a scene.
  29134. */
  29135. var AssetContainer = /** @class */ (function (_super) {
  29136. __extends(AssetContainer, _super);
  29137. /**
  29138. * Instantiates an AssetContainer.
  29139. * @param scene The scene the AssetContainer belongs to.
  29140. */
  29141. function AssetContainer(scene) {
  29142. var _this = _super.call(this) || this;
  29143. _this.scene = scene;
  29144. return _this;
  29145. }
  29146. /**
  29147. * Adds all the assets from the container to the scene.
  29148. */
  29149. AssetContainer.prototype.addAllToScene = function () {
  29150. var _this = this;
  29151. this.cameras.forEach(function (o) {
  29152. _this.scene.addCamera(o);
  29153. });
  29154. this.lights.forEach(function (o) {
  29155. _this.scene.addLight(o);
  29156. });
  29157. this.meshes.forEach(function (o) {
  29158. _this.scene.addMesh(o);
  29159. });
  29160. this.skeletons.forEach(function (o) {
  29161. _this.scene.addSkeleton(o);
  29162. });
  29163. this.animations.forEach(function (o) {
  29164. _this.scene.addAnimation(o);
  29165. });
  29166. this.animationGroups.forEach(function (o) {
  29167. _this.scene.addAnimationGroup(o);
  29168. });
  29169. this.multiMaterials.forEach(function (o) {
  29170. _this.scene.addMultiMaterial(o);
  29171. });
  29172. this.materials.forEach(function (o) {
  29173. _this.scene.addMaterial(o);
  29174. });
  29175. this.morphTargetManagers.forEach(function (o) {
  29176. _this.scene.addMorphTargetManager(o);
  29177. });
  29178. this.geometries.forEach(function (o) {
  29179. _this.scene.addGeometry(o);
  29180. });
  29181. this.transformNodes.forEach(function (o) {
  29182. _this.scene.addTransformNode(o);
  29183. });
  29184. this.actionManagers.forEach(function (o) {
  29185. _this.scene.addActionManager(o);
  29186. });
  29187. this.sounds.forEach(function (o) {
  29188. o.play();
  29189. o.autoplay = true;
  29190. _this.scene.mainSoundTrack.AddSound(o);
  29191. });
  29192. this.textures.forEach(function (o) {
  29193. _this.scene.addTexture(o);
  29194. });
  29195. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29196. var component = _a[_i];
  29197. component.addFromContainer(this.scene);
  29198. }
  29199. };
  29200. /**
  29201. * Removes all the assets in the container from the scene
  29202. */
  29203. AssetContainer.prototype.removeAllFromScene = function () {
  29204. var _this = this;
  29205. this.cameras.forEach(function (o) {
  29206. _this.scene.removeCamera(o);
  29207. });
  29208. this.lights.forEach(function (o) {
  29209. _this.scene.removeLight(o);
  29210. });
  29211. this.meshes.forEach(function (o) {
  29212. _this.scene.removeMesh(o);
  29213. });
  29214. this.skeletons.forEach(function (o) {
  29215. _this.scene.removeSkeleton(o);
  29216. });
  29217. this.animations.forEach(function (o) {
  29218. _this.scene.removeAnimation(o);
  29219. });
  29220. this.animationGroups.forEach(function (o) {
  29221. _this.scene.removeAnimationGroup(o);
  29222. });
  29223. this.multiMaterials.forEach(function (o) {
  29224. _this.scene.removeMultiMaterial(o);
  29225. });
  29226. this.materials.forEach(function (o) {
  29227. _this.scene.removeMaterial(o);
  29228. });
  29229. this.morphTargetManagers.forEach(function (o) {
  29230. _this.scene.removeMorphTargetManager(o);
  29231. });
  29232. this.geometries.forEach(function (o) {
  29233. _this.scene.removeGeometry(o);
  29234. });
  29235. this.transformNodes.forEach(function (o) {
  29236. _this.scene.removeTransformNode(o);
  29237. });
  29238. this.actionManagers.forEach(function (o) {
  29239. _this.scene.removeActionManager(o);
  29240. });
  29241. this.sounds.forEach(function (o) {
  29242. o.stop();
  29243. o.autoplay = false;
  29244. _this.scene.mainSoundTrack.RemoveSound(o);
  29245. });
  29246. this.textures.forEach(function (o) {
  29247. _this.scene.removeTexture(o);
  29248. });
  29249. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29250. var component = _a[_i];
  29251. component.removeFromContainer(this.scene);
  29252. }
  29253. };
  29254. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29255. if (!sourceAssets) {
  29256. return;
  29257. }
  29258. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29259. var asset = sourceAssets_1[_i];
  29260. var move = true;
  29261. if (keepAssets) {
  29262. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29263. var keepAsset = keepAssets_1[_a];
  29264. if (asset === keepAsset) {
  29265. move = false;
  29266. break;
  29267. }
  29268. }
  29269. }
  29270. if (move) {
  29271. targetAssets.push(asset);
  29272. }
  29273. }
  29274. };
  29275. /**
  29276. * Removes all the assets contained in the scene and adds them to the container.
  29277. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29278. */
  29279. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29280. if (keepAssets === undefined) {
  29281. keepAssets = new KeepAssets();
  29282. }
  29283. for (var key in this) {
  29284. if (this.hasOwnProperty(key)) {
  29285. this[key] = this[key] || [];
  29286. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  29287. }
  29288. }
  29289. this.removeAllFromScene();
  29290. };
  29291. /**
  29292. * 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.
  29293. * @returns the root mesh
  29294. */
  29295. AssetContainer.prototype.createRootMesh = function () {
  29296. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29297. this.meshes.forEach(function (m) {
  29298. if (!m.parent) {
  29299. rootMesh.addChild(m);
  29300. }
  29301. });
  29302. this.meshes.unshift(rootMesh);
  29303. return rootMesh;
  29304. };
  29305. return AssetContainer;
  29306. }(BABYLON.AbstractScene));
  29307. BABYLON.AssetContainer = AssetContainer;
  29308. })(BABYLON || (BABYLON = {}));
  29309. //# sourceMappingURL=babylon.assetContainer.js.map
  29310. var BABYLON;
  29311. (function (BABYLON) {
  29312. var Buffer = /** @class */ (function () {
  29313. /**
  29314. * Constructor
  29315. * @param engine the engine
  29316. * @param data the data to use for this buffer
  29317. * @param updatable whether the data is updatable
  29318. * @param stride the stride (optional)
  29319. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29320. * @param instanced whether the buffer is instanced (optional)
  29321. * @param useBytes set to true if the stride in in bytes (optional)
  29322. */
  29323. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29324. if (stride === void 0) { stride = 0; }
  29325. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29326. if (instanced === void 0) { instanced = false; }
  29327. if (useBytes === void 0) { useBytes = false; }
  29328. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29329. this._engine = engine.getScene().getEngine();
  29330. }
  29331. else {
  29332. this._engine = engine;
  29333. }
  29334. this._updatable = updatable;
  29335. this._instanced = instanced;
  29336. this._data = data;
  29337. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29338. if (!postponeInternalCreation) { // by default
  29339. this.create();
  29340. }
  29341. }
  29342. /**
  29343. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29344. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29345. * @param offset defines offset in the buffer (0 by default)
  29346. * @param size defines the size in floats of attributes (position is 3 for instance)
  29347. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29348. * @param instanced defines if the vertex buffer contains indexed data
  29349. * @param useBytes defines if the offset and stride are in bytes
  29350. * @returns the new vertex buffer
  29351. */
  29352. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29353. if (useBytes === void 0) { useBytes = false; }
  29354. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29355. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29356. // a lot of these parameters are ignored as they are overriden by the buffer
  29357. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29358. };
  29359. // Properties
  29360. Buffer.prototype.isUpdatable = function () {
  29361. return this._updatable;
  29362. };
  29363. Buffer.prototype.getData = function () {
  29364. return this._data;
  29365. };
  29366. Buffer.prototype.getBuffer = function () {
  29367. return this._buffer;
  29368. };
  29369. /**
  29370. * Gets the stride in float32 units (i.e. byte stride / 4).
  29371. * May not be an integer if the byte stride is not divisible by 4.
  29372. * DEPRECATED. Use byteStride instead.
  29373. * @returns the stride in float32 units
  29374. */
  29375. Buffer.prototype.getStrideSize = function () {
  29376. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29377. };
  29378. // Methods
  29379. Buffer.prototype.create = function (data) {
  29380. if (data === void 0) { data = null; }
  29381. if (!data && this._buffer) {
  29382. return; // nothing to do
  29383. }
  29384. data = data || this._data;
  29385. if (!data) {
  29386. return;
  29387. }
  29388. if (!this._buffer) { // create buffer
  29389. if (this._updatable) {
  29390. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29391. this._data = data;
  29392. }
  29393. else {
  29394. this._buffer = this._engine.createVertexBuffer(data);
  29395. }
  29396. }
  29397. else if (this._updatable) { // update buffer
  29398. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29399. this._data = data;
  29400. }
  29401. };
  29402. /** @hidden */
  29403. Buffer.prototype._rebuild = function () {
  29404. this._buffer = null;
  29405. this.create(this._data);
  29406. };
  29407. Buffer.prototype.update = function (data) {
  29408. this.create(data);
  29409. };
  29410. /**
  29411. * Updates the data directly.
  29412. * @param data the new data
  29413. * @param offset the new offset
  29414. * @param vertexCount the vertex count (optional)
  29415. * @param useBytes set to true if the offset is in bytes
  29416. */
  29417. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29418. if (useBytes === void 0) { useBytes = false; }
  29419. if (!this._buffer) {
  29420. return;
  29421. }
  29422. if (this._updatable) { // update buffer
  29423. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29424. this._data = null;
  29425. }
  29426. };
  29427. Buffer.prototype.dispose = function () {
  29428. if (!this._buffer) {
  29429. return;
  29430. }
  29431. if (this._engine._releaseBuffer(this._buffer)) {
  29432. this._buffer = null;
  29433. }
  29434. };
  29435. return Buffer;
  29436. }());
  29437. BABYLON.Buffer = Buffer;
  29438. })(BABYLON || (BABYLON = {}));
  29439. //# sourceMappingURL=babylon.buffer.js.map
  29440. var BABYLON;
  29441. (function (BABYLON) {
  29442. var VertexBuffer = /** @class */ (function () {
  29443. /**
  29444. * Constructor
  29445. * @param engine the engine
  29446. * @param data the data to use for this vertex buffer
  29447. * @param kind the vertex buffer kind
  29448. * @param updatable whether the data is updatable
  29449. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29450. * @param stride the stride (optional)
  29451. * @param instanced whether the buffer is instanced (optional)
  29452. * @param offset the offset of the data (optional)
  29453. * @param size the number of components (optional)
  29454. * @param type the type of the component (optional)
  29455. * @param normalized whether the data contains normalized data (optional)
  29456. * @param useBytes set to true if stride and offset are in bytes (optional)
  29457. */
  29458. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29459. if (normalized === void 0) { normalized = false; }
  29460. if (useBytes === void 0) { useBytes = false; }
  29461. if (data instanceof BABYLON.Buffer) {
  29462. this._buffer = data;
  29463. this._ownsBuffer = false;
  29464. }
  29465. else {
  29466. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29467. this._ownsBuffer = true;
  29468. }
  29469. this._kind = kind;
  29470. if (type == undefined) {
  29471. var data_1 = this.getData();
  29472. this.type = VertexBuffer.FLOAT;
  29473. if (data_1 instanceof Int8Array)
  29474. this.type = VertexBuffer.BYTE;
  29475. else if (data_1 instanceof Uint8Array)
  29476. this.type = VertexBuffer.UNSIGNED_BYTE;
  29477. else if (data_1 instanceof Int16Array)
  29478. this.type = VertexBuffer.SHORT;
  29479. else if (data_1 instanceof Uint16Array)
  29480. this.type = VertexBuffer.UNSIGNED_SHORT;
  29481. else if (data_1 instanceof Int32Array)
  29482. this.type = VertexBuffer.INT;
  29483. else if (data_1 instanceof Uint32Array)
  29484. this.type = VertexBuffer.UNSIGNED_INT;
  29485. }
  29486. else {
  29487. this.type = type;
  29488. }
  29489. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29490. if (useBytes) {
  29491. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29492. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29493. this.byteOffset = offset || 0;
  29494. }
  29495. else {
  29496. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29497. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29498. this.byteOffset = (offset || 0) * typeByteLength;
  29499. }
  29500. this.normalized = normalized;
  29501. this._instanced = instanced !== undefined ? instanced : false;
  29502. this._instanceDivisor = instanced ? 1 : 0;
  29503. }
  29504. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29505. /**
  29506. * Gets or sets the instance divisor when in instanced mode
  29507. */
  29508. get: function () {
  29509. return this._instanceDivisor;
  29510. },
  29511. set: function (value) {
  29512. this._instanceDivisor = value;
  29513. if (value == 0) {
  29514. this._instanced = false;
  29515. }
  29516. else {
  29517. this._instanced = true;
  29518. }
  29519. },
  29520. enumerable: true,
  29521. configurable: true
  29522. });
  29523. /** @hidden */
  29524. VertexBuffer.prototype._rebuild = function () {
  29525. if (!this._buffer) {
  29526. return;
  29527. }
  29528. this._buffer._rebuild();
  29529. };
  29530. /**
  29531. * Returns the kind of the VertexBuffer (string).
  29532. */
  29533. VertexBuffer.prototype.getKind = function () {
  29534. return this._kind;
  29535. };
  29536. // Properties
  29537. /**
  29538. * Boolean : is the VertexBuffer updatable ?
  29539. */
  29540. VertexBuffer.prototype.isUpdatable = function () {
  29541. return this._buffer.isUpdatable();
  29542. };
  29543. /**
  29544. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29545. */
  29546. VertexBuffer.prototype.getData = function () {
  29547. return this._buffer.getData();
  29548. };
  29549. /**
  29550. * Returns the WebGLBuffer associated to the VertexBuffer.
  29551. */
  29552. VertexBuffer.prototype.getBuffer = function () {
  29553. return this._buffer.getBuffer();
  29554. };
  29555. /**
  29556. * Returns the stride as a multiple of the type byte length.
  29557. * DEPRECATED. Use byteStride instead.
  29558. */
  29559. VertexBuffer.prototype.getStrideSize = function () {
  29560. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29561. };
  29562. /**
  29563. * Returns the offset as a multiple of the type byte length.
  29564. * DEPRECATED. Use byteOffset instead.
  29565. */
  29566. VertexBuffer.prototype.getOffset = function () {
  29567. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29568. };
  29569. /**
  29570. * Returns the number of components per vertex attribute (integer).
  29571. */
  29572. VertexBuffer.prototype.getSize = function () {
  29573. return this._size;
  29574. };
  29575. /**
  29576. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29577. */
  29578. VertexBuffer.prototype.getIsInstanced = function () {
  29579. return this._instanced;
  29580. };
  29581. /**
  29582. * Returns the instancing divisor, zero for non-instanced (integer).
  29583. */
  29584. VertexBuffer.prototype.getInstanceDivisor = function () {
  29585. return this._instanceDivisor;
  29586. };
  29587. // Methods
  29588. /**
  29589. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29590. * Returns the created WebGLBuffer.
  29591. */
  29592. VertexBuffer.prototype.create = function (data) {
  29593. return this._buffer.create(data);
  29594. };
  29595. /**
  29596. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29597. * This function will create a new buffer if the current one is not updatable
  29598. * Returns the updated WebGLBuffer.
  29599. */
  29600. VertexBuffer.prototype.update = function (data) {
  29601. return this._buffer.update(data);
  29602. };
  29603. /**
  29604. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29605. * Returns the directly updated WebGLBuffer.
  29606. * @param data the new data
  29607. * @param offset the new offset
  29608. * @param useBytes set to true if the offset is in bytes
  29609. */
  29610. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29611. if (useBytes === void 0) { useBytes = false; }
  29612. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29613. };
  29614. /**
  29615. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29616. */
  29617. VertexBuffer.prototype.dispose = function () {
  29618. if (this._ownsBuffer) {
  29619. this._buffer.dispose();
  29620. }
  29621. };
  29622. /**
  29623. * Enumerates each value of this vertex buffer as numbers.
  29624. * @param count the number of values to enumerate
  29625. * @param callback the callback function called for each value
  29626. */
  29627. VertexBuffer.prototype.forEach = function (count, callback) {
  29628. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29629. };
  29630. Object.defineProperty(VertexBuffer, "PositionKind", {
  29631. get: function () {
  29632. return VertexBuffer._PositionKind;
  29633. },
  29634. enumerable: true,
  29635. configurable: true
  29636. });
  29637. Object.defineProperty(VertexBuffer, "NormalKind", {
  29638. get: function () {
  29639. return VertexBuffer._NormalKind;
  29640. },
  29641. enumerable: true,
  29642. configurable: true
  29643. });
  29644. Object.defineProperty(VertexBuffer, "TangentKind", {
  29645. get: function () {
  29646. return VertexBuffer._TangentKind;
  29647. },
  29648. enumerable: true,
  29649. configurable: true
  29650. });
  29651. Object.defineProperty(VertexBuffer, "UVKind", {
  29652. get: function () {
  29653. return VertexBuffer._UVKind;
  29654. },
  29655. enumerable: true,
  29656. configurable: true
  29657. });
  29658. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29659. get: function () {
  29660. return VertexBuffer._UV2Kind;
  29661. },
  29662. enumerable: true,
  29663. configurable: true
  29664. });
  29665. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29666. get: function () {
  29667. return VertexBuffer._UV3Kind;
  29668. },
  29669. enumerable: true,
  29670. configurable: true
  29671. });
  29672. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29673. get: function () {
  29674. return VertexBuffer._UV4Kind;
  29675. },
  29676. enumerable: true,
  29677. configurable: true
  29678. });
  29679. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29680. get: function () {
  29681. return VertexBuffer._UV5Kind;
  29682. },
  29683. enumerable: true,
  29684. configurable: true
  29685. });
  29686. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29687. get: function () {
  29688. return VertexBuffer._UV6Kind;
  29689. },
  29690. enumerable: true,
  29691. configurable: true
  29692. });
  29693. Object.defineProperty(VertexBuffer, "ColorKind", {
  29694. get: function () {
  29695. return VertexBuffer._ColorKind;
  29696. },
  29697. enumerable: true,
  29698. configurable: true
  29699. });
  29700. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29701. get: function () {
  29702. return VertexBuffer._MatricesIndicesKind;
  29703. },
  29704. enumerable: true,
  29705. configurable: true
  29706. });
  29707. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29708. get: function () {
  29709. return VertexBuffer._MatricesWeightsKind;
  29710. },
  29711. enumerable: true,
  29712. configurable: true
  29713. });
  29714. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29715. get: function () {
  29716. return VertexBuffer._MatricesIndicesExtraKind;
  29717. },
  29718. enumerable: true,
  29719. configurable: true
  29720. });
  29721. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29722. get: function () {
  29723. return VertexBuffer._MatricesWeightsExtraKind;
  29724. },
  29725. enumerable: true,
  29726. configurable: true
  29727. });
  29728. /**
  29729. * Deduces the stride given a kind.
  29730. * @param kind The kind string to deduce
  29731. * @returns The deduced stride
  29732. */
  29733. VertexBuffer.DeduceStride = function (kind) {
  29734. switch (kind) {
  29735. case VertexBuffer.UVKind:
  29736. case VertexBuffer.UV2Kind:
  29737. case VertexBuffer.UV3Kind:
  29738. case VertexBuffer.UV4Kind:
  29739. case VertexBuffer.UV5Kind:
  29740. case VertexBuffer.UV6Kind:
  29741. return 2;
  29742. case VertexBuffer.NormalKind:
  29743. case VertexBuffer.PositionKind:
  29744. return 3;
  29745. case VertexBuffer.ColorKind:
  29746. case VertexBuffer.MatricesIndicesKind:
  29747. case VertexBuffer.MatricesIndicesExtraKind:
  29748. case VertexBuffer.MatricesWeightsKind:
  29749. case VertexBuffer.MatricesWeightsExtraKind:
  29750. case VertexBuffer.TangentKind:
  29751. return 4;
  29752. default:
  29753. throw new Error("Invalid kind '" + kind + "'");
  29754. }
  29755. };
  29756. /**
  29757. * Gets the byte length of the given type.
  29758. * @param type the type
  29759. * @returns the number of bytes
  29760. */
  29761. VertexBuffer.GetTypeByteLength = function (type) {
  29762. switch (type) {
  29763. case VertexBuffer.BYTE:
  29764. case VertexBuffer.UNSIGNED_BYTE:
  29765. return 1;
  29766. case VertexBuffer.SHORT:
  29767. case VertexBuffer.UNSIGNED_SHORT:
  29768. return 2;
  29769. case VertexBuffer.INT:
  29770. case VertexBuffer.FLOAT:
  29771. return 4;
  29772. default:
  29773. throw new Error("Invalid type '" + type + "'");
  29774. }
  29775. };
  29776. /**
  29777. * Enumerates each value of the given parameters as numbers.
  29778. * @param data the data to enumerate
  29779. * @param byteOffset the byte offset of the data
  29780. * @param byteStride the byte stride of the data
  29781. * @param componentCount the number of components per element
  29782. * @param componentType the type of the component
  29783. * @param count the total number of components
  29784. * @param normalized whether the data is normalized
  29785. * @param callback the callback function called for each value
  29786. */
  29787. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29788. if (data instanceof Array) {
  29789. var offset = byteOffset / 4;
  29790. var stride = byteStride / 4;
  29791. for (var index = 0; index < count; index += componentCount) {
  29792. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29793. callback(data[offset + componentIndex], index + componentIndex);
  29794. }
  29795. offset += stride;
  29796. }
  29797. }
  29798. else {
  29799. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29800. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29801. for (var index = 0; index < count; index += componentCount) {
  29802. var componentByteOffset = byteOffset;
  29803. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29804. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29805. callback(value, index + componentIndex);
  29806. componentByteOffset += componentByteLength;
  29807. }
  29808. byteOffset += byteStride;
  29809. }
  29810. }
  29811. };
  29812. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29813. switch (type) {
  29814. case VertexBuffer.BYTE: {
  29815. var value = dataView.getInt8(byteOffset);
  29816. if (normalized) {
  29817. value = Math.max(value / 127, -1);
  29818. }
  29819. return value;
  29820. }
  29821. case VertexBuffer.UNSIGNED_BYTE: {
  29822. var value = dataView.getUint8(byteOffset);
  29823. if (normalized) {
  29824. value = value / 255;
  29825. }
  29826. return value;
  29827. }
  29828. case VertexBuffer.SHORT: {
  29829. var value = dataView.getInt16(byteOffset, true);
  29830. if (normalized) {
  29831. value = Math.max(value / 16383, -1);
  29832. }
  29833. return value;
  29834. }
  29835. case VertexBuffer.UNSIGNED_SHORT: {
  29836. var value = dataView.getUint16(byteOffset, true);
  29837. if (normalized) {
  29838. value = value / 65535;
  29839. }
  29840. return value;
  29841. }
  29842. case VertexBuffer.FLOAT: {
  29843. return dataView.getFloat32(byteOffset, true);
  29844. }
  29845. default: {
  29846. throw new Error("Invalid component type " + type);
  29847. }
  29848. }
  29849. };
  29850. /**
  29851. * The byte type.
  29852. */
  29853. VertexBuffer.BYTE = 5120;
  29854. /**
  29855. * The unsigned byte type.
  29856. */
  29857. VertexBuffer.UNSIGNED_BYTE = 5121;
  29858. /**
  29859. * The short type.
  29860. */
  29861. VertexBuffer.SHORT = 5122;
  29862. /**
  29863. * The unsigned short type.
  29864. */
  29865. VertexBuffer.UNSIGNED_SHORT = 5123;
  29866. /**
  29867. * The integer type.
  29868. */
  29869. VertexBuffer.INT = 5124;
  29870. /**
  29871. * The unsigned integer type.
  29872. */
  29873. VertexBuffer.UNSIGNED_INT = 5125;
  29874. /**
  29875. * The float type.
  29876. */
  29877. VertexBuffer.FLOAT = 5126;
  29878. // Enums
  29879. VertexBuffer._PositionKind = "position";
  29880. VertexBuffer._NormalKind = "normal";
  29881. VertexBuffer._TangentKind = "tangent";
  29882. VertexBuffer._UVKind = "uv";
  29883. VertexBuffer._UV2Kind = "uv2";
  29884. VertexBuffer._UV3Kind = "uv3";
  29885. VertexBuffer._UV4Kind = "uv4";
  29886. VertexBuffer._UV5Kind = "uv5";
  29887. VertexBuffer._UV6Kind = "uv6";
  29888. VertexBuffer._ColorKind = "color";
  29889. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29890. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29891. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29892. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29893. return VertexBuffer;
  29894. }());
  29895. BABYLON.VertexBuffer = VertexBuffer;
  29896. })(BABYLON || (BABYLON = {}));
  29897. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29898. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  29899. var BABYLON;
  29900. (function (BABYLON) {
  29901. /**
  29902. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29903. */
  29904. var DummyInternalTextureTracker = /** @class */ (function () {
  29905. function DummyInternalTextureTracker() {
  29906. /**
  29907. * Gets or set the previous tracker in the list
  29908. */
  29909. this.previous = null;
  29910. /**
  29911. * Gets or set the next tracker in the list
  29912. */
  29913. this.next = null;
  29914. }
  29915. return DummyInternalTextureTracker;
  29916. }());
  29917. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29918. })(BABYLON || (BABYLON = {}));
  29919. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29920. var BABYLON;
  29921. (function (BABYLON) {
  29922. /**
  29923. * Class used to store data associated with WebGL texture data for the engine
  29924. * This class should not be used directly
  29925. */
  29926. var InternalTexture = /** @class */ (function () {
  29927. /**
  29928. * Creates a new InternalTexture
  29929. * @param engine defines the engine to use
  29930. * @param dataSource defines the type of data that will be used
  29931. */
  29932. function InternalTexture(engine, dataSource) {
  29933. /**
  29934. * Observable called when the texture is loaded
  29935. */
  29936. this.onLoadedObservable = new BABYLON.Observable();
  29937. /**
  29938. * Gets or set the previous tracker in the list
  29939. */
  29940. this.previous = null;
  29941. /**
  29942. * Gets or set the next tracker in the list
  29943. */
  29944. this.next = null;
  29945. // Private
  29946. /** @hidden */
  29947. this._initialSlot = -1;
  29948. /** @hidden */
  29949. this._designatedSlot = -1;
  29950. /** @hidden */
  29951. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29952. /** @hidden */
  29953. this._comparisonFunction = 0;
  29954. /** @hidden */
  29955. this._sphericalPolynomial = null;
  29956. /** @hidden */
  29957. this._lodGenerationScale = 0;
  29958. /** @hidden */
  29959. this._lodGenerationOffset = 0;
  29960. /** @hidden */
  29961. this._isRGBD = false;
  29962. /** @hidden */
  29963. this._references = 1;
  29964. this._engine = engine;
  29965. this._dataSource = dataSource;
  29966. this._webGLTexture = engine._createTexture();
  29967. }
  29968. /**
  29969. * Gets the Engine the texture belongs to.
  29970. * @returns The babylon engine
  29971. */
  29972. InternalTexture.prototype.getEngine = function () {
  29973. return this._engine;
  29974. };
  29975. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29976. /**
  29977. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29978. */
  29979. get: function () {
  29980. return this._dataSource;
  29981. },
  29982. enumerable: true,
  29983. configurable: true
  29984. });
  29985. /**
  29986. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29987. */
  29988. InternalTexture.prototype.incrementReferences = function () {
  29989. this._references++;
  29990. };
  29991. /**
  29992. * Change the size of the texture (not the size of the content)
  29993. * @param width defines the new width
  29994. * @param height defines the new height
  29995. * @param depth defines the new depth (1 by default)
  29996. */
  29997. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29998. if (depth === void 0) { depth = 1; }
  29999. this.width = width;
  30000. this.height = height;
  30001. this.depth = depth;
  30002. this.baseWidth = width;
  30003. this.baseHeight = height;
  30004. this.baseDepth = depth;
  30005. this._size = width * height * depth;
  30006. };
  30007. /** @hidden */
  30008. InternalTexture.prototype._rebuild = function () {
  30009. var _this = this;
  30010. var proxy;
  30011. this.isReady = false;
  30012. this._cachedCoordinatesMode = null;
  30013. this._cachedWrapU = null;
  30014. this._cachedWrapV = null;
  30015. this._cachedAnisotropicFilteringLevel = null;
  30016. switch (this._dataSource) {
  30017. case InternalTexture.DATASOURCE_TEMP:
  30018. return;
  30019. case InternalTexture.DATASOURCE_URL:
  30020. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30021. _this.isReady = true;
  30022. }, null, this._buffer, undefined, this.format);
  30023. proxy._swapAndDie(this);
  30024. return;
  30025. case InternalTexture.DATASOURCE_RAW:
  30026. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30027. proxy._swapAndDie(this);
  30028. this.isReady = true;
  30029. return;
  30030. case InternalTexture.DATASOURCE_RAW3D:
  30031. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30032. proxy._swapAndDie(this);
  30033. this.isReady = true;
  30034. return;
  30035. case InternalTexture.DATASOURCE_DYNAMIC:
  30036. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30037. proxy._swapAndDie(this);
  30038. // The engine will make sure to update content so no need to flag it as isReady = true
  30039. return;
  30040. case InternalTexture.DATASOURCE_RENDERTARGET:
  30041. var options = new BABYLON.RenderTargetCreationOptions();
  30042. options.generateDepthBuffer = this._generateDepthBuffer;
  30043. options.generateMipMaps = this.generateMipMaps;
  30044. options.generateStencilBuffer = this._generateStencilBuffer;
  30045. options.samplingMode = this.samplingMode;
  30046. options.type = this.type;
  30047. if (this.isCube) {
  30048. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30049. }
  30050. else {
  30051. var size = {
  30052. width: this.width,
  30053. height: this.height
  30054. };
  30055. proxy = this._engine.createRenderTargetTexture(size, options);
  30056. }
  30057. proxy._swapAndDie(this);
  30058. this.isReady = true;
  30059. return;
  30060. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30061. var depthTextureOptions = {
  30062. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30063. comparisonFunction: this._comparisonFunction,
  30064. generateStencil: this._generateStencilBuffer,
  30065. isCube: this.isCube
  30066. };
  30067. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30068. proxy._swapAndDie(this);
  30069. this.isReady = true;
  30070. return;
  30071. case InternalTexture.DATASOURCE_CUBE:
  30072. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30073. _this.isReady = true;
  30074. }, null, this.format, this._extension);
  30075. proxy._swapAndDie(this);
  30076. return;
  30077. case InternalTexture.DATASOURCE_CUBERAW:
  30078. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30079. proxy._swapAndDie(this);
  30080. this.isReady = true;
  30081. return;
  30082. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  30083. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30084. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  30085. _this.isReady = true;
  30086. });
  30087. proxy._swapAndDie(this);
  30088. return;
  30089. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30090. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30091. if (proxy) {
  30092. proxy._swapAndDie(_this);
  30093. }
  30094. _this.isReady = true;
  30095. }, null, this.format, this._extension);
  30096. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30097. return;
  30098. }
  30099. };
  30100. /** @hidden */
  30101. InternalTexture.prototype._swapAndDie = function (target) {
  30102. target._webGLTexture = this._webGLTexture;
  30103. if (this._framebuffer) {
  30104. target._framebuffer = this._framebuffer;
  30105. }
  30106. if (this._depthStencilBuffer) {
  30107. target._depthStencilBuffer = this._depthStencilBuffer;
  30108. }
  30109. if (this._lodTextureHigh) {
  30110. if (target._lodTextureHigh) {
  30111. target._lodTextureHigh.dispose();
  30112. }
  30113. target._lodTextureHigh = this._lodTextureHigh;
  30114. }
  30115. if (this._lodTextureMid) {
  30116. if (target._lodTextureMid) {
  30117. target._lodTextureMid.dispose();
  30118. }
  30119. target._lodTextureMid = this._lodTextureMid;
  30120. }
  30121. if (this._lodTextureLow) {
  30122. if (target._lodTextureLow) {
  30123. target._lodTextureLow.dispose();
  30124. }
  30125. target._lodTextureLow = this._lodTextureLow;
  30126. }
  30127. var cache = this._engine.getLoadedTexturesCache();
  30128. var index = cache.indexOf(this);
  30129. if (index !== -1) {
  30130. cache.splice(index, 1);
  30131. }
  30132. };
  30133. /**
  30134. * Dispose the current allocated resources
  30135. */
  30136. InternalTexture.prototype.dispose = function () {
  30137. if (!this._webGLTexture) {
  30138. return;
  30139. }
  30140. this._references--;
  30141. if (this._references === 0) {
  30142. this._engine._releaseTexture(this);
  30143. this._webGLTexture = null;
  30144. this.previous = null;
  30145. this.next = null;
  30146. }
  30147. };
  30148. /**
  30149. * The source of the texture data is unknown
  30150. */
  30151. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30152. /**
  30153. * Texture data comes from an URL
  30154. */
  30155. InternalTexture.DATASOURCE_URL = 1;
  30156. /**
  30157. * Texture data is only used for temporary storage
  30158. */
  30159. InternalTexture.DATASOURCE_TEMP = 2;
  30160. /**
  30161. * Texture data comes from raw data (ArrayBuffer)
  30162. */
  30163. InternalTexture.DATASOURCE_RAW = 3;
  30164. /**
  30165. * Texture content is dynamic (video or dynamic texture)
  30166. */
  30167. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30168. /**
  30169. * Texture content is generated by rendering to it
  30170. */
  30171. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30172. /**
  30173. * Texture content is part of a multi render target process
  30174. */
  30175. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30176. /**
  30177. * Texture data comes from a cube data file
  30178. */
  30179. InternalTexture.DATASOURCE_CUBE = 7;
  30180. /**
  30181. * Texture data comes from a raw cube data
  30182. */
  30183. InternalTexture.DATASOURCE_CUBERAW = 8;
  30184. /**
  30185. * Texture data come from a prefiltered cube data file
  30186. */
  30187. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30188. /**
  30189. * Texture content is raw 3D data
  30190. */
  30191. InternalTexture.DATASOURCE_RAW3D = 10;
  30192. /**
  30193. * Texture content is a depth texture
  30194. */
  30195. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30196. /**
  30197. * Texture data comes from a raw cube data encoded with RGBD
  30198. */
  30199. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  30200. return InternalTexture;
  30201. }());
  30202. BABYLON.InternalTexture = InternalTexture;
  30203. })(BABYLON || (BABYLON = {}));
  30204. //# sourceMappingURL=babylon.internalTexture.js.map
  30205. var BABYLON;
  30206. (function (BABYLON) {
  30207. var BaseTexture = /** @class */ (function () {
  30208. function BaseTexture(scene) {
  30209. this._hasAlpha = false;
  30210. this.getAlphaFromRGB = false;
  30211. this.level = 1;
  30212. this.coordinatesIndex = 0;
  30213. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30214. /**
  30215. * | Value | Type | Description |
  30216. * | ----- | ------------------ | ----------- |
  30217. * | 0 | CLAMP_ADDRESSMODE | |
  30218. * | 1 | WRAP_ADDRESSMODE | |
  30219. * | 2 | MIRROR_ADDRESSMODE | |
  30220. */
  30221. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30222. /**
  30223. * | Value | Type | Description |
  30224. * | ----- | ------------------ | ----------- |
  30225. * | 0 | CLAMP_ADDRESSMODE | |
  30226. * | 1 | WRAP_ADDRESSMODE | |
  30227. * | 2 | MIRROR_ADDRESSMODE | |
  30228. */
  30229. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30230. /**
  30231. * | Value | Type | Description |
  30232. * | ----- | ------------------ | ----------- |
  30233. * | 0 | CLAMP_ADDRESSMODE | |
  30234. * | 1 | WRAP_ADDRESSMODE | |
  30235. * | 2 | MIRROR_ADDRESSMODE | |
  30236. */
  30237. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30238. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30239. this.isCube = false;
  30240. this.is3D = false;
  30241. this.gammaSpace = true;
  30242. this.invertZ = false;
  30243. this.lodLevelInAlpha = false;
  30244. this.isRenderTarget = false;
  30245. this.animations = new Array();
  30246. /**
  30247. * An event triggered when the texture is disposed.
  30248. */
  30249. this.onDisposeObservable = new BABYLON.Observable();
  30250. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30251. this._cachedSize = BABYLON.Size.Zero();
  30252. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30253. if (this._scene) {
  30254. this._scene.textures.push(this);
  30255. }
  30256. this._uid = null;
  30257. }
  30258. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30259. get: function () {
  30260. return this._hasAlpha;
  30261. },
  30262. set: function (value) {
  30263. if (this._hasAlpha === value) {
  30264. return;
  30265. }
  30266. this._hasAlpha = value;
  30267. if (this._scene) {
  30268. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30269. }
  30270. },
  30271. enumerable: true,
  30272. configurable: true
  30273. });
  30274. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30275. get: function () {
  30276. return this._coordinatesMode;
  30277. },
  30278. /**
  30279. * How a texture is mapped.
  30280. *
  30281. * | Value | Type | Description |
  30282. * | ----- | ----------------------------------- | ----------- |
  30283. * | 0 | EXPLICIT_MODE | |
  30284. * | 1 | SPHERICAL_MODE | |
  30285. * | 2 | PLANAR_MODE | |
  30286. * | 3 | CUBIC_MODE | |
  30287. * | 4 | PROJECTION_MODE | |
  30288. * | 5 | SKYBOX_MODE | |
  30289. * | 6 | INVCUBIC_MODE | |
  30290. * | 7 | EQUIRECTANGULAR_MODE | |
  30291. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30292. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30293. */
  30294. set: function (value) {
  30295. if (this._coordinatesMode === value) {
  30296. return;
  30297. }
  30298. this._coordinatesMode = value;
  30299. if (this._scene) {
  30300. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30301. }
  30302. },
  30303. enumerable: true,
  30304. configurable: true
  30305. });
  30306. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30307. /**
  30308. * Gets whether or not the texture contains RGBD data.
  30309. */
  30310. get: function () {
  30311. return this._texture != null && this._texture._isRGBD;
  30312. },
  30313. enumerable: true,
  30314. configurable: true
  30315. });
  30316. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30317. get: function () {
  30318. if (this._texture)
  30319. return this._texture._lodGenerationOffset;
  30320. return 0.0;
  30321. },
  30322. set: function (value) {
  30323. if (this._texture)
  30324. this._texture._lodGenerationOffset = value;
  30325. },
  30326. enumerable: true,
  30327. configurable: true
  30328. });
  30329. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30330. get: function () {
  30331. if (this._texture)
  30332. return this._texture._lodGenerationScale;
  30333. return 0.0;
  30334. },
  30335. set: function (value) {
  30336. if (this._texture)
  30337. this._texture._lodGenerationScale = value;
  30338. },
  30339. enumerable: true,
  30340. configurable: true
  30341. });
  30342. Object.defineProperty(BaseTexture.prototype, "uid", {
  30343. get: function () {
  30344. if (!this._uid) {
  30345. this._uid = BABYLON.Tools.RandomId();
  30346. }
  30347. return this._uid;
  30348. },
  30349. enumerable: true,
  30350. configurable: true
  30351. });
  30352. BaseTexture.prototype.toString = function () {
  30353. return this.name;
  30354. };
  30355. BaseTexture.prototype.getClassName = function () {
  30356. return "BaseTexture";
  30357. };
  30358. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30359. set: function (callback) {
  30360. if (this._onDisposeObserver) {
  30361. this.onDisposeObservable.remove(this._onDisposeObserver);
  30362. }
  30363. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30364. },
  30365. enumerable: true,
  30366. configurable: true
  30367. });
  30368. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30369. get: function () {
  30370. return true;
  30371. },
  30372. enumerable: true,
  30373. configurable: true
  30374. });
  30375. BaseTexture.prototype.getScene = function () {
  30376. return this._scene;
  30377. };
  30378. BaseTexture.prototype.getTextureMatrix = function () {
  30379. return BABYLON.Matrix.IdentityReadOnly;
  30380. };
  30381. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30382. return BABYLON.Matrix.IdentityReadOnly;
  30383. };
  30384. BaseTexture.prototype.getInternalTexture = function () {
  30385. return this._texture;
  30386. };
  30387. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30388. return !this.isBlocking || this.isReady();
  30389. };
  30390. BaseTexture.prototype.isReady = function () {
  30391. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30392. this.delayLoad();
  30393. return false;
  30394. }
  30395. if (this._texture) {
  30396. return this._texture.isReady;
  30397. }
  30398. return false;
  30399. };
  30400. BaseTexture.prototype.getSize = function () {
  30401. if (this._texture) {
  30402. if (this._texture.width) {
  30403. this._cachedSize.width = this._texture.width;
  30404. this._cachedSize.height = this._texture.height;
  30405. return this._cachedSize;
  30406. }
  30407. if (this._texture._size) {
  30408. this._cachedSize.width = this._texture._size;
  30409. this._cachedSize.height = this._texture._size;
  30410. return this._cachedSize;
  30411. }
  30412. }
  30413. return this._cachedSize;
  30414. };
  30415. BaseTexture.prototype.getBaseSize = function () {
  30416. if (!this.isReady() || !this._texture)
  30417. return BABYLON.Size.Zero();
  30418. if (this._texture._size) {
  30419. return new BABYLON.Size(this._texture._size, this._texture._size);
  30420. }
  30421. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30422. };
  30423. BaseTexture.prototype.scale = function (ratio) {
  30424. };
  30425. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30426. get: function () {
  30427. return false;
  30428. },
  30429. enumerable: true,
  30430. configurable: true
  30431. });
  30432. /** @hidden */
  30433. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30434. if (!this._scene) {
  30435. return null;
  30436. }
  30437. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30438. for (var index = 0; index < texturesCache.length; index++) {
  30439. var texturesCacheEntry = texturesCache[index];
  30440. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30441. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30442. texturesCacheEntry.incrementReferences();
  30443. return texturesCacheEntry;
  30444. }
  30445. }
  30446. }
  30447. return null;
  30448. };
  30449. /** @hidden */
  30450. BaseTexture.prototype._rebuild = function () {
  30451. };
  30452. BaseTexture.prototype.delayLoad = function () {
  30453. };
  30454. BaseTexture.prototype.clone = function () {
  30455. return null;
  30456. };
  30457. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30458. get: function () {
  30459. if (!this._texture) {
  30460. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30461. }
  30462. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30463. },
  30464. enumerable: true,
  30465. configurable: true
  30466. });
  30467. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30468. get: function () {
  30469. if (!this._texture) {
  30470. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30471. }
  30472. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30473. },
  30474. enumerable: true,
  30475. configurable: true
  30476. });
  30477. /**
  30478. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30479. * This will returns an RGBA array buffer containing either in values (0-255) or
  30480. * float values (0-1) depending of the underlying buffer type.
  30481. * @param faceIndex The face of the texture to read (in case of cube texture)
  30482. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30483. * @returns The Array buffer containing the pixels data.
  30484. */
  30485. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30486. if (faceIndex === void 0) { faceIndex = 0; }
  30487. if (level === void 0) { level = 0; }
  30488. if (!this._texture) {
  30489. return null;
  30490. }
  30491. var size = this.getSize();
  30492. var width = size.width;
  30493. var height = size.height;
  30494. var scene = this.getScene();
  30495. if (!scene) {
  30496. return null;
  30497. }
  30498. var engine = scene.getEngine();
  30499. if (level != 0) {
  30500. width = width / Math.pow(2, level);
  30501. height = height / Math.pow(2, level);
  30502. width = Math.round(width);
  30503. height = Math.round(height);
  30504. }
  30505. if (this._texture.isCube) {
  30506. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30507. }
  30508. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30509. };
  30510. BaseTexture.prototype.releaseInternalTexture = function () {
  30511. if (this._texture) {
  30512. this._texture.dispose();
  30513. this._texture = null;
  30514. }
  30515. };
  30516. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30517. get: function () {
  30518. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30519. return null;
  30520. }
  30521. if (!this._texture._sphericalPolynomial) {
  30522. this._texture._sphericalPolynomial =
  30523. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30524. }
  30525. return this._texture._sphericalPolynomial;
  30526. },
  30527. set: function (value) {
  30528. if (this._texture) {
  30529. this._texture._sphericalPolynomial = value;
  30530. }
  30531. },
  30532. enumerable: true,
  30533. configurable: true
  30534. });
  30535. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30536. get: function () {
  30537. if (this._texture) {
  30538. return this._texture._lodTextureHigh;
  30539. }
  30540. return null;
  30541. },
  30542. enumerable: true,
  30543. configurable: true
  30544. });
  30545. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30546. get: function () {
  30547. if (this._texture) {
  30548. return this._texture._lodTextureMid;
  30549. }
  30550. return null;
  30551. },
  30552. enumerable: true,
  30553. configurable: true
  30554. });
  30555. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30556. get: function () {
  30557. if (this._texture) {
  30558. return this._texture._lodTextureLow;
  30559. }
  30560. return null;
  30561. },
  30562. enumerable: true,
  30563. configurable: true
  30564. });
  30565. BaseTexture.prototype.dispose = function () {
  30566. if (!this._scene) {
  30567. return;
  30568. }
  30569. // Animations
  30570. this._scene.stopAnimation(this);
  30571. // Remove from scene
  30572. this._scene._removePendingData(this);
  30573. var index = this._scene.textures.indexOf(this);
  30574. if (index >= 0) {
  30575. this._scene.textures.splice(index, 1);
  30576. }
  30577. if (this._texture === undefined) {
  30578. return;
  30579. }
  30580. // Release
  30581. this.releaseInternalTexture();
  30582. // Callback
  30583. this.onDisposeObservable.notifyObservers(this);
  30584. this.onDisposeObservable.clear();
  30585. };
  30586. BaseTexture.prototype.serialize = function () {
  30587. if (!this.name) {
  30588. return null;
  30589. }
  30590. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30591. // Animations
  30592. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30593. return serializationObject;
  30594. };
  30595. BaseTexture.WhenAllReady = function (textures, callback) {
  30596. var numRemaining = textures.length;
  30597. if (numRemaining === 0) {
  30598. callback();
  30599. return;
  30600. }
  30601. var _loop_1 = function () {
  30602. texture = textures[i];
  30603. if (texture.isReady()) {
  30604. if (--numRemaining === 0) {
  30605. callback();
  30606. }
  30607. }
  30608. else {
  30609. onLoadObservable = texture.onLoadObservable;
  30610. var onLoadCallback_1 = function () {
  30611. onLoadObservable.removeCallback(onLoadCallback_1);
  30612. if (--numRemaining === 0) {
  30613. callback();
  30614. }
  30615. };
  30616. onLoadObservable.add(onLoadCallback_1);
  30617. }
  30618. };
  30619. var texture, onLoadObservable;
  30620. for (var i = 0; i < textures.length; i++) {
  30621. _loop_1();
  30622. }
  30623. };
  30624. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30625. __decorate([
  30626. BABYLON.serialize()
  30627. ], BaseTexture.prototype, "name", void 0);
  30628. __decorate([
  30629. BABYLON.serialize("hasAlpha")
  30630. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30631. __decorate([
  30632. BABYLON.serialize()
  30633. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30634. __decorate([
  30635. BABYLON.serialize()
  30636. ], BaseTexture.prototype, "level", void 0);
  30637. __decorate([
  30638. BABYLON.serialize()
  30639. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30640. __decorate([
  30641. BABYLON.serialize("coordinatesMode")
  30642. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30643. __decorate([
  30644. BABYLON.serialize()
  30645. ], BaseTexture.prototype, "wrapU", void 0);
  30646. __decorate([
  30647. BABYLON.serialize()
  30648. ], BaseTexture.prototype, "wrapV", void 0);
  30649. __decorate([
  30650. BABYLON.serialize()
  30651. ], BaseTexture.prototype, "wrapR", void 0);
  30652. __decorate([
  30653. BABYLON.serialize()
  30654. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30655. __decorate([
  30656. BABYLON.serialize()
  30657. ], BaseTexture.prototype, "isCube", void 0);
  30658. __decorate([
  30659. BABYLON.serialize()
  30660. ], BaseTexture.prototype, "is3D", void 0);
  30661. __decorate([
  30662. BABYLON.serialize()
  30663. ], BaseTexture.prototype, "gammaSpace", void 0);
  30664. __decorate([
  30665. BABYLON.serialize()
  30666. ], BaseTexture.prototype, "invertZ", void 0);
  30667. __decorate([
  30668. BABYLON.serialize()
  30669. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30670. __decorate([
  30671. BABYLON.serialize()
  30672. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30673. __decorate([
  30674. BABYLON.serialize()
  30675. ], BaseTexture.prototype, "lodGenerationScale", null);
  30676. __decorate([
  30677. BABYLON.serialize()
  30678. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30679. return BaseTexture;
  30680. }());
  30681. BABYLON.BaseTexture = BaseTexture;
  30682. })(BABYLON || (BABYLON = {}));
  30683. //# sourceMappingURL=babylon.baseTexture.js.map
  30684. var BABYLON;
  30685. (function (BABYLON) {
  30686. var Texture = /** @class */ (function (_super) {
  30687. __extends(Texture, _super);
  30688. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30689. if (noMipmap === void 0) { noMipmap = false; }
  30690. if (invertY === void 0) { invertY = true; }
  30691. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30692. if (onLoad === void 0) { onLoad = null; }
  30693. if (onError === void 0) { onError = null; }
  30694. if (buffer === void 0) { buffer = null; }
  30695. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30696. var _this = _super.call(this, scene) || this;
  30697. _this.uOffset = 0;
  30698. _this.vOffset = 0;
  30699. _this.uScale = 1.0;
  30700. _this.vScale = 1.0;
  30701. _this.uAng = 0;
  30702. _this.vAng = 0;
  30703. _this.wAng = 0;
  30704. /**
  30705. * Defines the center of rotation (U)
  30706. */
  30707. _this.uRotationCenter = 0.5;
  30708. /**
  30709. * Defines the center of rotation (V)
  30710. */
  30711. _this.vRotationCenter = 0.5;
  30712. /**
  30713. * Defines the center of rotation (W)
  30714. */
  30715. _this.wRotationCenter = 0.5;
  30716. _this._isBlocking = true;
  30717. _this.name = url || "";
  30718. _this.url = url;
  30719. _this._noMipmap = noMipmap;
  30720. _this._invertY = invertY;
  30721. _this._samplingMode = samplingMode;
  30722. _this._buffer = buffer;
  30723. _this._deleteBuffer = deleteBuffer;
  30724. if (format) {
  30725. _this._format = format;
  30726. }
  30727. scene = _this.getScene();
  30728. if (!scene) {
  30729. return _this;
  30730. }
  30731. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30732. var load = function () {
  30733. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30734. _this.onLoadObservable.notifyObservers(_this);
  30735. }
  30736. if (onLoad) {
  30737. onLoad();
  30738. }
  30739. if (!_this.isBlocking && scene) {
  30740. scene.resetCachedMaterial();
  30741. }
  30742. };
  30743. if (!_this.url) {
  30744. _this._delayedOnLoad = load;
  30745. _this._delayedOnError = onError;
  30746. return _this;
  30747. }
  30748. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30749. if (!_this._texture) {
  30750. if (!scene.useDelayedTextureLoading) {
  30751. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30752. if (deleteBuffer) {
  30753. delete _this._buffer;
  30754. }
  30755. }
  30756. else {
  30757. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30758. _this._delayedOnLoad = load;
  30759. _this._delayedOnError = onError;
  30760. }
  30761. }
  30762. else {
  30763. if (_this._texture.isReady) {
  30764. BABYLON.Tools.SetImmediate(function () { return load(); });
  30765. }
  30766. else {
  30767. _this._texture.onLoadedObservable.add(load);
  30768. }
  30769. }
  30770. return _this;
  30771. }
  30772. Object.defineProperty(Texture.prototype, "noMipmap", {
  30773. get: function () {
  30774. return this._noMipmap;
  30775. },
  30776. enumerable: true,
  30777. configurable: true
  30778. });
  30779. Object.defineProperty(Texture.prototype, "isBlocking", {
  30780. get: function () {
  30781. return this._isBlocking;
  30782. },
  30783. set: function (value) {
  30784. this._isBlocking = value;
  30785. },
  30786. enumerable: true,
  30787. configurable: true
  30788. });
  30789. Object.defineProperty(Texture.prototype, "samplingMode", {
  30790. get: function () {
  30791. return this._samplingMode;
  30792. },
  30793. enumerable: true,
  30794. configurable: true
  30795. });
  30796. /**
  30797. * Update the url (and optional buffer) of this texture if url was null during construction.
  30798. * @param url the url of the texture
  30799. * @param buffer the buffer of the texture (defaults to null)
  30800. */
  30801. Texture.prototype.updateURL = function (url, buffer) {
  30802. if (buffer === void 0) { buffer = null; }
  30803. if (this.url) {
  30804. throw new Error("URL is already set");
  30805. }
  30806. this.url = url;
  30807. this._buffer = buffer;
  30808. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30809. this.delayLoad();
  30810. };
  30811. Texture.prototype.delayLoad = function () {
  30812. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30813. return;
  30814. }
  30815. var scene = this.getScene();
  30816. if (!scene) {
  30817. return;
  30818. }
  30819. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30820. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30821. if (!this._texture) {
  30822. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30823. if (this._deleteBuffer) {
  30824. delete this._buffer;
  30825. }
  30826. }
  30827. else {
  30828. if (this._delayedOnLoad) {
  30829. if (this._texture.isReady) {
  30830. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30831. }
  30832. else {
  30833. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30834. }
  30835. }
  30836. }
  30837. this._delayedOnLoad = null;
  30838. this._delayedOnError = null;
  30839. };
  30840. /**
  30841. * Default is Trilinear mode.
  30842. *
  30843. * | Value | Type | Description |
  30844. * | ----- | ------------------ | ----------- |
  30845. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  30846. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  30847. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  30848. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  30849. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  30850. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  30851. * | 7 | NEAREST_LINEAR | |
  30852. * | 8 | NEAREST_NEAREST | |
  30853. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  30854. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  30855. * | 11 | LINEAR_LINEAR | |
  30856. * | 12 | LINEAR_NEAREST | |
  30857. *
  30858. * > _mag_: magnification filter (close to the viewer)
  30859. * > _min_: minification filter (far from the viewer)
  30860. * > _mip_: filter used between mip map levels
  30861. *
  30862. */
  30863. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30864. if (!this._texture) {
  30865. return;
  30866. }
  30867. var scene = this.getScene();
  30868. if (!scene) {
  30869. return;
  30870. }
  30871. this._samplingMode = samplingMode;
  30872. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30873. };
  30874. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30875. x *= this.uScale;
  30876. y *= this.vScale;
  30877. x -= this.uRotationCenter * this.uScale;
  30878. y -= this.vRotationCenter * this.vScale;
  30879. z -= this.wRotationCenter;
  30880. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30881. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30882. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30883. t.z += this.wRotationCenter;
  30884. };
  30885. Texture.prototype.getTextureMatrix = function () {
  30886. var _this = this;
  30887. if (this.uOffset === this._cachedUOffset &&
  30888. this.vOffset === this._cachedVOffset &&
  30889. this.uScale === this._cachedUScale &&
  30890. this.vScale === this._cachedVScale &&
  30891. this.uAng === this._cachedUAng &&
  30892. this.vAng === this._cachedVAng &&
  30893. this.wAng === this._cachedWAng) {
  30894. return this._cachedTextureMatrix;
  30895. }
  30896. this._cachedUOffset = this.uOffset;
  30897. this._cachedVOffset = this.vOffset;
  30898. this._cachedUScale = this.uScale;
  30899. this._cachedVScale = this.vScale;
  30900. this._cachedUAng = this.uAng;
  30901. this._cachedVAng = this.vAng;
  30902. this._cachedWAng = this.wAng;
  30903. if (!this._cachedTextureMatrix) {
  30904. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30905. this._rowGenerationMatrix = new BABYLON.Matrix();
  30906. this._t0 = BABYLON.Vector3.Zero();
  30907. this._t1 = BABYLON.Vector3.Zero();
  30908. this._t2 = BABYLON.Vector3.Zero();
  30909. }
  30910. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30911. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30912. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30913. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30914. this._t1.subtractInPlace(this._t0);
  30915. this._t2.subtractInPlace(this._t0);
  30916. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30917. this._cachedTextureMatrix.m[0] = this._t1.x;
  30918. this._cachedTextureMatrix.m[1] = this._t1.y;
  30919. this._cachedTextureMatrix.m[2] = this._t1.z;
  30920. this._cachedTextureMatrix.m[4] = this._t2.x;
  30921. this._cachedTextureMatrix.m[5] = this._t2.y;
  30922. this._cachedTextureMatrix.m[6] = this._t2.z;
  30923. this._cachedTextureMatrix.m[8] = this._t0.x;
  30924. this._cachedTextureMatrix.m[9] = this._t0.y;
  30925. this._cachedTextureMatrix.m[10] = this._t0.z;
  30926. var scene = this.getScene();
  30927. if (!scene) {
  30928. return this._cachedTextureMatrix;
  30929. }
  30930. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30931. return mat.hasTexture(_this);
  30932. });
  30933. return this._cachedTextureMatrix;
  30934. };
  30935. Texture.prototype.getReflectionTextureMatrix = function () {
  30936. var _this = this;
  30937. var scene = this.getScene();
  30938. if (!scene) {
  30939. return this._cachedTextureMatrix;
  30940. }
  30941. if (this.uOffset === this._cachedUOffset &&
  30942. this.vOffset === this._cachedVOffset &&
  30943. this.uScale === this._cachedUScale &&
  30944. this.vScale === this._cachedVScale &&
  30945. this.coordinatesMode === this._cachedCoordinatesMode) {
  30946. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30947. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30948. return this._cachedTextureMatrix;
  30949. }
  30950. }
  30951. else {
  30952. return this._cachedTextureMatrix;
  30953. }
  30954. }
  30955. if (!this._cachedTextureMatrix) {
  30956. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30957. }
  30958. if (!this._projectionModeMatrix) {
  30959. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30960. }
  30961. this._cachedUOffset = this.uOffset;
  30962. this._cachedVOffset = this.vOffset;
  30963. this._cachedUScale = this.uScale;
  30964. this._cachedVScale = this.vScale;
  30965. this._cachedCoordinatesMode = this.coordinatesMode;
  30966. switch (this.coordinatesMode) {
  30967. case Texture.PLANAR_MODE:
  30968. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30969. this._cachedTextureMatrix[0] = this.uScale;
  30970. this._cachedTextureMatrix[5] = this.vScale;
  30971. this._cachedTextureMatrix[12] = this.uOffset;
  30972. this._cachedTextureMatrix[13] = this.vOffset;
  30973. break;
  30974. case Texture.PROJECTION_MODE:
  30975. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30976. this._projectionModeMatrix.m[0] = 0.5;
  30977. this._projectionModeMatrix.m[5] = -0.5;
  30978. this._projectionModeMatrix.m[10] = 0.0;
  30979. this._projectionModeMatrix.m[12] = 0.5;
  30980. this._projectionModeMatrix.m[13] = 0.5;
  30981. this._projectionModeMatrix.m[14] = 1.0;
  30982. this._projectionModeMatrix.m[15] = 1.0;
  30983. var projectionMatrix = scene.getProjectionMatrix();
  30984. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30985. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30986. break;
  30987. default:
  30988. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30989. break;
  30990. }
  30991. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30992. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30993. });
  30994. return this._cachedTextureMatrix;
  30995. };
  30996. Texture.prototype.clone = function () {
  30997. var _this = this;
  30998. return BABYLON.SerializationHelper.Clone(function () {
  30999. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31000. }, this);
  31001. };
  31002. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  31003. get: function () {
  31004. if (!this._onLoadObservable) {
  31005. this._onLoadObservable = new BABYLON.Observable();
  31006. }
  31007. return this._onLoadObservable;
  31008. },
  31009. enumerable: true,
  31010. configurable: true
  31011. });
  31012. Texture.prototype.serialize = function () {
  31013. var serializationObject = _super.prototype.serialize.call(this);
  31014. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  31015. serializationObject.base64String = this._buffer;
  31016. serializationObject.name = serializationObject.name.replace("data:", "");
  31017. }
  31018. serializationObject.invertY = this._invertY;
  31019. serializationObject.samplingMode = this.samplingMode;
  31020. return serializationObject;
  31021. };
  31022. Texture.prototype.getClassName = function () {
  31023. return "Texture";
  31024. };
  31025. Texture.prototype.dispose = function () {
  31026. _super.prototype.dispose.call(this);
  31027. if (this._onLoadObservable) {
  31028. this._onLoadObservable.clear();
  31029. this._onLoadObservable = null;
  31030. }
  31031. this._delayedOnLoad = null;
  31032. this._delayedOnError = null;
  31033. };
  31034. // Statics
  31035. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31036. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31037. if (onLoad === void 0) { onLoad = null; }
  31038. if (onError === void 0) { onError = null; }
  31039. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31040. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  31041. };
  31042. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31043. if (parsedTexture.customType) {
  31044. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31045. // Update Sampling Mode
  31046. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31047. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31048. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31049. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31050. }
  31051. }
  31052. return parsedCustomTexture;
  31053. }
  31054. if (parsedTexture.isCube) {
  31055. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31056. }
  31057. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31058. return null;
  31059. }
  31060. var texture = BABYLON.SerializationHelper.Parse(function () {
  31061. var generateMipMaps = true;
  31062. if (parsedTexture.noMipmap) {
  31063. generateMipMaps = false;
  31064. }
  31065. if (parsedTexture.mirrorPlane) {
  31066. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31067. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31068. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31069. return mirrorTexture;
  31070. }
  31071. else if (parsedTexture.isRenderTarget) {
  31072. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31073. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31074. return renderTargetTexture;
  31075. }
  31076. else {
  31077. var texture;
  31078. if (parsedTexture.base64String) {
  31079. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31080. }
  31081. else {
  31082. var url = rootUrl + parsedTexture.name;
  31083. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31084. url = parsedTexture.url;
  31085. }
  31086. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31087. }
  31088. return texture;
  31089. }
  31090. }, parsedTexture, scene);
  31091. // Update Sampling Mode
  31092. if (parsedTexture.samplingMode) {
  31093. var sampling = parsedTexture.samplingMode;
  31094. if (texture._samplingMode !== sampling) {
  31095. texture.updateSamplingMode(sampling);
  31096. }
  31097. }
  31098. // Animations
  31099. if (parsedTexture.animations) {
  31100. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31101. var parsedAnimation = parsedTexture.animations[animationIndex];
  31102. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31103. }
  31104. }
  31105. return texture;
  31106. };
  31107. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31108. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31109. if (noMipmap === void 0) { noMipmap = false; }
  31110. if (invertY === void 0) { invertY = true; }
  31111. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31112. if (onLoad === void 0) { onLoad = null; }
  31113. if (onError === void 0) { onError = null; }
  31114. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31115. if (name.substr(0, 5) !== "data:") {
  31116. name = "data:" + name;
  31117. }
  31118. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31119. };
  31120. // Constants
  31121. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  31122. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  31123. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  31124. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  31125. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  31126. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  31127. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  31128. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  31129. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  31130. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  31131. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  31132. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  31133. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  31134. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  31135. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  31136. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  31137. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  31138. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  31139. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  31140. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  31141. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  31142. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  31143. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  31144. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  31145. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  31146. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  31147. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  31148. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  31149. /**
  31150. * 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
  31151. */
  31152. Texture.UseSerializedUrlIfAny = false;
  31153. __decorate([
  31154. BABYLON.serialize()
  31155. ], Texture.prototype, "url", void 0);
  31156. __decorate([
  31157. BABYLON.serialize()
  31158. ], Texture.prototype, "uOffset", void 0);
  31159. __decorate([
  31160. BABYLON.serialize()
  31161. ], Texture.prototype, "vOffset", void 0);
  31162. __decorate([
  31163. BABYLON.serialize()
  31164. ], Texture.prototype, "uScale", void 0);
  31165. __decorate([
  31166. BABYLON.serialize()
  31167. ], Texture.prototype, "vScale", void 0);
  31168. __decorate([
  31169. BABYLON.serialize()
  31170. ], Texture.prototype, "uAng", void 0);
  31171. __decorate([
  31172. BABYLON.serialize()
  31173. ], Texture.prototype, "vAng", void 0);
  31174. __decorate([
  31175. BABYLON.serialize()
  31176. ], Texture.prototype, "wAng", void 0);
  31177. __decorate([
  31178. BABYLON.serialize()
  31179. ], Texture.prototype, "uRotationCenter", void 0);
  31180. __decorate([
  31181. BABYLON.serialize()
  31182. ], Texture.prototype, "vRotationCenter", void 0);
  31183. __decorate([
  31184. BABYLON.serialize()
  31185. ], Texture.prototype, "wRotationCenter", void 0);
  31186. __decorate([
  31187. BABYLON.serialize()
  31188. ], Texture.prototype, "isBlocking", null);
  31189. return Texture;
  31190. }(BABYLON.BaseTexture));
  31191. BABYLON.Texture = Texture;
  31192. })(BABYLON || (BABYLON = {}));
  31193. //# sourceMappingURL=babylon.texture.js.map
  31194. var BABYLON;
  31195. (function (BABYLON) {
  31196. /**
  31197. * @hidden
  31198. **/
  31199. var _InstancesBatch = /** @class */ (function () {
  31200. function _InstancesBatch() {
  31201. this.mustReturn = false;
  31202. this.visibleInstances = new Array();
  31203. this.renderSelf = new Array();
  31204. }
  31205. return _InstancesBatch;
  31206. }());
  31207. BABYLON._InstancesBatch = _InstancesBatch;
  31208. var Mesh = /** @class */ (function (_super) {
  31209. __extends(Mesh, _super);
  31210. /**
  31211. * @constructor
  31212. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31213. * @param {Scene} scene The scene to add this mesh to.
  31214. * @param {Node} parent The parent of this mesh, if it has one
  31215. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31216. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31217. * When false, achieved by calling a clone(), also passing False.
  31218. * This will make creation of children, recursive.
  31219. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31220. */
  31221. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31222. if (scene === void 0) { scene = null; }
  31223. if (parent === void 0) { parent = null; }
  31224. if (source === void 0) { source = null; }
  31225. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31226. var _this = _super.call(this, name, scene) || this;
  31227. // Members
  31228. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31229. _this.instances = new Array();
  31230. _this._LODLevels = new Array();
  31231. /** @hidden */
  31232. _this._visibleInstances = {};
  31233. _this._renderIdForInstances = new Array();
  31234. _this._batchCache = new _InstancesBatch();
  31235. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31236. // Use by builder only to know what orientation were the mesh build in.
  31237. /** @hidden */
  31238. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31239. _this.overrideMaterialSideOrientation = null;
  31240. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31241. // Will be used to save a source mesh reference, If any
  31242. _this._source = null;
  31243. scene = _this.getScene();
  31244. if (source) {
  31245. // Geometry
  31246. if (source._geometry) {
  31247. source._geometry.applyToMesh(_this);
  31248. }
  31249. // Deep copy
  31250. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31251. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  31252. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  31253. ], ["_poseMatrix"]);
  31254. // Source mesh
  31255. _this._source = source;
  31256. // Animation ranges
  31257. if (_this._source._ranges) {
  31258. var ranges = _this._source._ranges;
  31259. for (var name in ranges) {
  31260. if (!ranges.hasOwnProperty(name)) {
  31261. continue;
  31262. }
  31263. if (!ranges[name]) {
  31264. continue;
  31265. }
  31266. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  31267. }
  31268. }
  31269. // Metadata
  31270. if (source.metadata && source.metadata.clone) {
  31271. _this.metadata = source.metadata.clone();
  31272. }
  31273. else {
  31274. _this.metadata = source.metadata;
  31275. }
  31276. // Tags
  31277. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31278. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31279. }
  31280. // Parent
  31281. _this.parent = source.parent;
  31282. // Pivot
  31283. _this.setPivotMatrix(source.getPivotMatrix());
  31284. _this.id = name + "." + source.id;
  31285. // Material
  31286. _this.material = source.material;
  31287. var index;
  31288. if (!doNotCloneChildren) {
  31289. // Children
  31290. var directDescendants = source.getDescendants(true);
  31291. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31292. var child = directDescendants[index_1];
  31293. if (child.clone) {
  31294. child.clone(name + "." + child.name, _this);
  31295. }
  31296. }
  31297. }
  31298. // Physics clone
  31299. var physicsEngine = _this.getScene().getPhysicsEngine();
  31300. if (clonePhysicsImpostor && physicsEngine) {
  31301. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31302. if (impostor) {
  31303. _this.physicsImpostor = impostor.clone(_this);
  31304. }
  31305. }
  31306. // Particles
  31307. for (index = 0; index < scene.particleSystems.length; index++) {
  31308. var system = scene.particleSystems[index];
  31309. if (system.emitter === source) {
  31310. system.clone(system.name, _this);
  31311. }
  31312. }
  31313. _this.refreshBoundingInfo();
  31314. _this.computeWorldMatrix(true);
  31315. }
  31316. // Parent
  31317. if (parent !== null) {
  31318. _this.parent = parent;
  31319. }
  31320. return _this;
  31321. }
  31322. Object.defineProperty(Mesh, "FRONTSIDE", {
  31323. /**
  31324. * Mesh side orientation : usually the external or front surface
  31325. */
  31326. get: function () {
  31327. return Mesh._FRONTSIDE;
  31328. },
  31329. enumerable: true,
  31330. configurable: true
  31331. });
  31332. Object.defineProperty(Mesh, "BACKSIDE", {
  31333. /**
  31334. * Mesh side orientation : usually the internal or back surface
  31335. */
  31336. get: function () {
  31337. return Mesh._BACKSIDE;
  31338. },
  31339. enumerable: true,
  31340. configurable: true
  31341. });
  31342. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31343. /**
  31344. * Mesh side orientation : both internal and external or front and back surfaces
  31345. */
  31346. get: function () {
  31347. return Mesh._DOUBLESIDE;
  31348. },
  31349. enumerable: true,
  31350. configurable: true
  31351. });
  31352. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31353. /**
  31354. * Mesh side orientation : by default, `FRONTSIDE`
  31355. */
  31356. get: function () {
  31357. return Mesh._DEFAULTSIDE;
  31358. },
  31359. enumerable: true,
  31360. configurable: true
  31361. });
  31362. Object.defineProperty(Mesh, "NO_CAP", {
  31363. /**
  31364. * Mesh cap setting : no cap
  31365. */
  31366. get: function () {
  31367. return Mesh._NO_CAP;
  31368. },
  31369. enumerable: true,
  31370. configurable: true
  31371. });
  31372. Object.defineProperty(Mesh, "CAP_START", {
  31373. /**
  31374. * Mesh cap setting : one cap at the beginning of the mesh
  31375. */
  31376. get: function () {
  31377. return Mesh._CAP_START;
  31378. },
  31379. enumerable: true,
  31380. configurable: true
  31381. });
  31382. Object.defineProperty(Mesh, "CAP_END", {
  31383. /**
  31384. * Mesh cap setting : one cap at the end of the mesh
  31385. */
  31386. get: function () {
  31387. return Mesh._CAP_END;
  31388. },
  31389. enumerable: true,
  31390. configurable: true
  31391. });
  31392. Object.defineProperty(Mesh, "CAP_ALL", {
  31393. /**
  31394. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31395. */
  31396. get: function () {
  31397. return Mesh._CAP_ALL;
  31398. },
  31399. enumerable: true,
  31400. configurable: true
  31401. });
  31402. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  31403. /**
  31404. * An event triggered before rendering the mesh
  31405. */
  31406. get: function () {
  31407. if (!this._onBeforeRenderObservable) {
  31408. this._onBeforeRenderObservable = new BABYLON.Observable();
  31409. }
  31410. return this._onBeforeRenderObservable;
  31411. },
  31412. enumerable: true,
  31413. configurable: true
  31414. });
  31415. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  31416. /**
  31417. * An event triggered after rendering the mesh
  31418. */
  31419. get: function () {
  31420. if (!this._onAfterRenderObservable) {
  31421. this._onAfterRenderObservable = new BABYLON.Observable();
  31422. }
  31423. return this._onAfterRenderObservable;
  31424. },
  31425. enumerable: true,
  31426. configurable: true
  31427. });
  31428. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  31429. /**
  31430. * An event triggered before drawing the mesh
  31431. */
  31432. get: function () {
  31433. if (!this._onBeforeDrawObservable) {
  31434. this._onBeforeDrawObservable = new BABYLON.Observable();
  31435. }
  31436. return this._onBeforeDrawObservable;
  31437. },
  31438. enumerable: true,
  31439. configurable: true
  31440. });
  31441. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31442. set: function (callback) {
  31443. if (this._onBeforeDrawObserver) {
  31444. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31445. }
  31446. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31447. },
  31448. enumerable: true,
  31449. configurable: true
  31450. });
  31451. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31452. get: function () {
  31453. return this._morphTargetManager;
  31454. },
  31455. set: function (value) {
  31456. if (this._morphTargetManager === value) {
  31457. return;
  31458. }
  31459. this._morphTargetManager = value;
  31460. this._syncGeometryWithMorphTargetManager();
  31461. },
  31462. enumerable: true,
  31463. configurable: true
  31464. });
  31465. Object.defineProperty(Mesh.prototype, "source", {
  31466. get: function () {
  31467. return this._source;
  31468. },
  31469. enumerable: true,
  31470. configurable: true
  31471. });
  31472. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31473. get: function () {
  31474. return this._unIndexed;
  31475. },
  31476. set: function (value) {
  31477. if (this._unIndexed !== value) {
  31478. this._unIndexed = value;
  31479. this._markSubMeshesAsAttributesDirty();
  31480. }
  31481. },
  31482. enumerable: true,
  31483. configurable: true
  31484. });
  31485. // Methods
  31486. /**
  31487. * Returns the string "Mesh".
  31488. */
  31489. Mesh.prototype.getClassName = function () {
  31490. return "Mesh";
  31491. };
  31492. /**
  31493. * Returns a string.
  31494. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31495. */
  31496. Mesh.prototype.toString = function (fullDetails) {
  31497. var ret = _super.prototype.toString.call(this, fullDetails);
  31498. ret += ", n vertices: " + this.getTotalVertices();
  31499. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31500. if (this.animations) {
  31501. for (var i = 0; i < this.animations.length; i++) {
  31502. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31503. }
  31504. }
  31505. if (fullDetails) {
  31506. if (this._geometry) {
  31507. var ib = this.getIndices();
  31508. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31509. if (vb && ib) {
  31510. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31511. }
  31512. }
  31513. else {
  31514. ret += ", flat shading: UNKNOWN";
  31515. }
  31516. }
  31517. return ret;
  31518. };
  31519. /** @hidden */
  31520. Mesh.prototype._unBindEffect = function () {
  31521. _super.prototype._unBindEffect.call(this);
  31522. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31523. var instance = _a[_i];
  31524. instance._unBindEffect();
  31525. }
  31526. };
  31527. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31528. /**
  31529. * True if the mesh has some Levels Of Details (LOD).
  31530. * Returns a boolean.
  31531. */
  31532. get: function () {
  31533. return this._LODLevels.length > 0;
  31534. },
  31535. enumerable: true,
  31536. configurable: true
  31537. });
  31538. /**
  31539. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31540. * @returns an array of {BABYLON.MeshLODLevel}
  31541. */
  31542. Mesh.prototype.getLODLevels = function () {
  31543. return this._LODLevels;
  31544. };
  31545. Mesh.prototype._sortLODLevels = function () {
  31546. this._LODLevels.sort(function (a, b) {
  31547. if (a.distance < b.distance) {
  31548. return 1;
  31549. }
  31550. if (a.distance > b.distance) {
  31551. return -1;
  31552. }
  31553. return 0;
  31554. });
  31555. };
  31556. /**
  31557. * Add a mesh as LOD level triggered at the given distance.
  31558. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31559. * @param distance The distance from the center of the object to show this level
  31560. * @param mesh The mesh to be added as LOD level (can be null)
  31561. * @return This mesh (for chaining)
  31562. */
  31563. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31564. if (mesh && mesh._masterMesh) {
  31565. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31566. return this;
  31567. }
  31568. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31569. this._LODLevels.push(level);
  31570. if (mesh) {
  31571. mesh._masterMesh = this;
  31572. }
  31573. this._sortLODLevels();
  31574. return this;
  31575. };
  31576. /**
  31577. * Returns the LOD level mesh at the passed distance or null if not found.
  31578. * It is related to the method `addLODLevel(distance, mesh)`.
  31579. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31580. * Returns an object Mesh or `null`.
  31581. */
  31582. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31583. for (var index = 0; index < this._LODLevels.length; index++) {
  31584. var level = this._LODLevels[index];
  31585. if (level.distance === distance) {
  31586. return level.mesh;
  31587. }
  31588. }
  31589. return null;
  31590. };
  31591. /**
  31592. * Remove a mesh from the LOD array
  31593. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31594. * @param {Mesh} mesh The mesh to be removed.
  31595. * @return {Mesh} This mesh (for chaining)
  31596. */
  31597. Mesh.prototype.removeLODLevel = function (mesh) {
  31598. for (var index = 0; index < this._LODLevels.length; index++) {
  31599. if (this._LODLevels[index].mesh === mesh) {
  31600. this._LODLevels.splice(index, 1);
  31601. if (mesh) {
  31602. mesh._masterMesh = null;
  31603. }
  31604. }
  31605. }
  31606. this._sortLODLevels();
  31607. return this;
  31608. };
  31609. /**
  31610. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31611. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31612. */
  31613. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31614. if (!this._LODLevels || this._LODLevels.length === 0) {
  31615. return this;
  31616. }
  31617. var bSphere;
  31618. if (boundingSphere) {
  31619. bSphere = boundingSphere;
  31620. }
  31621. else {
  31622. var boundingInfo = this.getBoundingInfo();
  31623. bSphere = boundingInfo.boundingSphere;
  31624. }
  31625. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31626. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31627. if (this.onLODLevelSelection) {
  31628. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31629. }
  31630. return this;
  31631. }
  31632. for (var index = 0; index < this._LODLevels.length; index++) {
  31633. var level = this._LODLevels[index];
  31634. if (level.distance < distanceToCamera) {
  31635. if (level.mesh) {
  31636. level.mesh._preActivate();
  31637. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31638. }
  31639. if (this.onLODLevelSelection) {
  31640. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31641. }
  31642. return level.mesh;
  31643. }
  31644. }
  31645. if (this.onLODLevelSelection) {
  31646. this.onLODLevelSelection(distanceToCamera, this, this);
  31647. }
  31648. return this;
  31649. };
  31650. Object.defineProperty(Mesh.prototype, "geometry", {
  31651. /**
  31652. * Returns the mesh internal Geometry object.
  31653. */
  31654. get: function () {
  31655. return this._geometry;
  31656. },
  31657. enumerable: true,
  31658. configurable: true
  31659. });
  31660. /**
  31661. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31662. */
  31663. Mesh.prototype.getTotalVertices = function () {
  31664. if (this._geometry === null || this._geometry === undefined) {
  31665. return 0;
  31666. }
  31667. return this._geometry.getTotalVertices();
  31668. };
  31669. /**
  31670. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31671. * 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.
  31672. * You can force the copy with forceCopy === true
  31673. * Returns null if the mesh has no geometry or no vertex buffer.
  31674. * Possible `kind` values :
  31675. * - BABYLON.VertexBuffer.PositionKind
  31676. * - BABYLON.VertexBuffer.UVKind
  31677. * - BABYLON.VertexBuffer.UV2Kind
  31678. * - BABYLON.VertexBuffer.UV3Kind
  31679. * - BABYLON.VertexBuffer.UV4Kind
  31680. * - BABYLON.VertexBuffer.UV5Kind
  31681. * - BABYLON.VertexBuffer.UV6Kind
  31682. * - BABYLON.VertexBuffer.ColorKind
  31683. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31684. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31685. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31686. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31687. */
  31688. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31689. if (!this._geometry) {
  31690. return null;
  31691. }
  31692. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31693. };
  31694. /**
  31695. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31696. * Returns `null` if the mesh has no geometry.
  31697. * Possible `kind` values :
  31698. * - BABYLON.VertexBuffer.PositionKind
  31699. * - BABYLON.VertexBuffer.UVKind
  31700. * - BABYLON.VertexBuffer.UV2Kind
  31701. * - BABYLON.VertexBuffer.UV3Kind
  31702. * - BABYLON.VertexBuffer.UV4Kind
  31703. * - BABYLON.VertexBuffer.UV5Kind
  31704. * - BABYLON.VertexBuffer.UV6Kind
  31705. * - BABYLON.VertexBuffer.ColorKind
  31706. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31707. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31708. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31709. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31710. */
  31711. Mesh.prototype.getVertexBuffer = function (kind) {
  31712. if (!this._geometry) {
  31713. return null;
  31714. }
  31715. return this._geometry.getVertexBuffer(kind);
  31716. };
  31717. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31718. if (!this._geometry) {
  31719. if (this._delayInfo) {
  31720. return this._delayInfo.indexOf(kind) !== -1;
  31721. }
  31722. return false;
  31723. }
  31724. return this._geometry.isVerticesDataPresent(kind);
  31725. };
  31726. /**
  31727. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31728. * Possible `kind` values :
  31729. * - BABYLON.VertexBuffer.PositionKind
  31730. * - BABYLON.VertexBuffer.UVKind
  31731. * - BABYLON.VertexBuffer.UV2Kind
  31732. * - BABYLON.VertexBuffer.UV3Kind
  31733. * - BABYLON.VertexBuffer.UV4Kind
  31734. * - BABYLON.VertexBuffer.UV5Kind
  31735. * - BABYLON.VertexBuffer.UV6Kind
  31736. * - BABYLON.VertexBuffer.ColorKind
  31737. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31738. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31739. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31740. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31741. */
  31742. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31743. if (!this._geometry) {
  31744. if (this._delayInfo) {
  31745. return this._delayInfo.indexOf(kind) !== -1;
  31746. }
  31747. return false;
  31748. }
  31749. return this._geometry.isVertexBufferUpdatable(kind);
  31750. };
  31751. /**
  31752. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31753. * Possible `kind` values :
  31754. * - BABYLON.VertexBuffer.PositionKind
  31755. * - BABYLON.VertexBuffer.UVKind
  31756. * - BABYLON.VertexBuffer.UV2Kind
  31757. * - BABYLON.VertexBuffer.UV3Kind
  31758. * - BABYLON.VertexBuffer.UV4Kind
  31759. * - BABYLON.VertexBuffer.UV5Kind
  31760. * - BABYLON.VertexBuffer.UV6Kind
  31761. * - BABYLON.VertexBuffer.ColorKind
  31762. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31763. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31764. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31765. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31766. */
  31767. Mesh.prototype.getVerticesDataKinds = function () {
  31768. if (!this._geometry) {
  31769. var result = new Array();
  31770. if (this._delayInfo) {
  31771. this._delayInfo.forEach(function (kind, index, array) {
  31772. result.push(kind);
  31773. });
  31774. }
  31775. return result;
  31776. }
  31777. return this._geometry.getVerticesDataKinds();
  31778. };
  31779. /**
  31780. * Returns a positive integer : the total number of indices in this mesh geometry.
  31781. * Returns zero if the mesh has no geometry.
  31782. */
  31783. Mesh.prototype.getTotalIndices = function () {
  31784. if (!this._geometry) {
  31785. return 0;
  31786. }
  31787. return this._geometry.getTotalIndices();
  31788. };
  31789. /**
  31790. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31791. * @param copyWhenShared If true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  31792. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  31793. * @returns the indices array or an empty array if the mesh has no geometry
  31794. */
  31795. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  31796. if (!this._geometry) {
  31797. return [];
  31798. }
  31799. return this._geometry.getIndices(copyWhenShared, forceCopy);
  31800. };
  31801. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31802. get: function () {
  31803. return this._masterMesh !== null && this._masterMesh !== undefined;
  31804. },
  31805. enumerable: true,
  31806. configurable: true
  31807. });
  31808. /**
  31809. * Determine if the current mesh is ready to be rendered
  31810. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31811. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31812. * @returns true if all associated assets are ready (material, textures, shaders)
  31813. */
  31814. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31815. if (completeCheck === void 0) { completeCheck = false; }
  31816. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31817. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31818. return false;
  31819. }
  31820. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31821. return false;
  31822. }
  31823. if (!this.subMeshes || this.subMeshes.length === 0) {
  31824. return true;
  31825. }
  31826. if (!completeCheck) {
  31827. return true;
  31828. }
  31829. var engine = this.getEngine();
  31830. var scene = this.getScene();
  31831. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31832. this.computeWorldMatrix();
  31833. var mat = this.material || scene.defaultMaterial;
  31834. if (mat) {
  31835. if (mat.storeEffectOnSubMeshes) {
  31836. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31837. var subMesh = _a[_i];
  31838. var effectiveMaterial = subMesh.getMaterial();
  31839. if (effectiveMaterial) {
  31840. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31841. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31842. return false;
  31843. }
  31844. }
  31845. else {
  31846. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31847. return false;
  31848. }
  31849. }
  31850. }
  31851. }
  31852. }
  31853. else {
  31854. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31855. return false;
  31856. }
  31857. }
  31858. }
  31859. // Shadows
  31860. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31861. var light = _c[_b];
  31862. var generator = light.getShadowGenerator();
  31863. if (generator) {
  31864. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31865. var subMesh = _e[_d];
  31866. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31867. return false;
  31868. }
  31869. }
  31870. }
  31871. }
  31872. // LOD
  31873. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31874. var lod = _g[_f];
  31875. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31876. return false;
  31877. }
  31878. }
  31879. return true;
  31880. };
  31881. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31882. /**
  31883. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31884. * This property is pertinent only for updatable parametric shapes.
  31885. */
  31886. get: function () {
  31887. return this._areNormalsFrozen;
  31888. },
  31889. enumerable: true,
  31890. configurable: true
  31891. });
  31892. /**
  31893. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31894. * It has no effect at all on other shapes.
  31895. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31896. * Returns the Mesh.
  31897. */
  31898. Mesh.prototype.freezeNormals = function () {
  31899. this._areNormalsFrozen = true;
  31900. return this;
  31901. };
  31902. /**
  31903. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31904. * It has no effect at all on other shapes.
  31905. * It reactivates the mesh normals computation if it was previously frozen.
  31906. * Returns the Mesh.
  31907. */
  31908. Mesh.prototype.unfreezeNormals = function () {
  31909. this._areNormalsFrozen = false;
  31910. return this;
  31911. };
  31912. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31913. /**
  31914. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31915. */
  31916. set: function (count) {
  31917. this._overridenInstanceCount = count;
  31918. },
  31919. enumerable: true,
  31920. configurable: true
  31921. });
  31922. // Methods
  31923. /** @hidden */
  31924. Mesh.prototype._preActivate = function () {
  31925. var sceneRenderId = this.getScene().getRenderId();
  31926. if (this._preActivateId === sceneRenderId) {
  31927. return this;
  31928. }
  31929. this._preActivateId = sceneRenderId;
  31930. this._visibleInstances = null;
  31931. return this;
  31932. };
  31933. /** @hidden */
  31934. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31935. if (this._visibleInstances) {
  31936. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31937. }
  31938. return this;
  31939. };
  31940. /** @hidden */
  31941. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31942. if (!this._visibleInstances) {
  31943. this._visibleInstances = {};
  31944. this._visibleInstances.defaultRenderId = renderId;
  31945. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31946. }
  31947. if (!this._visibleInstances[renderId]) {
  31948. this._visibleInstances[renderId] = new Array();
  31949. }
  31950. this._visibleInstances[renderId].push(instance);
  31951. return this;
  31952. };
  31953. /**
  31954. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31955. * This means the mesh underlying bounding box and sphere are recomputed.
  31956. * Returns the Mesh.
  31957. */
  31958. Mesh.prototype.refreshBoundingInfo = function () {
  31959. return this._refreshBoundingInfo(false);
  31960. };
  31961. /** @hidden */
  31962. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31963. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31964. return this;
  31965. }
  31966. var data = this._getPositionData(applySkeleton);
  31967. if (data) {
  31968. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31969. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31970. }
  31971. if (this.subMeshes) {
  31972. for (var index = 0; index < this.subMeshes.length; index++) {
  31973. this.subMeshes[index].refreshBoundingInfo();
  31974. }
  31975. }
  31976. this._updateBoundingInfo();
  31977. return this;
  31978. };
  31979. Mesh.prototype._getPositionData = function (applySkeleton) {
  31980. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31981. if (data && applySkeleton && this.skeleton) {
  31982. data = BABYLON.Tools.Slice(data);
  31983. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31984. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31985. if (matricesWeightsData && matricesIndicesData) {
  31986. var needExtras = this.numBoneInfluencers > 4;
  31987. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31988. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31989. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31990. var tempVector = BABYLON.Tmp.Vector3[0];
  31991. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31992. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31993. var matWeightIdx = 0;
  31994. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31995. finalMatrix.reset();
  31996. var inf;
  31997. var weight;
  31998. for (inf = 0; inf < 4; inf++) {
  31999. weight = matricesWeightsData[matWeightIdx + inf];
  32000. if (weight > 0) {
  32001. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32002. finalMatrix.addToSelf(tempMatrix);
  32003. }
  32004. }
  32005. if (needExtras) {
  32006. for (inf = 0; inf < 4; inf++) {
  32007. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32008. if (weight > 0) {
  32009. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32010. finalMatrix.addToSelf(tempMatrix);
  32011. }
  32012. }
  32013. }
  32014. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  32015. tempVector.toArray(data, index);
  32016. }
  32017. }
  32018. }
  32019. return data;
  32020. };
  32021. /** @hidden */
  32022. Mesh.prototype._createGlobalSubMesh = function (force) {
  32023. var totalVertices = this.getTotalVertices();
  32024. if (!totalVertices || !this.getIndices()) {
  32025. return null;
  32026. }
  32027. // Check if we need to recreate the submeshes
  32028. if (this.subMeshes && this.subMeshes.length > 0) {
  32029. var ib = this.getIndices();
  32030. if (!ib) {
  32031. return null;
  32032. }
  32033. var totalIndices = ib.length;
  32034. var needToRecreate = false;
  32035. if (force) {
  32036. needToRecreate = true;
  32037. }
  32038. else {
  32039. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32040. var submesh = _a[_i];
  32041. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  32042. needToRecreate = true;
  32043. break;
  32044. }
  32045. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  32046. needToRecreate = true;
  32047. break;
  32048. }
  32049. }
  32050. }
  32051. if (!needToRecreate) {
  32052. return this.subMeshes[0];
  32053. }
  32054. }
  32055. this.releaseSubMeshes();
  32056. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  32057. };
  32058. Mesh.prototype.subdivide = function (count) {
  32059. if (count < 1) {
  32060. return;
  32061. }
  32062. var totalIndices = this.getTotalIndices();
  32063. var subdivisionSize = (totalIndices / count) | 0;
  32064. var offset = 0;
  32065. // Ensure that subdivisionSize is a multiple of 3
  32066. while (subdivisionSize % 3 !== 0) {
  32067. subdivisionSize++;
  32068. }
  32069. this.releaseSubMeshes();
  32070. for (var index = 0; index < count; index++) {
  32071. if (offset >= totalIndices) {
  32072. break;
  32073. }
  32074. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32075. offset += subdivisionSize;
  32076. }
  32077. this.synchronizeInstances();
  32078. };
  32079. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32080. if (updatable === void 0) { updatable = false; }
  32081. if (!this._geometry) {
  32082. var vertexData = new BABYLON.VertexData();
  32083. vertexData.set(data, kind);
  32084. var scene = this.getScene();
  32085. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32086. }
  32087. else {
  32088. this._geometry.setVerticesData(kind, data, updatable, stride);
  32089. }
  32090. return this;
  32091. };
  32092. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32093. if (updatable === void 0) { updatable = true; }
  32094. var vb = this.getVertexBuffer(kind);
  32095. if (!vb || vb.isUpdatable() === updatable) {
  32096. return;
  32097. }
  32098. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32099. };
  32100. /**
  32101. * Sets the mesh VertexBuffer.
  32102. * Returns the Mesh.
  32103. */
  32104. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32105. if (!this._geometry) {
  32106. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32107. }
  32108. this._geometry.setVerticesBuffer(buffer);
  32109. return this;
  32110. };
  32111. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32112. if (!this._geometry) {
  32113. return this;
  32114. }
  32115. if (!makeItUnique) {
  32116. this._geometry.updateVerticesData(kind, data, updateExtends);
  32117. }
  32118. else {
  32119. this.makeGeometryUnique();
  32120. this.updateVerticesData(kind, data, updateExtends, false);
  32121. }
  32122. return this;
  32123. };
  32124. /**
  32125. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32126. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32127. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  32128. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  32129. * Returns the Mesh.
  32130. */
  32131. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32132. if (computeNormals === void 0) { computeNormals = true; }
  32133. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32134. if (!positions) {
  32135. return this;
  32136. }
  32137. positionFunction(positions);
  32138. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32139. if (computeNormals) {
  32140. var indices = this.getIndices();
  32141. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32142. if (!normals) {
  32143. return this;
  32144. }
  32145. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32146. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32147. }
  32148. return this;
  32149. };
  32150. /**
  32151. * Creates a un-shared specific occurence of the geometry for the mesh.
  32152. * Returns the Mesh.
  32153. */
  32154. Mesh.prototype.makeGeometryUnique = function () {
  32155. if (!this._geometry) {
  32156. return this;
  32157. }
  32158. var oldGeometry = this._geometry;
  32159. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32160. oldGeometry.releaseForMesh(this, true);
  32161. geometry.applyToMesh(this);
  32162. return this;
  32163. };
  32164. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32165. if (totalVertices === void 0) { totalVertices = null; }
  32166. if (updatable === void 0) { updatable = false; }
  32167. if (!this._geometry) {
  32168. var vertexData = new BABYLON.VertexData();
  32169. vertexData.indices = indices;
  32170. var scene = this.getScene();
  32171. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32172. }
  32173. else {
  32174. this._geometry.setIndices(indices, totalVertices, updatable);
  32175. }
  32176. return this;
  32177. };
  32178. /**
  32179. * Update the current index buffer
  32180. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  32181. * Returns the Mesh.
  32182. */
  32183. Mesh.prototype.updateIndices = function (indices, offset) {
  32184. if (!this._geometry) {
  32185. return this;
  32186. }
  32187. this._geometry.updateIndices(indices, offset);
  32188. return this;
  32189. };
  32190. /**
  32191. * Invert the geometry to move from a right handed system to a left handed one.
  32192. * Returns the Mesh.
  32193. */
  32194. Mesh.prototype.toLeftHanded = function () {
  32195. if (!this._geometry) {
  32196. return this;
  32197. }
  32198. this._geometry.toLeftHanded();
  32199. return this;
  32200. };
  32201. /** @hidden */
  32202. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32203. if (!this._geometry) {
  32204. return this;
  32205. }
  32206. var engine = this.getScene().getEngine();
  32207. // Wireframe
  32208. var indexToBind;
  32209. if (this._unIndexed) {
  32210. indexToBind = null;
  32211. }
  32212. else {
  32213. switch (fillMode) {
  32214. case BABYLON.Material.PointFillMode:
  32215. indexToBind = null;
  32216. break;
  32217. case BABYLON.Material.WireFrameFillMode:
  32218. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32219. break;
  32220. default:
  32221. case BABYLON.Material.TriangleFillMode:
  32222. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32223. break;
  32224. }
  32225. }
  32226. // VBOs
  32227. this._geometry._bind(effect, indexToBind);
  32228. return this;
  32229. };
  32230. /** @hidden */
  32231. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32232. if (alternate === void 0) { alternate = false; }
  32233. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32234. return this;
  32235. }
  32236. if (this._onBeforeDrawObservable) {
  32237. this._onBeforeDrawObservable.notifyObservers(this);
  32238. }
  32239. var scene = this.getScene();
  32240. var engine = scene.getEngine();
  32241. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32242. // or triangles as points
  32243. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32244. }
  32245. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32246. // Triangles as wireframe
  32247. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32248. }
  32249. else {
  32250. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32251. }
  32252. if (scene._isAlternateRenderingEnabled && !alternate) {
  32253. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32254. if (!effect || !scene.activeCamera) {
  32255. return this;
  32256. }
  32257. scene._switchToAlternateCameraConfiguration(true);
  32258. this._effectiveMaterial.bindView(effect);
  32259. this._effectiveMaterial.bindViewProjection(effect);
  32260. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32261. this._draw(subMesh, fillMode, instancesCount, true);
  32262. engine.setViewport(scene.activeCamera.viewport);
  32263. scene._switchToAlternateCameraConfiguration(false);
  32264. this._effectiveMaterial.bindView(effect);
  32265. this._effectiveMaterial.bindViewProjection(effect);
  32266. }
  32267. return this;
  32268. };
  32269. /**
  32270. * Registers for this mesh a javascript function called just before the rendering process.
  32271. * This function is passed the current mesh.
  32272. * Return the Mesh.
  32273. */
  32274. Mesh.prototype.registerBeforeRender = function (func) {
  32275. this.onBeforeRenderObservable.add(func);
  32276. return this;
  32277. };
  32278. /**
  32279. * Disposes a previously registered javascript function called before the rendering.
  32280. * This function is passed the current mesh.
  32281. * Returns the Mesh.
  32282. */
  32283. Mesh.prototype.unregisterBeforeRender = function (func) {
  32284. this.onBeforeRenderObservable.removeCallback(func);
  32285. return this;
  32286. };
  32287. /**
  32288. * Registers for this mesh a javascript function called just after the rendering is complete.
  32289. * This function is passed the current mesh.
  32290. * Returns the Mesh.
  32291. */
  32292. Mesh.prototype.registerAfterRender = function (func) {
  32293. this.onAfterRenderObservable.add(func);
  32294. return this;
  32295. };
  32296. /**
  32297. * Disposes a previously registered javascript function called after the rendering.
  32298. * This function is passed the current mesh.
  32299. * Return the Mesh.
  32300. */
  32301. Mesh.prototype.unregisterAfterRender = function (func) {
  32302. this.onAfterRenderObservable.removeCallback(func);
  32303. return this;
  32304. };
  32305. /** @hidden */
  32306. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32307. var scene = this.getScene();
  32308. this._batchCache.mustReturn = false;
  32309. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32310. this._batchCache.visibleInstances[subMeshId] = null;
  32311. if (this._visibleInstances) {
  32312. var currentRenderId = scene.getRenderId();
  32313. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32314. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32315. var selfRenderId = this._renderId;
  32316. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32317. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32318. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32319. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32320. }
  32321. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32322. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32323. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32324. this._batchCache.mustReturn = true;
  32325. return this._batchCache;
  32326. }
  32327. if (currentRenderId !== selfRenderId) {
  32328. this._batchCache.renderSelf[subMeshId] = false;
  32329. }
  32330. }
  32331. this._renderIdForInstances[subMeshId] = currentRenderId;
  32332. }
  32333. return this._batchCache;
  32334. };
  32335. /** @hidden */
  32336. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32337. var visibleInstances = batch.visibleInstances[subMesh._id];
  32338. if (!visibleInstances) {
  32339. return this;
  32340. }
  32341. var matricesCount = visibleInstances.length + 1;
  32342. var bufferSize = matricesCount * 16 * 4;
  32343. var currentInstancesBufferSize = this._instancesBufferSize;
  32344. var instancesBuffer = this._instancesBuffer;
  32345. while (this._instancesBufferSize < bufferSize) {
  32346. this._instancesBufferSize *= 2;
  32347. }
  32348. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32349. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32350. }
  32351. var offset = 0;
  32352. var instancesCount = 0;
  32353. var world = this.getWorldMatrix();
  32354. if (batch.renderSelf[subMesh._id]) {
  32355. world.copyToArray(this._instancesData, offset);
  32356. offset += 16;
  32357. instancesCount++;
  32358. }
  32359. if (visibleInstances) {
  32360. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32361. var instance = visibleInstances[instanceIndex];
  32362. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32363. offset += 16;
  32364. instancesCount++;
  32365. }
  32366. }
  32367. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32368. if (instancesBuffer) {
  32369. instancesBuffer.dispose();
  32370. }
  32371. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32372. this._instancesBuffer = instancesBuffer;
  32373. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32374. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32375. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32376. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32377. }
  32378. else {
  32379. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32380. }
  32381. this._bind(subMesh, effect, fillMode);
  32382. this._draw(subMesh, fillMode, instancesCount);
  32383. engine.unbindInstanceAttributes();
  32384. return this;
  32385. };
  32386. /** @hidden */
  32387. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32388. var scene = this.getScene();
  32389. var engine = scene.getEngine();
  32390. if (hardwareInstancedRendering) {
  32391. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32392. }
  32393. else {
  32394. if (batch.renderSelf[subMesh._id]) {
  32395. // Draw
  32396. if (onBeforeDraw) {
  32397. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32398. }
  32399. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32400. }
  32401. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32402. if (visibleInstancesForSubMesh) {
  32403. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32404. var instance = visibleInstancesForSubMesh[instanceIndex];
  32405. // World
  32406. var world = instance.getWorldMatrix();
  32407. if (onBeforeDraw) {
  32408. onBeforeDraw(true, world, effectiveMaterial);
  32409. }
  32410. // Draw
  32411. this._draw(subMesh, fillMode);
  32412. }
  32413. }
  32414. }
  32415. return this;
  32416. };
  32417. /**
  32418. * 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
  32419. * @param subMesh defines the subMesh to render
  32420. * @param enableAlphaMode defines if alpha mode can be changed
  32421. * @returns the current mesh
  32422. */
  32423. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32424. this._checkOcclusionQuery();
  32425. if (this._isOccluded) {
  32426. return this;
  32427. }
  32428. var scene = this.getScene();
  32429. // Managing instances
  32430. var batch = this._getInstancesRenderList(subMesh._id);
  32431. if (batch.mustReturn) {
  32432. return this;
  32433. }
  32434. // Checking geometry state
  32435. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32436. return this;
  32437. }
  32438. if (this._onBeforeRenderObservable) {
  32439. this._onBeforeRenderObservable.notifyObservers(this);
  32440. }
  32441. var engine = scene.getEngine();
  32442. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32443. // Material
  32444. var material = subMesh.getMaterial();
  32445. if (!material) {
  32446. return this;
  32447. }
  32448. this._effectiveMaterial = material;
  32449. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32450. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32451. return this;
  32452. }
  32453. }
  32454. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32455. return this;
  32456. }
  32457. // Alpha mode
  32458. if (enableAlphaMode) {
  32459. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32460. }
  32461. // Outline - step 1
  32462. var savedDepthWrite = engine.getDepthWrite();
  32463. if (this.renderOutline) {
  32464. engine.setDepthWrite(false);
  32465. scene.getOutlineRenderer().render(subMesh, batch);
  32466. engine.setDepthWrite(savedDepthWrite);
  32467. }
  32468. var effect;
  32469. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32470. effect = subMesh.effect;
  32471. }
  32472. else {
  32473. effect = this._effectiveMaterial.getEffect();
  32474. }
  32475. if (!effect) {
  32476. return this;
  32477. }
  32478. var sideOrientation = this.overrideMaterialSideOrientation;
  32479. if (sideOrientation == null) {
  32480. sideOrientation = this._effectiveMaterial.sideOrientation;
  32481. if (this._getWorldMatrixDeterminant() < 0) {
  32482. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32483. }
  32484. }
  32485. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32486. if (this._effectiveMaterial.forceDepthWrite) {
  32487. engine.setDepthWrite(true);
  32488. }
  32489. // Bind
  32490. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32491. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32492. this._bind(subMesh, effect, fillMode);
  32493. }
  32494. var world = this.getWorldMatrix();
  32495. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32496. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32497. }
  32498. else {
  32499. this._effectiveMaterial.bind(world, this);
  32500. }
  32501. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32502. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32503. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32504. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32505. }
  32506. // Draw
  32507. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32508. // Unbind
  32509. this._effectiveMaterial.unbind();
  32510. // Outline - step 2
  32511. if (this.renderOutline && savedDepthWrite) {
  32512. engine.setDepthWrite(true);
  32513. engine.setColorWrite(false);
  32514. scene.getOutlineRenderer().render(subMesh, batch);
  32515. engine.setColorWrite(true);
  32516. }
  32517. // Overlay
  32518. if (this.renderOverlay) {
  32519. var currentMode = engine.getAlphaMode();
  32520. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32521. scene.getOutlineRenderer().render(subMesh, batch, true);
  32522. engine.setAlphaMode(currentMode);
  32523. }
  32524. if (this._onAfterRenderObservable) {
  32525. this._onAfterRenderObservable.notifyObservers(this);
  32526. }
  32527. return this;
  32528. };
  32529. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32530. if (isInstance && effectiveMaterial) {
  32531. effectiveMaterial.bindOnlyWorldMatrix(world);
  32532. }
  32533. };
  32534. /**
  32535. * Returns an array populated with IParticleSystem objects whose the mesh is the emitter.
  32536. */
  32537. Mesh.prototype.getEmittedParticleSystems = function () {
  32538. var results = new Array();
  32539. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32540. var particleSystem = this.getScene().particleSystems[index];
  32541. if (particleSystem.emitter === this) {
  32542. results.push(particleSystem);
  32543. }
  32544. }
  32545. return results;
  32546. };
  32547. /**
  32548. * Returns an array populated with IParticleSystem objects whose the mesh or its children are the emitter.
  32549. */
  32550. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32551. var results = new Array();
  32552. var descendants = this.getDescendants();
  32553. descendants.push(this);
  32554. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32555. var particleSystem = this.getScene().particleSystems[index];
  32556. var emitter = particleSystem.emitter;
  32557. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32558. results.push(particleSystem);
  32559. }
  32560. }
  32561. return results;
  32562. };
  32563. /**
  32564. * Normalize matrix weights so that all vertices have a total weight set to 1
  32565. */
  32566. Mesh.prototype.cleanMatrixWeights = function () {
  32567. var epsilon = 1e-3;
  32568. var noInfluenceBoneIndex = 0.0;
  32569. if (this.skeleton) {
  32570. noInfluenceBoneIndex = this.skeleton.bones.length;
  32571. }
  32572. else {
  32573. return;
  32574. }
  32575. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32576. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32577. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32578. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32579. var influencers = this.numBoneInfluencers;
  32580. var size = matricesWeights.length;
  32581. for (var i = 0; i < size; i += 4) {
  32582. var weight = 0.0;
  32583. var firstZeroWeight = -1;
  32584. for (var j = 0; j < 4; j++) {
  32585. var w = matricesWeights[i + j];
  32586. weight += w;
  32587. if (w < epsilon && firstZeroWeight < 0) {
  32588. firstZeroWeight = j;
  32589. }
  32590. }
  32591. if (matricesWeightsExtra) {
  32592. for (var j = 0; j < 4; j++) {
  32593. var w = matricesWeightsExtra[i + j];
  32594. weight += w;
  32595. if (w < epsilon && firstZeroWeight < 0) {
  32596. firstZeroWeight = j + 4;
  32597. }
  32598. }
  32599. }
  32600. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32601. firstZeroWeight = influencers - 1;
  32602. }
  32603. if (weight > epsilon) {
  32604. var mweight = 1.0 / weight;
  32605. for (var j = 0; j < 4; j++) {
  32606. matricesWeights[i + j] *= mweight;
  32607. }
  32608. if (matricesWeightsExtra) {
  32609. for (var j = 0; j < 4; j++) {
  32610. matricesWeightsExtra[i + j] *= mweight;
  32611. }
  32612. }
  32613. }
  32614. else {
  32615. if (firstZeroWeight >= 4) {
  32616. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32617. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32618. }
  32619. else {
  32620. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32621. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32622. }
  32623. }
  32624. }
  32625. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32626. if (matricesIndicesExtra) {
  32627. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32628. }
  32629. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32630. if (matricesWeightsExtra) {
  32631. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32632. }
  32633. };
  32634. /** @hidden */
  32635. Mesh.prototype._checkDelayState = function () {
  32636. var scene = this.getScene();
  32637. if (this._geometry) {
  32638. this._geometry.load(scene);
  32639. }
  32640. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32641. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32642. this._queueLoad(scene);
  32643. }
  32644. return this;
  32645. };
  32646. Mesh.prototype._queueLoad = function (scene) {
  32647. var _this = this;
  32648. scene._addPendingData(this);
  32649. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32650. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32651. if (data instanceof ArrayBuffer) {
  32652. _this._delayLoadingFunction(data, _this);
  32653. }
  32654. else {
  32655. _this._delayLoadingFunction(JSON.parse(data), _this);
  32656. }
  32657. _this.instances.forEach(function (instance) {
  32658. instance._syncSubMeshes();
  32659. });
  32660. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32661. scene._removePendingData(_this);
  32662. }, function () { }, scene.database, getBinaryData);
  32663. return this;
  32664. };
  32665. /**
  32666. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  32667. * A mesh is in the frustum if its bounding box intersects the frustum
  32668. * @param frustumPlanes defines the frustum to test
  32669. * @returns true if the mesh is in the frustum planes
  32670. */
  32671. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32672. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32673. return false;
  32674. }
  32675. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32676. return false;
  32677. }
  32678. this._checkDelayState();
  32679. return true;
  32680. };
  32681. /**
  32682. * Sets the mesh material by the material or multiMaterial `id` property.
  32683. * The material `id` is a string identifying the material or the multiMaterial.
  32684. * This method returns the Mesh.
  32685. */
  32686. Mesh.prototype.setMaterialByID = function (id) {
  32687. var materials = this.getScene().materials;
  32688. var index;
  32689. for (index = materials.length - 1; index > -1; index--) {
  32690. if (materials[index].id === id) {
  32691. this.material = materials[index];
  32692. return this;
  32693. }
  32694. }
  32695. // Multi
  32696. var multiMaterials = this.getScene().multiMaterials;
  32697. for (index = multiMaterials.length - 1; index > -1; index--) {
  32698. if (multiMaterials[index].id === id) {
  32699. this.material = multiMaterials[index];
  32700. return this;
  32701. }
  32702. }
  32703. return this;
  32704. };
  32705. /**
  32706. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32707. */
  32708. Mesh.prototype.getAnimatables = function () {
  32709. var results = new Array();
  32710. if (this.material) {
  32711. results.push(this.material);
  32712. }
  32713. if (this.skeleton) {
  32714. results.push(this.skeleton);
  32715. }
  32716. return results;
  32717. };
  32718. /**
  32719. * Modifies the mesh geometry according to the passed transformation matrix.
  32720. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32721. * The mesh normals are modified accordingly the same transformation.
  32722. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32723. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32724. * Returns the Mesh.
  32725. */
  32726. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32727. // Position
  32728. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32729. return this;
  32730. }
  32731. var submeshes = this.subMeshes.splice(0);
  32732. this._resetPointsArrayCache();
  32733. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32734. var temp = new Array();
  32735. var index;
  32736. for (index = 0; index < data.length; index += 3) {
  32737. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32738. }
  32739. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32740. // Normals
  32741. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32742. return this;
  32743. }
  32744. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32745. temp = [];
  32746. for (index = 0; index < data.length; index += 3) {
  32747. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32748. }
  32749. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32750. // flip faces?
  32751. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32752. this.flipFaces();
  32753. }
  32754. // Restore submeshes
  32755. this.releaseSubMeshes();
  32756. this.subMeshes = submeshes;
  32757. return this;
  32758. };
  32759. /**
  32760. * Modifies the mesh geometry according to its own current World Matrix.
  32761. * The mesh World Matrix is then reset.
  32762. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32763. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32764. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32765. * Returns the Mesh.
  32766. */
  32767. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32768. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32769. this.scaling.copyFromFloats(1, 1, 1);
  32770. this.position.copyFromFloats(0, 0, 0);
  32771. this.rotation.copyFromFloats(0, 0, 0);
  32772. //only if quaternion is already set
  32773. if (this.rotationQuaternion) {
  32774. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32775. }
  32776. this._worldMatrix = BABYLON.Matrix.Identity();
  32777. return this;
  32778. };
  32779. Object.defineProperty(Mesh.prototype, "_positions", {
  32780. // Cache
  32781. get: function () {
  32782. if (this._geometry) {
  32783. return this._geometry._positions;
  32784. }
  32785. return null;
  32786. },
  32787. enumerable: true,
  32788. configurable: true
  32789. });
  32790. /** @hidden */
  32791. Mesh.prototype._resetPointsArrayCache = function () {
  32792. if (this._geometry) {
  32793. this._geometry._resetPointsArrayCache();
  32794. }
  32795. return this;
  32796. };
  32797. /** @hidden */
  32798. Mesh.prototype._generatePointsArray = function () {
  32799. if (this._geometry) {
  32800. return this._geometry._generatePointsArray();
  32801. }
  32802. return false;
  32803. };
  32804. /**
  32805. * Returns a new Mesh object generated from the current mesh properties.
  32806. * This method must not get confused with createInstance().
  32807. * The parameter `name` is a string, the name given to the new mesh.
  32808. * The optional parameter `newParent` can be any Node object (default `null`).
  32809. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32810. * 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.
  32811. */
  32812. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32813. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32814. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32815. };
  32816. /**
  32817. * Releases resources associated with this mesh.
  32818. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32819. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32820. */
  32821. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32822. var _this = this;
  32823. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32824. this.morphTargetManager = null;
  32825. if (this._geometry) {
  32826. this._geometry.releaseForMesh(this, true);
  32827. }
  32828. if (this._onBeforeDrawObservable) {
  32829. this._onBeforeDrawObservable.clear();
  32830. }
  32831. if (this._onBeforeRenderObservable) {
  32832. this._onBeforeRenderObservable.clear();
  32833. }
  32834. if (this._onAfterRenderObservable) {
  32835. this._onAfterRenderObservable.clear();
  32836. }
  32837. // Sources
  32838. var meshes = this.getScene().meshes;
  32839. meshes.forEach(function (abstractMesh) {
  32840. var mesh = abstractMesh;
  32841. if (mesh._source && mesh._source === _this) {
  32842. mesh._source = null;
  32843. }
  32844. });
  32845. this._source = null;
  32846. // Instances
  32847. if (this._instancesBuffer) {
  32848. this._instancesBuffer.dispose();
  32849. this._instancesBuffer = null;
  32850. }
  32851. while (this.instances.length) {
  32852. this.instances[0].dispose();
  32853. }
  32854. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32855. };
  32856. /**
  32857. * Modifies the mesh geometry according to a displacement map.
  32858. * 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.
  32859. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32860. * This method returns nothing.
  32861. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32862. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32863. * 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.
  32864. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32865. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32866. *
  32867. * Returns the Mesh.
  32868. */
  32869. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32870. var _this = this;
  32871. var scene = this.getScene();
  32872. var onload = function (img) {
  32873. // Getting height map data
  32874. var canvas = document.createElement("canvas");
  32875. var context = canvas.getContext("2d");
  32876. var heightMapWidth = img.width;
  32877. var heightMapHeight = img.height;
  32878. canvas.width = heightMapWidth;
  32879. canvas.height = heightMapHeight;
  32880. context.drawImage(img, 0, 0);
  32881. // Create VertexData from map data
  32882. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32883. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32884. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32885. //execute success callback, if set
  32886. if (onSuccess) {
  32887. onSuccess(_this);
  32888. }
  32889. };
  32890. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32891. return this;
  32892. };
  32893. /**
  32894. * Modifies the mesh geometry according to a displacementMap buffer.
  32895. * 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.
  32896. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32897. * This method returns nothing.
  32898. * 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.
  32899. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32900. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32901. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32902. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32903. *
  32904. * Returns the Mesh.
  32905. */
  32906. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32907. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32908. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32909. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32910. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32911. return this;
  32912. }
  32913. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32914. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32915. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32916. var position = BABYLON.Vector3.Zero();
  32917. var normal = BABYLON.Vector3.Zero();
  32918. var uv = BABYLON.Vector2.Zero();
  32919. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32920. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32921. for (var index = 0; index < positions.length; index += 3) {
  32922. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32923. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32924. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32925. // Compute height
  32926. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32927. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32928. var pos = (u + v * heightMapWidth) * 4;
  32929. var r = buffer[pos] / 255.0;
  32930. var g = buffer[pos + 1] / 255.0;
  32931. var b = buffer[pos + 2] / 255.0;
  32932. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32933. normal.normalize();
  32934. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32935. position = position.add(normal);
  32936. position.toArray(positions, index);
  32937. }
  32938. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32939. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32940. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32941. return this;
  32942. };
  32943. /**
  32944. * Modify the mesh to get a flat shading rendering.
  32945. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32946. * This method returns the Mesh.
  32947. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32948. */
  32949. Mesh.prototype.convertToFlatShadedMesh = function () {
  32950. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32951. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32952. var kinds = this.getVerticesDataKinds();
  32953. var vbs = {};
  32954. var data = {};
  32955. var newdata = {};
  32956. var updatableNormals = false;
  32957. var kindIndex;
  32958. var kind;
  32959. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32960. kind = kinds[kindIndex];
  32961. var vertexBuffer = this.getVertexBuffer(kind);
  32962. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32963. updatableNormals = vertexBuffer.isUpdatable();
  32964. kinds.splice(kindIndex, 1);
  32965. kindIndex--;
  32966. continue;
  32967. }
  32968. vbs[kind] = vertexBuffer;
  32969. data[kind] = vbs[kind].getData();
  32970. newdata[kind] = [];
  32971. }
  32972. // Save previous submeshes
  32973. var previousSubmeshes = this.subMeshes.slice(0);
  32974. var indices = this.getIndices();
  32975. var totalIndices = this.getTotalIndices();
  32976. // Generating unique vertices per face
  32977. var index;
  32978. for (index = 0; index < totalIndices; index++) {
  32979. var vertexIndex = indices[index];
  32980. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32981. kind = kinds[kindIndex];
  32982. var stride = vbs[kind].getStrideSize();
  32983. for (var offset = 0; offset < stride; offset++) {
  32984. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32985. }
  32986. }
  32987. }
  32988. // Updating faces & normal
  32989. var normals = [];
  32990. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32991. for (index = 0; index < totalIndices; index += 3) {
  32992. indices[index] = index;
  32993. indices[index + 1] = index + 1;
  32994. indices[index + 2] = index + 2;
  32995. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32996. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32997. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32998. var p1p2 = p1.subtract(p2);
  32999. var p3p2 = p3.subtract(p2);
  33000. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  33001. // Store same normals for every vertex
  33002. for (var localIndex = 0; localIndex < 3; localIndex++) {
  33003. normals.push(normal.x);
  33004. normals.push(normal.y);
  33005. normals.push(normal.z);
  33006. }
  33007. }
  33008. this.setIndices(indices);
  33009. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  33010. // Updating vertex buffers
  33011. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33012. kind = kinds[kindIndex];
  33013. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33014. }
  33015. // Updating submeshes
  33016. this.releaseSubMeshes();
  33017. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33018. var previousOne = previousSubmeshes[submeshIndex];
  33019. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33020. }
  33021. this.synchronizeInstances();
  33022. return this;
  33023. };
  33024. /**
  33025. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  33026. * In other words, more vertices, no more indices and a single bigger VBO.
  33027. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  33028. * Returns the Mesh.
  33029. */
  33030. Mesh.prototype.convertToUnIndexedMesh = function () {
  33031. /// <summary>Remove indices by unfolding faces into buffers</summary>
  33032. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33033. var kinds = this.getVerticesDataKinds();
  33034. var vbs = {};
  33035. var data = {};
  33036. var newdata = {};
  33037. var kindIndex;
  33038. var kind;
  33039. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33040. kind = kinds[kindIndex];
  33041. var vertexBuffer = this.getVertexBuffer(kind);
  33042. vbs[kind] = vertexBuffer;
  33043. data[kind] = vbs[kind].getData();
  33044. newdata[kind] = [];
  33045. }
  33046. // Save previous submeshes
  33047. var previousSubmeshes = this.subMeshes.slice(0);
  33048. var indices = this.getIndices();
  33049. var totalIndices = this.getTotalIndices();
  33050. // Generating unique vertices per face
  33051. var index;
  33052. for (index = 0; index < totalIndices; index++) {
  33053. var vertexIndex = indices[index];
  33054. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33055. kind = kinds[kindIndex];
  33056. var stride = vbs[kind].getStrideSize();
  33057. for (var offset = 0; offset < stride; offset++) {
  33058. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33059. }
  33060. }
  33061. }
  33062. // Updating indices
  33063. for (index = 0; index < totalIndices; index += 3) {
  33064. indices[index] = index;
  33065. indices[index + 1] = index + 1;
  33066. indices[index + 2] = index + 2;
  33067. }
  33068. this.setIndices(indices);
  33069. // Updating vertex buffers
  33070. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33071. kind = kinds[kindIndex];
  33072. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33073. }
  33074. // Updating submeshes
  33075. this.releaseSubMeshes();
  33076. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33077. var previousOne = previousSubmeshes[submeshIndex];
  33078. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33079. }
  33080. this._unIndexed = true;
  33081. this.synchronizeInstances();
  33082. return this;
  33083. };
  33084. /**
  33085. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  33086. * This method returns the Mesh.
  33087. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33088. */
  33089. Mesh.prototype.flipFaces = function (flipNormals) {
  33090. if (flipNormals === void 0) { flipNormals = false; }
  33091. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33092. var i;
  33093. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33094. for (i = 0; i < vertex_data.normals.length; i++) {
  33095. vertex_data.normals[i] *= -1;
  33096. }
  33097. }
  33098. if (vertex_data.indices) {
  33099. var temp;
  33100. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33101. // reassign indices
  33102. temp = vertex_data.indices[i + 1];
  33103. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33104. vertex_data.indices[i + 2] = temp;
  33105. }
  33106. }
  33107. vertex_data.applyToMesh(this);
  33108. return this;
  33109. };
  33110. // Instances
  33111. /**
  33112. * Creates a new InstancedMesh object from the mesh model.
  33113. * An instance shares the same properties and the same material than its model.
  33114. * Please make sure to call mesh.makeGeometryUnique() if you are calling createInstance on a previously cloned mesh.
  33115. * Only these properties of each instance can then be set individually :
  33116. * - position
  33117. * - rotation
  33118. * - rotationQuaternion
  33119. * - setPivotMatrix
  33120. * - scaling
  33121. *
  33122. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  33123. * Warning : this method is not supported for Line mesh and LineSystem
  33124. */
  33125. Mesh.prototype.createInstance = function (name) {
  33126. return new BABYLON.InstancedMesh(name, this);
  33127. };
  33128. /**
  33129. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33130. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33131. * This method returns the Mesh.
  33132. */
  33133. Mesh.prototype.synchronizeInstances = function () {
  33134. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33135. var instance = this.instances[instanceIndex];
  33136. instance._syncSubMeshes();
  33137. }
  33138. return this;
  33139. };
  33140. /**
  33141. * Simplify the mesh according to the given array of settings.
  33142. * Function will return immediately and will simplify async. It returns the Mesh.
  33143. * @param settings a collection of simplification settings.
  33144. * @param parallelProcessing should all levels calculate parallel or one after the other.
  33145. * @param type the type of simplification to run.
  33146. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  33147. */
  33148. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  33149. if (parallelProcessing === void 0) { parallelProcessing = true; }
  33150. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  33151. this.getScene().simplificationQueue.addTask({
  33152. settings: settings,
  33153. parallelProcessing: parallelProcessing,
  33154. mesh: this,
  33155. simplificationType: simplificationType,
  33156. successCallback: successCallback
  33157. });
  33158. return this;
  33159. };
  33160. /**
  33161. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33162. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33163. * This should be used together with the simplification to avoid disappearing triangles.
  33164. * Returns the Mesh.
  33165. * @param successCallback an optional success callback to be called after the optimization finished.
  33166. */
  33167. Mesh.prototype.optimizeIndices = function (successCallback) {
  33168. var _this = this;
  33169. var indices = this.getIndices();
  33170. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33171. if (!positions || !indices) {
  33172. return this;
  33173. }
  33174. var vectorPositions = new Array();
  33175. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33176. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33177. }
  33178. var dupes = new Array();
  33179. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33180. var realPos = vectorPositions.length - 1 - iteration;
  33181. var testedPosition = vectorPositions[realPos];
  33182. for (var j = 0; j < realPos; ++j) {
  33183. var againstPosition = vectorPositions[j];
  33184. if (testedPosition.equals(againstPosition)) {
  33185. dupes[realPos] = j;
  33186. break;
  33187. }
  33188. }
  33189. }, function () {
  33190. for (var i = 0; i < indices.length; ++i) {
  33191. indices[i] = dupes[indices[i]] || indices[i];
  33192. }
  33193. //indices are now reordered
  33194. var originalSubMeshes = _this.subMeshes.slice(0);
  33195. _this.setIndices(indices);
  33196. _this.subMeshes = originalSubMeshes;
  33197. if (successCallback) {
  33198. successCallback(_this);
  33199. }
  33200. });
  33201. return this;
  33202. };
  33203. Mesh.prototype.serialize = function (serializationObject) {
  33204. serializationObject.name = this.name;
  33205. serializationObject.id = this.id;
  33206. serializationObject.type = this.getClassName();
  33207. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33208. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33209. }
  33210. serializationObject.position = this.position.asArray();
  33211. if (this.rotationQuaternion) {
  33212. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33213. }
  33214. else if (this.rotation) {
  33215. serializationObject.rotation = this.rotation.asArray();
  33216. }
  33217. serializationObject.scaling = this.scaling.asArray();
  33218. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33219. serializationObject.isEnabled = this.isEnabled(false);
  33220. serializationObject.isVisible = this.isVisible;
  33221. serializationObject.infiniteDistance = this.infiniteDistance;
  33222. serializationObject.pickable = this.isPickable;
  33223. serializationObject.receiveShadows = this.receiveShadows;
  33224. serializationObject.billboardMode = this.billboardMode;
  33225. serializationObject.visibility = this.visibility;
  33226. serializationObject.checkCollisions = this.checkCollisions;
  33227. serializationObject.isBlocker = this.isBlocker;
  33228. // Parent
  33229. if (this.parent) {
  33230. serializationObject.parentId = this.parent.id;
  33231. }
  33232. // Geometry
  33233. serializationObject.isUnIndexed = this.isUnIndexed;
  33234. var geometry = this._geometry;
  33235. if (geometry) {
  33236. var geometryId = geometry.id;
  33237. serializationObject.geometryId = geometryId;
  33238. // SubMeshes
  33239. serializationObject.subMeshes = [];
  33240. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33241. var subMesh = this.subMeshes[subIndex];
  33242. serializationObject.subMeshes.push({
  33243. materialIndex: subMesh.materialIndex,
  33244. verticesStart: subMesh.verticesStart,
  33245. verticesCount: subMesh.verticesCount,
  33246. indexStart: subMesh.indexStart,
  33247. indexCount: subMesh.indexCount
  33248. });
  33249. }
  33250. }
  33251. // Material
  33252. if (this.material) {
  33253. serializationObject.materialId = this.material.id;
  33254. }
  33255. else {
  33256. this.material = null;
  33257. }
  33258. // Morph targets
  33259. if (this.morphTargetManager) {
  33260. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33261. }
  33262. // Skeleton
  33263. if (this.skeleton) {
  33264. serializationObject.skeletonId = this.skeleton.id;
  33265. }
  33266. // Physics
  33267. //TODO implement correct serialization for physics impostors.
  33268. var impostor = this.getPhysicsImpostor();
  33269. if (impostor) {
  33270. serializationObject.physicsMass = impostor.getParam("mass");
  33271. serializationObject.physicsFriction = impostor.getParam("friction");
  33272. serializationObject.physicsRestitution = impostor.getParam("mass");
  33273. serializationObject.physicsImpostor = impostor.type;
  33274. }
  33275. // Metadata
  33276. if (this.metadata) {
  33277. serializationObject.metadata = this.metadata;
  33278. }
  33279. // Instances
  33280. serializationObject.instances = [];
  33281. for (var index = 0; index < this.instances.length; index++) {
  33282. var instance = this.instances[index];
  33283. var serializationInstance = {
  33284. name: instance.name,
  33285. id: instance.id,
  33286. position: instance.position.asArray(),
  33287. scaling: instance.scaling.asArray()
  33288. };
  33289. if (instance.rotationQuaternion) {
  33290. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33291. }
  33292. else if (instance.rotation) {
  33293. serializationInstance.rotation = instance.rotation.asArray();
  33294. }
  33295. serializationObject.instances.push(serializationInstance);
  33296. // Animations
  33297. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33298. serializationInstance.ranges = instance.serializeAnimationRanges();
  33299. }
  33300. //
  33301. // Animations
  33302. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33303. serializationObject.ranges = this.serializeAnimationRanges();
  33304. // Layer mask
  33305. serializationObject.layerMask = this.layerMask;
  33306. // Alpha
  33307. serializationObject.alphaIndex = this.alphaIndex;
  33308. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33309. // Overlay
  33310. serializationObject.overlayAlpha = this.overlayAlpha;
  33311. serializationObject.overlayColor = this.overlayColor.asArray();
  33312. serializationObject.renderOverlay = this.renderOverlay;
  33313. // Fog
  33314. serializationObject.applyFog = this.applyFog;
  33315. // Action Manager
  33316. if (this.actionManager) {
  33317. serializationObject.actions = this.actionManager.serialize(this.name);
  33318. }
  33319. };
  33320. /** @hidden */
  33321. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33322. if (!this.geometry) {
  33323. return;
  33324. }
  33325. this._markSubMeshesAsAttributesDirty();
  33326. var morphTargetManager = this._morphTargetManager;
  33327. if (morphTargetManager && morphTargetManager.vertexCount) {
  33328. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33329. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33330. this.morphTargetManager = null;
  33331. return;
  33332. }
  33333. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33334. var morphTarget = morphTargetManager.getActiveTarget(index);
  33335. var positions = morphTarget.getPositions();
  33336. if (!positions) {
  33337. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33338. return;
  33339. }
  33340. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33341. var normals = morphTarget.getNormals();
  33342. if (normals) {
  33343. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33344. }
  33345. var tangents = morphTarget.getTangents();
  33346. if (tangents) {
  33347. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33348. }
  33349. }
  33350. }
  33351. else {
  33352. var index = 0;
  33353. // Positions
  33354. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33355. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33356. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33357. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33358. }
  33359. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33360. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33361. }
  33362. index++;
  33363. }
  33364. }
  33365. };
  33366. // Statics
  33367. /**
  33368. * Returns a new Mesh object parsed from the source provided.
  33369. * The parameter `parsedMesh` is the source.
  33370. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33371. */
  33372. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33373. var mesh;
  33374. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33375. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33376. }
  33377. else {
  33378. mesh = new Mesh(parsedMesh.name, scene);
  33379. }
  33380. mesh.id = parsedMesh.id;
  33381. if (BABYLON.Tags) {
  33382. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33383. }
  33384. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33385. if (parsedMesh.metadata !== undefined) {
  33386. mesh.metadata = parsedMesh.metadata;
  33387. }
  33388. if (parsedMesh.rotationQuaternion) {
  33389. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33390. }
  33391. else if (parsedMesh.rotation) {
  33392. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33393. }
  33394. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33395. if (parsedMesh.localMatrix) {
  33396. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33397. }
  33398. else if (parsedMesh.pivotMatrix) {
  33399. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33400. }
  33401. mesh.setEnabled(parsedMesh.isEnabled);
  33402. mesh.isVisible = parsedMesh.isVisible;
  33403. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33404. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33405. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33406. if (parsedMesh.applyFog !== undefined) {
  33407. mesh.applyFog = parsedMesh.applyFog;
  33408. }
  33409. if (parsedMesh.pickable !== undefined) {
  33410. mesh.isPickable = parsedMesh.pickable;
  33411. }
  33412. if (parsedMesh.alphaIndex !== undefined) {
  33413. mesh.alphaIndex = parsedMesh.alphaIndex;
  33414. }
  33415. mesh.receiveShadows = parsedMesh.receiveShadows;
  33416. mesh.billboardMode = parsedMesh.billboardMode;
  33417. if (parsedMesh.visibility !== undefined) {
  33418. mesh.visibility = parsedMesh.visibility;
  33419. }
  33420. mesh.checkCollisions = parsedMesh.checkCollisions;
  33421. if (parsedMesh.isBlocker !== undefined) {
  33422. mesh.isBlocker = parsedMesh.isBlocker;
  33423. }
  33424. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33425. // freezeWorldMatrix
  33426. if (parsedMesh.freezeWorldMatrix) {
  33427. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33428. }
  33429. // Parent
  33430. if (parsedMesh.parentId) {
  33431. mesh._waitingParentId = parsedMesh.parentId;
  33432. }
  33433. // Actions
  33434. if (parsedMesh.actions !== undefined) {
  33435. mesh._waitingActions = parsedMesh.actions;
  33436. }
  33437. // Overlay
  33438. if (parsedMesh.overlayAlpha !== undefined) {
  33439. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33440. }
  33441. if (parsedMesh.overlayColor !== undefined) {
  33442. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33443. }
  33444. if (parsedMesh.renderOverlay !== undefined) {
  33445. mesh.renderOverlay = parsedMesh.renderOverlay;
  33446. }
  33447. // Geometry
  33448. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33449. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33450. if (parsedMesh.delayLoadingFile) {
  33451. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33452. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33453. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33454. if (parsedMesh._binaryInfo) {
  33455. mesh._binaryInfo = parsedMesh._binaryInfo;
  33456. }
  33457. mesh._delayInfo = [];
  33458. if (parsedMesh.hasUVs) {
  33459. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33460. }
  33461. if (parsedMesh.hasUVs2) {
  33462. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33463. }
  33464. if (parsedMesh.hasUVs3) {
  33465. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33466. }
  33467. if (parsedMesh.hasUVs4) {
  33468. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33469. }
  33470. if (parsedMesh.hasUVs5) {
  33471. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33472. }
  33473. if (parsedMesh.hasUVs6) {
  33474. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33475. }
  33476. if (parsedMesh.hasColors) {
  33477. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33478. }
  33479. if (parsedMesh.hasMatricesIndices) {
  33480. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33481. }
  33482. if (parsedMesh.hasMatricesWeights) {
  33483. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33484. }
  33485. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33486. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33487. mesh._checkDelayState();
  33488. }
  33489. }
  33490. else {
  33491. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33492. }
  33493. // Material
  33494. if (parsedMesh.materialId) {
  33495. mesh.setMaterialByID(parsedMesh.materialId);
  33496. }
  33497. else {
  33498. mesh.material = null;
  33499. }
  33500. // Morph targets
  33501. if (parsedMesh.morphTargetManagerId > -1) {
  33502. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33503. }
  33504. // Skeleton
  33505. if (parsedMesh.skeletonId > -1) {
  33506. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33507. if (parsedMesh.numBoneInfluencers) {
  33508. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33509. }
  33510. }
  33511. // Animations
  33512. if (parsedMesh.animations) {
  33513. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33514. var parsedAnimation = parsedMesh.animations[animationIndex];
  33515. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33516. }
  33517. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33518. }
  33519. if (parsedMesh.autoAnimate) {
  33520. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33521. }
  33522. // Layer Mask
  33523. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33524. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33525. }
  33526. else {
  33527. mesh.layerMask = 0x0FFFFFFF;
  33528. }
  33529. // Physics
  33530. if (parsedMesh.physicsImpostor) {
  33531. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33532. mass: parsedMesh.physicsMass,
  33533. friction: parsedMesh.physicsFriction,
  33534. restitution: parsedMesh.physicsRestitution
  33535. }, scene);
  33536. }
  33537. // Instances
  33538. if (parsedMesh.instances) {
  33539. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33540. var parsedInstance = parsedMesh.instances[index];
  33541. var instance = mesh.createInstance(parsedInstance.name);
  33542. if (parsedInstance.id) {
  33543. instance.id = parsedInstance.id;
  33544. }
  33545. if (BABYLON.Tags) {
  33546. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33547. }
  33548. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33549. if (parsedInstance.parentId) {
  33550. instance._waitingParentId = parsedInstance.parentId;
  33551. }
  33552. if (parsedInstance.rotationQuaternion) {
  33553. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33554. }
  33555. else if (parsedInstance.rotation) {
  33556. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33557. }
  33558. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33559. instance.checkCollisions = mesh.checkCollisions;
  33560. if (parsedMesh.animations) {
  33561. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33562. parsedAnimation = parsedMesh.animations[animationIndex];
  33563. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33564. }
  33565. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33566. if (parsedMesh.autoAnimate) {
  33567. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33568. }
  33569. }
  33570. }
  33571. }
  33572. return mesh;
  33573. };
  33574. /**
  33575. * Creates a ribbon mesh.
  33576. * Please consider using the same method from the MeshBuilder class instead.
  33577. * The ribbon is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33578. *
  33579. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33580. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33581. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33582. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33583. * 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.
  33584. * 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.
  33585. * 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
  33586. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33587. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33588. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33589. */
  33590. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33591. if (closeArray === void 0) { closeArray = false; }
  33592. if (updatable === void 0) { updatable = false; }
  33593. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33594. pathArray: pathArray,
  33595. closeArray: closeArray,
  33596. closePath: closePath,
  33597. offset: offset,
  33598. updatable: updatable,
  33599. sideOrientation: sideOrientation,
  33600. instance: instance
  33601. }, scene);
  33602. };
  33603. /**
  33604. * Creates a plane polygonal mesh. By default, this is a disc.
  33605. * Please consider using the same method from the MeshBuilder class instead.
  33606. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33607. * 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.
  33608. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33609. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33610. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33611. */
  33612. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33613. if (scene === void 0) { scene = null; }
  33614. var options = {
  33615. radius: radius,
  33616. tessellation: tessellation,
  33617. sideOrientation: sideOrientation,
  33618. updatable: updatable
  33619. };
  33620. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33621. };
  33622. /**
  33623. * Creates a box mesh.
  33624. * Please consider using the same method from the MeshBuilder class instead.
  33625. * The parameter `size` sets the size (float) of each box side (default 1).
  33626. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33627. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33628. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33629. */
  33630. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33631. if (scene === void 0) { scene = null; }
  33632. var options = {
  33633. size: size,
  33634. sideOrientation: sideOrientation,
  33635. updatable: updatable
  33636. };
  33637. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33638. };
  33639. /**
  33640. * Creates a sphere mesh.
  33641. * Please consider using the same method from the MeshBuilder class instead.
  33642. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33643. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33644. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33645. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  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.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33649. var options = {
  33650. segments: segments,
  33651. diameterX: diameter,
  33652. diameterY: diameter,
  33653. diameterZ: diameter,
  33654. sideOrientation: sideOrientation,
  33655. updatable: updatable
  33656. };
  33657. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33658. };
  33659. /**
  33660. * Creates a cylinder or a cone mesh.
  33661. * Please consider using the same method from the MeshBuilder class instead.
  33662. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33663. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33664. * 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.
  33665. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33666. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33667. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33668. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33669. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33670. */
  33671. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33672. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33673. if (scene !== undefined) {
  33674. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33675. updatable = scene;
  33676. }
  33677. scene = subdivisions;
  33678. subdivisions = 1;
  33679. }
  33680. var options = {
  33681. height: height,
  33682. diameterTop: diameterTop,
  33683. diameterBottom: diameterBottom,
  33684. tessellation: tessellation,
  33685. subdivisions: subdivisions,
  33686. sideOrientation: sideOrientation,
  33687. updatable: updatable
  33688. };
  33689. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33690. };
  33691. // Torus (Code from SharpDX.org)
  33692. /**
  33693. * Creates a torus mesh.
  33694. * Please consider using the same method from the MeshBuilder class instead.
  33695. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33696. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33697. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33698. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33699. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33700. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33701. */
  33702. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33703. var options = {
  33704. diameter: diameter,
  33705. thickness: thickness,
  33706. tessellation: tessellation,
  33707. sideOrientation: sideOrientation,
  33708. updatable: updatable
  33709. };
  33710. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33711. };
  33712. /**
  33713. * Creates a torus knot mesh.
  33714. * Please consider using the same method from the MeshBuilder class instead.
  33715. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33716. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33717. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33718. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33719. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33720. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33721. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33722. */
  33723. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33724. var options = {
  33725. radius: radius,
  33726. tube: tube,
  33727. radialSegments: radialSegments,
  33728. tubularSegments: tubularSegments,
  33729. p: p,
  33730. q: q,
  33731. sideOrientation: sideOrientation,
  33732. updatable: updatable
  33733. };
  33734. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33735. };
  33736. /**
  33737. * Creates a line mesh.
  33738. * Please consider using the same method from the MeshBuilder class instead.
  33739. * 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.
  33740. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33741. * The parameter `points` is an array successive Vector3.
  33742. * 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
  33743. * When updating an instance, remember that only point positions can change, not the number of points.
  33744. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33745. */
  33746. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33747. if (scene === void 0) { scene = null; }
  33748. if (updatable === void 0) { updatable = false; }
  33749. if (instance === void 0) { instance = null; }
  33750. var options = {
  33751. points: points,
  33752. updatable: updatable,
  33753. instance: instance
  33754. };
  33755. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33756. };
  33757. /**
  33758. * Creates a dashed line mesh.
  33759. * Please consider using the same method from the MeshBuilder class instead.
  33760. * 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.
  33761. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33762. * The parameter `points` is an array successive Vector3.
  33763. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33764. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33765. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33766. * 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
  33767. * When updating an instance, remember that only point positions can change, not the number of points.
  33768. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33769. */
  33770. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33771. if (scene === void 0) { scene = null; }
  33772. var options = {
  33773. points: points,
  33774. dashSize: dashSize,
  33775. gapSize: gapSize,
  33776. dashNb: dashNb,
  33777. updatable: updatable,
  33778. instance: instance
  33779. };
  33780. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33781. };
  33782. /**
  33783. * Creates a polygon mesh.
  33784. * Please consider using the same method from the MeshBuilder class instead.
  33785. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33786. * 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.
  33787. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33788. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33789. * Remember you can only change the shape positions, not their number when updating a polygon.
  33790. */
  33791. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33792. var options = {
  33793. shape: shape,
  33794. holes: holes,
  33795. updatable: updatable,
  33796. sideOrientation: sideOrientation
  33797. };
  33798. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33799. };
  33800. /**
  33801. * Creates an extruded polygon mesh, with depth in the Y direction.
  33802. * Please consider using the same method from the MeshBuilder class instead.
  33803. */
  33804. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33805. var options = {
  33806. shape: shape,
  33807. holes: holes,
  33808. depth: depth,
  33809. updatable: updatable,
  33810. sideOrientation: sideOrientation
  33811. };
  33812. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33813. };
  33814. /**
  33815. * Creates an extruded shape mesh.
  33816. * The extrusion is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33817. * Please consider using the same method from the MeshBuilder class instead.
  33818. *
  33819. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33820. * 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
  33821. * extruded along the Z axis.
  33822. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33823. * 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.
  33824. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33825. * 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
  33826. * 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
  33827. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33828. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33829. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33830. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33831. */
  33832. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33833. if (scene === void 0) { scene = null; }
  33834. var options = {
  33835. shape: shape,
  33836. path: path,
  33837. scale: scale,
  33838. rotation: rotation,
  33839. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33840. sideOrientation: sideOrientation,
  33841. instance: instance,
  33842. updatable: updatable
  33843. };
  33844. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33845. };
  33846. /**
  33847. * Creates an custom extruded shape mesh.
  33848. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33849. * Please consider using the same method from the MeshBuilder class instead.
  33850. *
  33851. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33852. * 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
  33853. * extruded along the Z axis.
  33854. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33855. * 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
  33856. * and the distance of this point from the begining of the path :
  33857. * ```javascript
  33858. * var rotationFunction = function(i, distance) {
  33859. * // do things
  33860. * return rotationValue; }
  33861. * ```
  33862. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33863. * 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
  33864. * and the distance of this point from the begining of the path :
  33865. * ```javascript
  33866. * var scaleFunction = function(i, distance) {
  33867. * // do things
  33868. * return scaleValue;}
  33869. * ```
  33870. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33871. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33872. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33873. * 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
  33874. * 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
  33875. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33876. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33877. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33878. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33879. */
  33880. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33881. var options = {
  33882. shape: shape,
  33883. path: path,
  33884. scaleFunction: scaleFunction,
  33885. rotationFunction: rotationFunction,
  33886. ribbonCloseArray: ribbonCloseArray,
  33887. ribbonClosePath: ribbonClosePath,
  33888. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33889. sideOrientation: sideOrientation,
  33890. instance: instance,
  33891. updatable: updatable
  33892. };
  33893. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33894. };
  33895. /**
  33896. * Creates lathe mesh.
  33897. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33898. * Please consider using the same method from the MeshBuilder class instead.
  33899. * 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
  33900. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33901. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33902. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33903. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33904. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33905. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33906. */
  33907. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33908. var options = {
  33909. shape: shape,
  33910. radius: radius,
  33911. tessellation: tessellation,
  33912. sideOrientation: sideOrientation,
  33913. updatable: updatable
  33914. };
  33915. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33916. };
  33917. /**
  33918. * Creates a plane mesh.
  33919. * Please consider using the same method from the MeshBuilder class instead.
  33920. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33921. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33922. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33923. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33924. */
  33925. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33926. var options = {
  33927. size: size,
  33928. width: size,
  33929. height: size,
  33930. sideOrientation: sideOrientation,
  33931. updatable: updatable
  33932. };
  33933. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33934. };
  33935. /**
  33936. * Creates a ground mesh.
  33937. * Please consider using the same method from the MeshBuilder class instead.
  33938. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33939. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33940. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33941. */
  33942. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33943. var options = {
  33944. width: width,
  33945. height: height,
  33946. subdivisions: subdivisions,
  33947. updatable: updatable
  33948. };
  33949. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33950. };
  33951. /**
  33952. * Creates a tiled ground mesh.
  33953. * Please consider using the same method from the MeshBuilder class instead.
  33954. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33955. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33956. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33957. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33958. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33959. * numbers of subdivisions on the ground width and height of each tile.
  33960. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33961. */
  33962. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33963. var options = {
  33964. xmin: xmin,
  33965. zmin: zmin,
  33966. xmax: xmax,
  33967. zmax: zmax,
  33968. subdivisions: subdivisions,
  33969. precision: precision,
  33970. updatable: updatable
  33971. };
  33972. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33973. };
  33974. /**
  33975. * Creates a ground mesh from a height map.
  33976. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33977. * Please consider using the same method from the MeshBuilder class instead.
  33978. * The parameter `url` sets the URL of the height map image resource.
  33979. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33980. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33981. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33982. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33983. * 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).
  33984. * This function is passed the newly built mesh :
  33985. * ```javascript
  33986. * function(mesh) { // do things
  33987. * return; }
  33988. * ```
  33989. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33990. */
  33991. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33992. var options = {
  33993. width: width,
  33994. height: height,
  33995. subdivisions: subdivisions,
  33996. minHeight: minHeight,
  33997. maxHeight: maxHeight,
  33998. updatable: updatable,
  33999. onReady: onReady
  34000. };
  34001. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  34002. };
  34003. /**
  34004. * Creates a tube mesh.
  34005. * The tube is a parametric shape : http://doc.babylonjs.com/how_to/parametric_shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  34006. * Please consider using the same method from the MeshBuilder class instead.
  34007. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  34008. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  34009. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  34010. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  34011. * 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.
  34012. * It must return a radius value (positive float) :
  34013. * ```javascript
  34014. * var radiusFunction = function(i, distance) {
  34015. * // do things
  34016. * return radius; }
  34017. * ```
  34018. * 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
  34019. * 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
  34020. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34021. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34022. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34023. */
  34024. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  34025. var options = {
  34026. path: path,
  34027. radius: radius,
  34028. tessellation: tessellation,
  34029. radiusFunction: radiusFunction,
  34030. arc: 1,
  34031. cap: cap,
  34032. updatable: updatable,
  34033. sideOrientation: sideOrientation,
  34034. instance: instance
  34035. };
  34036. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  34037. };
  34038. /**
  34039. * Creates a polyhedron mesh.
  34040. * Please consider using the same method from the MeshBuilder class instead.
  34041. * 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
  34042. * to choose the wanted type.
  34043. * The parameter `size` (positive float, default 1) sets the polygon size.
  34044. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  34045. * 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`.
  34046. * 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
  34047. * 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)`).
  34048. * 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
  34049. * 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.
  34050. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34051. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34052. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34053. */
  34054. Mesh.CreatePolyhedron = function (name, options, scene) {
  34055. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  34056. };
  34057. /**
  34058. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  34059. * Please consider using the same method from the MeshBuilder class instead.
  34060. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  34061. * 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`).
  34062. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  34063. * 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.
  34064. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34065. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34066. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34067. */
  34068. Mesh.CreateIcoSphere = function (name, options, scene) {
  34069. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  34070. };
  34071. /**
  34072. * Creates a decal mesh.
  34073. * Please consider using the same method from the MeshBuilder class instead.
  34074. * 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.
  34075. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  34076. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  34077. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  34078. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  34079. */
  34080. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  34081. var options = {
  34082. position: position,
  34083. normal: normal,
  34084. size: size,
  34085. angle: angle
  34086. };
  34087. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  34088. };
  34089. // Skeletons
  34090. /**
  34091. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34092. */
  34093. Mesh.prototype.setPositionsForCPUSkinning = function () {
  34094. if (!this._sourcePositions) {
  34095. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34096. if (!source) {
  34097. return this._sourcePositions;
  34098. }
  34099. this._sourcePositions = new Float32Array(source);
  34100. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34101. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  34102. }
  34103. }
  34104. return this._sourcePositions;
  34105. };
  34106. /**
  34107. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34108. */
  34109. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34110. if (!this._sourceNormals) {
  34111. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34112. if (!source) {
  34113. return this._sourceNormals;
  34114. }
  34115. this._sourceNormals = new Float32Array(source);
  34116. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34117. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34118. }
  34119. }
  34120. return this._sourceNormals;
  34121. };
  34122. /**
  34123. * Updates the vertex buffer by applying transformation from the bones.
  34124. * Returns the Mesh.
  34125. *
  34126. * @param {skeleton} skeleton to apply
  34127. */
  34128. Mesh.prototype.applySkeleton = function (skeleton) {
  34129. if (!this.geometry) {
  34130. return this;
  34131. }
  34132. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  34133. return this;
  34134. }
  34135. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  34136. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34137. return this;
  34138. }
  34139. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34140. return this;
  34141. }
  34142. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34143. return this;
  34144. }
  34145. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34146. return this;
  34147. }
  34148. if (!this._sourcePositions) {
  34149. var submeshes = this.subMeshes.slice();
  34150. this.setPositionsForCPUSkinning();
  34151. this.subMeshes = submeshes;
  34152. }
  34153. if (!this._sourceNormals) {
  34154. this.setNormalsForCPUSkinning();
  34155. }
  34156. // positionsData checks for not being Float32Array will only pass at most once
  34157. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34158. if (!positionsData) {
  34159. return this;
  34160. }
  34161. if (!(positionsData instanceof Float32Array)) {
  34162. positionsData = new Float32Array(positionsData);
  34163. }
  34164. // normalsData checks for not being Float32Array will only pass at most once
  34165. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34166. if (!normalsData) {
  34167. return this;
  34168. }
  34169. if (!(normalsData instanceof Float32Array)) {
  34170. normalsData = new Float32Array(normalsData);
  34171. }
  34172. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34173. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34174. if (!matricesWeightsData || !matricesIndicesData) {
  34175. return this;
  34176. }
  34177. var needExtras = this.numBoneInfluencers > 4;
  34178. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34179. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34180. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34181. var tempVector3 = BABYLON.Vector3.Zero();
  34182. var finalMatrix = new BABYLON.Matrix();
  34183. var tempMatrix = new BABYLON.Matrix();
  34184. var matWeightIdx = 0;
  34185. var inf;
  34186. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34187. var weight;
  34188. for (inf = 0; inf < 4; inf++) {
  34189. weight = matricesWeightsData[matWeightIdx + inf];
  34190. if (weight > 0) {
  34191. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34192. finalMatrix.addToSelf(tempMatrix);
  34193. }
  34194. }
  34195. if (needExtras) {
  34196. for (inf = 0; inf < 4; inf++) {
  34197. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34198. if (weight > 0) {
  34199. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34200. finalMatrix.addToSelf(tempMatrix);
  34201. }
  34202. }
  34203. }
  34204. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34205. tempVector3.toArray(positionsData, index);
  34206. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34207. tempVector3.toArray(normalsData, index);
  34208. finalMatrix.reset();
  34209. }
  34210. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34211. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34212. return this;
  34213. };
  34214. // Tools
  34215. /**
  34216. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34217. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34218. */
  34219. Mesh.MinMax = function (meshes) {
  34220. var minVector = null;
  34221. var maxVector = null;
  34222. meshes.forEach(function (mesh, index, array) {
  34223. var boundingInfo = mesh.getBoundingInfo();
  34224. var boundingBox = boundingInfo.boundingBox;
  34225. if (!minVector || !maxVector) {
  34226. minVector = boundingBox.minimumWorld;
  34227. maxVector = boundingBox.maximumWorld;
  34228. }
  34229. else {
  34230. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34231. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34232. }
  34233. });
  34234. if (!minVector || !maxVector) {
  34235. return {
  34236. min: BABYLON.Vector3.Zero(),
  34237. max: BABYLON.Vector3.Zero()
  34238. };
  34239. }
  34240. return {
  34241. min: minVector,
  34242. max: maxVector
  34243. };
  34244. };
  34245. /**
  34246. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34247. */
  34248. Mesh.Center = function (meshesOrMinMaxVector) {
  34249. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34250. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34251. };
  34252. /**
  34253. * Merge the array of meshes into a single mesh for performance reasons.
  34254. * @param meshes - The vertices source. They should all be of the same material. Entries can empty
  34255. * @param disposeSource - When true (default), dispose of the vertices from the source meshes
  34256. * @param allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34257. * @param meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34258. * @param subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34259. */
  34260. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34261. if (disposeSource === void 0) { disposeSource = true; }
  34262. var index;
  34263. if (!allow32BitsIndices) {
  34264. var totalVertices = 0;
  34265. // Counting vertices
  34266. for (index = 0; index < meshes.length; index++) {
  34267. if (meshes[index]) {
  34268. totalVertices += meshes[index].getTotalVertices();
  34269. if (totalVertices > 65536) {
  34270. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34271. return null;
  34272. }
  34273. }
  34274. }
  34275. }
  34276. // Merge
  34277. var vertexData = null;
  34278. var otherVertexData;
  34279. var indiceArray = new Array();
  34280. var source = null;
  34281. for (index = 0; index < meshes.length; index++) {
  34282. if (meshes[index]) {
  34283. var wm = meshes[index].computeWorldMatrix(true);
  34284. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34285. otherVertexData.transform(wm);
  34286. if (vertexData) {
  34287. vertexData.merge(otherVertexData, allow32BitsIndices);
  34288. }
  34289. else {
  34290. vertexData = otherVertexData;
  34291. source = meshes[index];
  34292. }
  34293. if (subdivideWithSubMeshes) {
  34294. indiceArray.push(meshes[index].getTotalIndices());
  34295. }
  34296. }
  34297. }
  34298. source = source;
  34299. if (!meshSubclass) {
  34300. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34301. }
  34302. vertexData.applyToMesh(meshSubclass);
  34303. // Setting properties
  34304. meshSubclass.material = source.material;
  34305. meshSubclass.checkCollisions = source.checkCollisions;
  34306. // Cleaning
  34307. if (disposeSource) {
  34308. for (index = 0; index < meshes.length; index++) {
  34309. if (meshes[index]) {
  34310. meshes[index].dispose();
  34311. }
  34312. }
  34313. }
  34314. // Subdivide
  34315. if (subdivideWithSubMeshes) {
  34316. //-- removal of global submesh
  34317. meshSubclass.releaseSubMeshes();
  34318. index = 0;
  34319. var offset = 0;
  34320. //-- apply subdivision according to index table
  34321. while (index < indiceArray.length) {
  34322. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34323. offset += indiceArray[index];
  34324. index++;
  34325. }
  34326. }
  34327. return meshSubclass;
  34328. };
  34329. // Consts
  34330. Mesh._FRONTSIDE = 0;
  34331. Mesh._BACKSIDE = 1;
  34332. Mesh._DOUBLESIDE = 2;
  34333. Mesh._DEFAULTSIDE = 0;
  34334. Mesh._NO_CAP = 0;
  34335. Mesh._CAP_START = 1;
  34336. Mesh._CAP_END = 2;
  34337. Mesh._CAP_ALL = 3;
  34338. return Mesh;
  34339. }(BABYLON.AbstractMesh));
  34340. BABYLON.Mesh = Mesh;
  34341. })(BABYLON || (BABYLON = {}));
  34342. //# sourceMappingURL=babylon.mesh.js.map
  34343. var BABYLON;
  34344. (function (BABYLON) {
  34345. var BaseSubMesh = /** @class */ (function () {
  34346. function BaseSubMesh() {
  34347. }
  34348. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34349. get: function () {
  34350. return this._materialEffect;
  34351. },
  34352. enumerable: true,
  34353. configurable: true
  34354. });
  34355. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34356. if (defines === void 0) { defines = null; }
  34357. if (this._materialEffect === effect) {
  34358. if (!effect) {
  34359. this._materialDefines = null;
  34360. }
  34361. return;
  34362. }
  34363. this._materialDefines = defines;
  34364. this._materialEffect = effect;
  34365. };
  34366. return BaseSubMesh;
  34367. }());
  34368. BABYLON.BaseSubMesh = BaseSubMesh;
  34369. var SubMesh = /** @class */ (function (_super) {
  34370. __extends(SubMesh, _super);
  34371. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34372. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34373. var _this = _super.call(this) || this;
  34374. _this.materialIndex = materialIndex;
  34375. _this.verticesStart = verticesStart;
  34376. _this.verticesCount = verticesCount;
  34377. _this.indexStart = indexStart;
  34378. _this.indexCount = indexCount;
  34379. /** @hidden */
  34380. _this._renderId = 0;
  34381. _this._mesh = mesh;
  34382. _this._renderingMesh = renderingMesh || mesh;
  34383. mesh.subMeshes.push(_this);
  34384. _this._trianglePlanes = [];
  34385. _this._id = mesh.subMeshes.length - 1;
  34386. if (createBoundingBox) {
  34387. _this.refreshBoundingInfo();
  34388. mesh.computeWorldMatrix(true);
  34389. }
  34390. return _this;
  34391. }
  34392. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34393. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34394. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34395. };
  34396. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34397. get: function () {
  34398. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34399. },
  34400. enumerable: true,
  34401. configurable: true
  34402. });
  34403. /**
  34404. * Returns the submesh BoudingInfo object.
  34405. */
  34406. SubMesh.prototype.getBoundingInfo = function () {
  34407. if (this.IsGlobal) {
  34408. return this._mesh.getBoundingInfo();
  34409. }
  34410. return this._boundingInfo;
  34411. };
  34412. /**
  34413. * Sets the submesh BoundingInfo.
  34414. * Return the SubMesh.
  34415. */
  34416. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34417. this._boundingInfo = boundingInfo;
  34418. return this;
  34419. };
  34420. /**
  34421. * Returns the mesh of the current submesh.
  34422. */
  34423. SubMesh.prototype.getMesh = function () {
  34424. return this._mesh;
  34425. };
  34426. /**
  34427. * Returns the rendering mesh of the submesh.
  34428. */
  34429. SubMesh.prototype.getRenderingMesh = function () {
  34430. return this._renderingMesh;
  34431. };
  34432. /**
  34433. * Returns the submesh material.
  34434. */
  34435. SubMesh.prototype.getMaterial = function () {
  34436. var rootMaterial = this._renderingMesh.material;
  34437. if (rootMaterial === null || rootMaterial === undefined) {
  34438. return this._mesh.getScene().defaultMaterial;
  34439. }
  34440. else if (rootMaterial.getSubMaterial) {
  34441. var multiMaterial = rootMaterial;
  34442. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34443. if (this._currentMaterial !== effectiveMaterial) {
  34444. this._currentMaterial = effectiveMaterial;
  34445. this._materialDefines = null;
  34446. }
  34447. return effectiveMaterial;
  34448. }
  34449. return rootMaterial;
  34450. };
  34451. // Methods
  34452. /**
  34453. * Sets a new updated BoundingInfo object to the submesh.
  34454. * Returns the SubMesh.
  34455. */
  34456. SubMesh.prototype.refreshBoundingInfo = function () {
  34457. this._lastColliderWorldVertices = null;
  34458. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34459. return this;
  34460. }
  34461. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34462. if (!data) {
  34463. this._boundingInfo = this._mesh.getBoundingInfo();
  34464. return this;
  34465. }
  34466. var indices = this._renderingMesh.getIndices();
  34467. var extend;
  34468. //is this the only submesh?
  34469. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34470. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34471. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34472. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34473. }
  34474. else {
  34475. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34476. }
  34477. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34478. return this;
  34479. };
  34480. /** @hidden */
  34481. SubMesh.prototype._checkCollision = function (collider) {
  34482. var boundingInfo = this.getBoundingInfo();
  34483. return boundingInfo._checkCollision(collider);
  34484. };
  34485. /**
  34486. * Updates the submesh BoundingInfo.
  34487. * Returns the Submesh.
  34488. */
  34489. SubMesh.prototype.updateBoundingInfo = function (world) {
  34490. var boundingInfo = this.getBoundingInfo();
  34491. if (!boundingInfo) {
  34492. this.refreshBoundingInfo();
  34493. boundingInfo = this.getBoundingInfo();
  34494. }
  34495. boundingInfo.update(world);
  34496. return this;
  34497. };
  34498. /**
  34499. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34500. * Boolean returned.
  34501. */
  34502. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34503. var boundingInfo = this.getBoundingInfo();
  34504. if (!boundingInfo) {
  34505. return false;
  34506. }
  34507. return boundingInfo.isInFrustum(frustumPlanes);
  34508. };
  34509. /**
  34510. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34511. * Boolean returned.
  34512. */
  34513. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34514. var boundingInfo = this.getBoundingInfo();
  34515. if (!boundingInfo) {
  34516. return false;
  34517. }
  34518. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34519. };
  34520. /**
  34521. * Renders the submesh.
  34522. * Returns it.
  34523. */
  34524. SubMesh.prototype.render = function (enableAlphaMode) {
  34525. this._renderingMesh.render(this, enableAlphaMode);
  34526. return this;
  34527. };
  34528. /**
  34529. * Returns a new Index Buffer.
  34530. * Type returned : WebGLBuffer.
  34531. */
  34532. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34533. if (!this._linesIndexBuffer) {
  34534. var linesIndices = [];
  34535. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34536. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34537. }
  34538. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34539. this.linesIndexCount = linesIndices.length;
  34540. }
  34541. return this._linesIndexBuffer;
  34542. };
  34543. /**
  34544. * True is the passed Ray intersects the submesh bounding box.
  34545. * Boolean returned.
  34546. */
  34547. SubMesh.prototype.canIntersects = function (ray) {
  34548. var boundingInfo = this.getBoundingInfo();
  34549. if (!boundingInfo) {
  34550. return false;
  34551. }
  34552. return ray.intersectsBox(boundingInfo.boundingBox);
  34553. };
  34554. /**
  34555. * Returns an object IntersectionInfo.
  34556. */
  34557. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34558. var intersectInfo = null;
  34559. var material = this.getMaterial();
  34560. if (!material) {
  34561. return null;
  34562. }
  34563. switch (material.fillMode) {
  34564. case BABYLON.Material.PointListDrawMode:
  34565. case BABYLON.Material.LineListDrawMode:
  34566. case BABYLON.Material.LineLoopDrawMode:
  34567. case BABYLON.Material.LineStripDrawMode:
  34568. case BABYLON.Material.TriangleFanDrawMode:
  34569. case BABYLON.Material.TriangleStripDrawMode:
  34570. return null;
  34571. }
  34572. // LineMesh first as it's also a Mesh...
  34573. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34574. var lineMesh = this._mesh;
  34575. // Line test
  34576. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34577. var p0 = positions[indices[index]];
  34578. var p1 = positions[indices[index + 1]];
  34579. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34580. if (length < 0) {
  34581. continue;
  34582. }
  34583. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34584. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34585. if (fastCheck) {
  34586. break;
  34587. }
  34588. }
  34589. }
  34590. }
  34591. else {
  34592. // Triangles test
  34593. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34594. var p0 = positions[indices[index]];
  34595. var p1 = positions[indices[index + 1]];
  34596. var p2 = positions[indices[index + 2]];
  34597. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34598. if (currentIntersectInfo) {
  34599. if (currentIntersectInfo.distance < 0) {
  34600. continue;
  34601. }
  34602. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34603. intersectInfo = currentIntersectInfo;
  34604. intersectInfo.faceId = index / 3;
  34605. if (fastCheck) {
  34606. break;
  34607. }
  34608. }
  34609. }
  34610. }
  34611. }
  34612. return intersectInfo;
  34613. };
  34614. /** @hidden */
  34615. SubMesh.prototype._rebuild = function () {
  34616. if (this._linesIndexBuffer) {
  34617. this._linesIndexBuffer = null;
  34618. }
  34619. };
  34620. // Clone
  34621. /**
  34622. * Creates a new Submesh from the passed Mesh.
  34623. */
  34624. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34625. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34626. if (!this.IsGlobal) {
  34627. var boundingInfo = this.getBoundingInfo();
  34628. if (!boundingInfo) {
  34629. return result;
  34630. }
  34631. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34632. }
  34633. return result;
  34634. };
  34635. // Dispose
  34636. /**
  34637. * Disposes the Submesh.
  34638. * Returns nothing.
  34639. */
  34640. SubMesh.prototype.dispose = function () {
  34641. if (this._linesIndexBuffer) {
  34642. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34643. this._linesIndexBuffer = null;
  34644. }
  34645. // Remove from mesh
  34646. var index = this._mesh.subMeshes.indexOf(this);
  34647. this._mesh.subMeshes.splice(index, 1);
  34648. };
  34649. // Statics
  34650. /**
  34651. * Creates a new Submesh from the passed parameters :
  34652. * - materialIndex (integer) : the index of the main mesh material.
  34653. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34654. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34655. * - mesh (Mesh) : the main mesh to create the submesh from.
  34656. * - renderingMesh (optional Mesh) : rendering mesh.
  34657. */
  34658. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34659. var minVertexIndex = Number.MAX_VALUE;
  34660. var maxVertexIndex = -Number.MAX_VALUE;
  34661. renderingMesh = (renderingMesh || mesh);
  34662. var indices = renderingMesh.getIndices();
  34663. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34664. var vertexIndex = indices[index];
  34665. if (vertexIndex < minVertexIndex)
  34666. minVertexIndex = vertexIndex;
  34667. if (vertexIndex > maxVertexIndex)
  34668. maxVertexIndex = vertexIndex;
  34669. }
  34670. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34671. };
  34672. return SubMesh;
  34673. }(BaseSubMesh));
  34674. BABYLON.SubMesh = SubMesh;
  34675. })(BABYLON || (BABYLON = {}));
  34676. //# sourceMappingURL=babylon.subMesh.js.map
  34677. var __assign = (this && this.__assign) || function () {
  34678. __assign = Object.assign || function(t) {
  34679. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34680. s = arguments[i];
  34681. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34682. t[p] = s[p];
  34683. }
  34684. return t;
  34685. };
  34686. return __assign.apply(this, arguments);
  34687. };
  34688. var BABYLON;
  34689. (function (BABYLON) {
  34690. /**
  34691. * Manages the defines for the Material
  34692. */
  34693. var MaterialDefines = /** @class */ (function () {
  34694. function MaterialDefines() {
  34695. this._isDirty = true;
  34696. /** @hidden */
  34697. this._areLightsDirty = true;
  34698. /** @hidden */
  34699. this._areAttributesDirty = true;
  34700. /** @hidden */
  34701. this._areTexturesDirty = true;
  34702. /** @hidden */
  34703. this._areFresnelDirty = true;
  34704. /** @hidden */
  34705. this._areMiscDirty = true;
  34706. /** @hidden */
  34707. this._areImageProcessingDirty = true;
  34708. /** @hidden */
  34709. this._normals = false;
  34710. /** @hidden */
  34711. this._uvs = false;
  34712. /** @hidden */
  34713. this._needNormals = false;
  34714. /** @hidden */
  34715. this._needUVs = false;
  34716. }
  34717. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34718. /**
  34719. * Specifies if the material needs to be re-calculated
  34720. */
  34721. get: function () {
  34722. return this._isDirty;
  34723. },
  34724. enumerable: true,
  34725. configurable: true
  34726. });
  34727. /**
  34728. * Marks the material to indicate that it has been re-calculated
  34729. */
  34730. MaterialDefines.prototype.markAsProcessed = function () {
  34731. this._isDirty = false;
  34732. this._areAttributesDirty = false;
  34733. this._areTexturesDirty = false;
  34734. this._areFresnelDirty = false;
  34735. this._areLightsDirty = false;
  34736. this._areMiscDirty = false;
  34737. this._areImageProcessingDirty = false;
  34738. };
  34739. /**
  34740. * Marks the material to indicate that it needs to be re-calculated
  34741. */
  34742. MaterialDefines.prototype.markAsUnprocessed = function () {
  34743. this._isDirty = true;
  34744. };
  34745. /**
  34746. * Marks the material to indicate all of its defines need to be re-calculated
  34747. */
  34748. MaterialDefines.prototype.markAllAsDirty = function () {
  34749. this._areTexturesDirty = true;
  34750. this._areAttributesDirty = true;
  34751. this._areLightsDirty = true;
  34752. this._areFresnelDirty = true;
  34753. this._areMiscDirty = true;
  34754. this._areImageProcessingDirty = true;
  34755. this._isDirty = true;
  34756. };
  34757. /**
  34758. * Marks the material to indicate that image processing needs to be re-calculated
  34759. */
  34760. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34761. this._areImageProcessingDirty = true;
  34762. this._isDirty = true;
  34763. };
  34764. /**
  34765. * Marks the material to indicate the lights need to be re-calculated
  34766. */
  34767. MaterialDefines.prototype.markAsLightDirty = function () {
  34768. this._areLightsDirty = true;
  34769. this._isDirty = true;
  34770. };
  34771. /**
  34772. * Marks the attribute state as changed
  34773. */
  34774. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34775. this._areAttributesDirty = true;
  34776. this._isDirty = true;
  34777. };
  34778. /**
  34779. * Marks the texture state as changed
  34780. */
  34781. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34782. this._areTexturesDirty = true;
  34783. this._isDirty = true;
  34784. };
  34785. /**
  34786. * Marks the fresnel state as changed
  34787. */
  34788. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34789. this._areFresnelDirty = true;
  34790. this._isDirty = true;
  34791. };
  34792. /**
  34793. * Marks the misc state as changed
  34794. */
  34795. MaterialDefines.prototype.markAsMiscDirty = function () {
  34796. this._areMiscDirty = true;
  34797. this._isDirty = true;
  34798. };
  34799. /**
  34800. * Rebuilds the material defines
  34801. */
  34802. MaterialDefines.prototype.rebuild = function () {
  34803. if (this._keys) {
  34804. delete this._keys;
  34805. }
  34806. this._keys = [];
  34807. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34808. var key = _a[_i];
  34809. if (key[0] === "_") {
  34810. continue;
  34811. }
  34812. this._keys.push(key);
  34813. }
  34814. };
  34815. /**
  34816. * Specifies if two material defines are equal
  34817. * @param other - A material define instance to compare to
  34818. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34819. */
  34820. MaterialDefines.prototype.isEqual = function (other) {
  34821. if (this._keys.length !== other._keys.length) {
  34822. return false;
  34823. }
  34824. for (var index = 0; index < this._keys.length; index++) {
  34825. var prop = this._keys[index];
  34826. if (this[prop] !== other[prop]) {
  34827. return false;
  34828. }
  34829. }
  34830. return true;
  34831. };
  34832. /**
  34833. * Clones this instance's defines to another instance
  34834. * @param other - material defines to clone values to
  34835. */
  34836. MaterialDefines.prototype.cloneTo = function (other) {
  34837. if (this._keys.length !== other._keys.length) {
  34838. other._keys = this._keys.slice(0);
  34839. }
  34840. for (var index = 0; index < this._keys.length; index++) {
  34841. var prop = this._keys[index];
  34842. other[prop] = this[prop];
  34843. }
  34844. };
  34845. /**
  34846. * Resets the material define values
  34847. */
  34848. MaterialDefines.prototype.reset = function () {
  34849. for (var index = 0; index < this._keys.length; index++) {
  34850. var prop = this._keys[index];
  34851. var type = typeof this[prop];
  34852. switch (type) {
  34853. case "number":
  34854. this[prop] = 0;
  34855. break;
  34856. case "string":
  34857. this[prop] = "";
  34858. break;
  34859. default:
  34860. this[prop] = false;
  34861. break;
  34862. }
  34863. }
  34864. };
  34865. /**
  34866. * Converts the material define values to a string
  34867. * @returns - String of material define information
  34868. */
  34869. MaterialDefines.prototype.toString = function () {
  34870. var result = "";
  34871. for (var index = 0; index < this._keys.length; index++) {
  34872. var prop = this._keys[index];
  34873. var value = this[prop];
  34874. var type = typeof value;
  34875. switch (type) {
  34876. case "number":
  34877. case "string":
  34878. result += "#define " + prop + " " + value + "\n";
  34879. break;
  34880. default:
  34881. if (value) {
  34882. result += "#define " + prop + "\n";
  34883. }
  34884. break;
  34885. }
  34886. }
  34887. return result;
  34888. };
  34889. return MaterialDefines;
  34890. }());
  34891. BABYLON.MaterialDefines = MaterialDefines;
  34892. /**
  34893. * Base class for the main features of a material in Babylon.js
  34894. */
  34895. var Material = /** @class */ (function () {
  34896. /**
  34897. * Creates a material instance
  34898. * @param name defines the name of the material
  34899. * @param scene defines the scene to reference
  34900. * @param doNotAdd specifies if the material should be added to the scene
  34901. */
  34902. function Material(name, scene, doNotAdd) {
  34903. /**
  34904. * Specifies if the ready state should be checked on each call
  34905. */
  34906. this.checkReadyOnEveryCall = false;
  34907. /**
  34908. * Specifies if the ready state should be checked once
  34909. */
  34910. this.checkReadyOnlyOnce = false;
  34911. /**
  34912. * The state of the material
  34913. */
  34914. this.state = "";
  34915. /**
  34916. * The alpha value of the material
  34917. */
  34918. this._alpha = 1.0;
  34919. /**
  34920. * Specifies if back face culling is enabled
  34921. */
  34922. this._backFaceCulling = true;
  34923. /**
  34924. * Specifies if the material should be serialized
  34925. */
  34926. this.doNotSerialize = false;
  34927. /**
  34928. * Specifies if the effect should be stored on sub meshes
  34929. */
  34930. this.storeEffectOnSubMeshes = false;
  34931. /**
  34932. * An event triggered when the material is disposed
  34933. */
  34934. this.onDisposeObservable = new BABYLON.Observable();
  34935. /**
  34936. * Stores the value of the alpha mode
  34937. */
  34938. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34939. /**
  34940. * Stores the state of the need depth pre-pass value
  34941. */
  34942. this._needDepthPrePass = false;
  34943. /**
  34944. * Specifies if depth writing should be disabled
  34945. */
  34946. this.disableDepthWrite = false;
  34947. /**
  34948. * Specifies if depth writing should be forced
  34949. */
  34950. this.forceDepthWrite = false;
  34951. /**
  34952. * Specifies if there should be a separate pass for culling
  34953. */
  34954. this.separateCullingPass = false;
  34955. /**
  34956. * Stores the state specifing if fog should be enabled
  34957. */
  34958. this._fogEnabled = true;
  34959. /**
  34960. * Stores the size of points
  34961. */
  34962. this.pointSize = 1.0;
  34963. /**
  34964. * Stores the z offset value
  34965. */
  34966. this.zOffset = 0;
  34967. /**
  34968. * @hidden
  34969. * Specifies if the material was previously ready
  34970. */
  34971. this._wasPreviouslyReady = false;
  34972. /**
  34973. * Stores the fill mode state
  34974. */
  34975. this._fillMode = Material.TriangleFillMode;
  34976. this.name = name;
  34977. this.id = name || BABYLON.Tools.RandomId();
  34978. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34979. this.uniqueId = this._scene.getUniqueId();
  34980. if (this._scene.useRightHandedSystem) {
  34981. this.sideOrientation = Material.ClockWiseSideOrientation;
  34982. }
  34983. else {
  34984. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34985. }
  34986. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34987. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34988. if (!doNotAdd) {
  34989. this._scene.materials.push(this);
  34990. }
  34991. }
  34992. Object.defineProperty(Material, "TriangleFillMode", {
  34993. /**
  34994. * Returns the triangle fill mode
  34995. */
  34996. get: function () {
  34997. return Material._TriangleFillMode;
  34998. },
  34999. enumerable: true,
  35000. configurable: true
  35001. });
  35002. Object.defineProperty(Material, "WireFrameFillMode", {
  35003. /**
  35004. * Returns the wireframe mode
  35005. */
  35006. get: function () {
  35007. return Material._WireFrameFillMode;
  35008. },
  35009. enumerable: true,
  35010. configurable: true
  35011. });
  35012. Object.defineProperty(Material, "PointFillMode", {
  35013. /**
  35014. * Returns the point fill mode
  35015. */
  35016. get: function () {
  35017. return Material._PointFillMode;
  35018. },
  35019. enumerable: true,
  35020. configurable: true
  35021. });
  35022. Object.defineProperty(Material, "PointListDrawMode", {
  35023. /**
  35024. * Returns the point list draw mode
  35025. */
  35026. get: function () {
  35027. return Material._PointListDrawMode;
  35028. },
  35029. enumerable: true,
  35030. configurable: true
  35031. });
  35032. Object.defineProperty(Material, "LineListDrawMode", {
  35033. /**
  35034. * Returns the line list draw mode
  35035. */
  35036. get: function () {
  35037. return Material._LineListDrawMode;
  35038. },
  35039. enumerable: true,
  35040. configurable: true
  35041. });
  35042. Object.defineProperty(Material, "LineLoopDrawMode", {
  35043. /**
  35044. * Returns the line loop draw mode
  35045. */
  35046. get: function () {
  35047. return Material._LineLoopDrawMode;
  35048. },
  35049. enumerable: true,
  35050. configurable: true
  35051. });
  35052. Object.defineProperty(Material, "LineStripDrawMode", {
  35053. /**
  35054. * Returns the line strip draw mode
  35055. */
  35056. get: function () {
  35057. return Material._LineStripDrawMode;
  35058. },
  35059. enumerable: true,
  35060. configurable: true
  35061. });
  35062. Object.defineProperty(Material, "TriangleStripDrawMode", {
  35063. /**
  35064. * Returns the triangle strip draw mode
  35065. */
  35066. get: function () {
  35067. return Material._TriangleStripDrawMode;
  35068. },
  35069. enumerable: true,
  35070. configurable: true
  35071. });
  35072. Object.defineProperty(Material, "TriangleFanDrawMode", {
  35073. /**
  35074. * Returns the triangle fan draw mode
  35075. */
  35076. get: function () {
  35077. return Material._TriangleFanDrawMode;
  35078. },
  35079. enumerable: true,
  35080. configurable: true
  35081. });
  35082. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  35083. /**
  35084. * Returns the clock-wise side orientation
  35085. */
  35086. get: function () {
  35087. return Material._ClockWiseSideOrientation;
  35088. },
  35089. enumerable: true,
  35090. configurable: true
  35091. });
  35092. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  35093. /**
  35094. * Returns the counter clock-wise side orientation
  35095. */
  35096. get: function () {
  35097. return Material._CounterClockWiseSideOrientation;
  35098. },
  35099. enumerable: true,
  35100. configurable: true
  35101. });
  35102. Object.defineProperty(Material, "TextureDirtyFlag", {
  35103. /**
  35104. * Returns the dirty texture flag value
  35105. */
  35106. get: function () {
  35107. return Material._TextureDirtyFlag;
  35108. },
  35109. enumerable: true,
  35110. configurable: true
  35111. });
  35112. Object.defineProperty(Material, "LightDirtyFlag", {
  35113. /**
  35114. * Returns the dirty light flag value
  35115. */
  35116. get: function () {
  35117. return Material._LightDirtyFlag;
  35118. },
  35119. enumerable: true,
  35120. configurable: true
  35121. });
  35122. Object.defineProperty(Material, "FresnelDirtyFlag", {
  35123. /**
  35124. * Returns the dirty fresnel flag value
  35125. */
  35126. get: function () {
  35127. return Material._FresnelDirtyFlag;
  35128. },
  35129. enumerable: true,
  35130. configurable: true
  35131. });
  35132. Object.defineProperty(Material, "AttributesDirtyFlag", {
  35133. /**
  35134. * Returns the dirty attributes flag value
  35135. */
  35136. get: function () {
  35137. return Material._AttributesDirtyFlag;
  35138. },
  35139. enumerable: true,
  35140. configurable: true
  35141. });
  35142. Object.defineProperty(Material, "MiscDirtyFlag", {
  35143. /**
  35144. * Returns the dirty misc flag value
  35145. */
  35146. get: function () {
  35147. return Material._MiscDirtyFlag;
  35148. },
  35149. enumerable: true,
  35150. configurable: true
  35151. });
  35152. Object.defineProperty(Material.prototype, "alpha", {
  35153. /**
  35154. * Gets the alpha value of the material
  35155. */
  35156. get: function () {
  35157. return this._alpha;
  35158. },
  35159. /**
  35160. * Sets the alpha value of the material
  35161. */
  35162. set: function (value) {
  35163. if (this._alpha === value) {
  35164. return;
  35165. }
  35166. this._alpha = value;
  35167. this.markAsDirty(Material.MiscDirtyFlag);
  35168. },
  35169. enumerable: true,
  35170. configurable: true
  35171. });
  35172. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35173. /**
  35174. * Gets the back-face culling state
  35175. */
  35176. get: function () {
  35177. return this._backFaceCulling;
  35178. },
  35179. /**
  35180. * Sets the back-face culling state
  35181. */
  35182. set: function (value) {
  35183. if (this._backFaceCulling === value) {
  35184. return;
  35185. }
  35186. this._backFaceCulling = value;
  35187. this.markAsDirty(Material.TextureDirtyFlag);
  35188. },
  35189. enumerable: true,
  35190. configurable: true
  35191. });
  35192. Object.defineProperty(Material.prototype, "onDispose", {
  35193. /**
  35194. * Called during a dispose event
  35195. */
  35196. set: function (callback) {
  35197. if (this._onDisposeObserver) {
  35198. this.onDisposeObservable.remove(this._onDisposeObserver);
  35199. }
  35200. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35201. },
  35202. enumerable: true,
  35203. configurable: true
  35204. });
  35205. Object.defineProperty(Material.prototype, "onBindObservable", {
  35206. /**
  35207. * An event triggered when the material is bound
  35208. */
  35209. get: function () {
  35210. if (!this._onBindObservable) {
  35211. this._onBindObservable = new BABYLON.Observable();
  35212. }
  35213. return this._onBindObservable;
  35214. },
  35215. enumerable: true,
  35216. configurable: true
  35217. });
  35218. Object.defineProperty(Material.prototype, "onBind", {
  35219. /**
  35220. * Called during a bind event
  35221. */
  35222. set: function (callback) {
  35223. if (this._onBindObserver) {
  35224. this.onBindObservable.remove(this._onBindObserver);
  35225. }
  35226. this._onBindObserver = this.onBindObservable.add(callback);
  35227. },
  35228. enumerable: true,
  35229. configurable: true
  35230. });
  35231. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  35232. /**
  35233. * An event triggered when the material is unbound
  35234. */
  35235. get: function () {
  35236. if (!this._onUnBindObservable) {
  35237. this._onUnBindObservable = new BABYLON.Observable();
  35238. }
  35239. return this._onUnBindObservable;
  35240. },
  35241. enumerable: true,
  35242. configurable: true
  35243. });
  35244. Object.defineProperty(Material.prototype, "alphaMode", {
  35245. /**
  35246. * Gets the value of the alpha mode
  35247. */
  35248. get: function () {
  35249. return this._alphaMode;
  35250. },
  35251. /**
  35252. * Sets the value of the alpha mode.
  35253. *
  35254. * | Value | Type | Description |
  35255. * | --- | --- | --- |
  35256. * | 0 | ALPHA_DISABLE | |
  35257. * | 1 | ALPHA_ADD | |
  35258. * | 2 | ALPHA_COMBINE | |
  35259. * | 3 | ALPHA_SUBTRACT | |
  35260. * | 4 | ALPHA_MULTIPLY | |
  35261. * | 5 | ALPHA_MAXIMIZED | |
  35262. * | 6 | ALPHA_ONEONE | |
  35263. * | 7 | ALPHA_PREMULTIPLIED | |
  35264. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35265. * | 9 | ALPHA_INTERPOLATE | |
  35266. * | 10 | ALPHA_SCREENMODE | |
  35267. *
  35268. */
  35269. set: function (value) {
  35270. if (this._alphaMode === value) {
  35271. return;
  35272. }
  35273. this._alphaMode = value;
  35274. this.markAsDirty(Material.TextureDirtyFlag);
  35275. },
  35276. enumerable: true,
  35277. configurable: true
  35278. });
  35279. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35280. /**
  35281. * Gets the depth pre-pass value
  35282. */
  35283. get: function () {
  35284. return this._needDepthPrePass;
  35285. },
  35286. /**
  35287. * Sets the need depth pre-pass value
  35288. */
  35289. set: function (value) {
  35290. if (this._needDepthPrePass === value) {
  35291. return;
  35292. }
  35293. this._needDepthPrePass = value;
  35294. if (this._needDepthPrePass) {
  35295. this.checkReadyOnEveryCall = true;
  35296. }
  35297. },
  35298. enumerable: true,
  35299. configurable: true
  35300. });
  35301. Object.defineProperty(Material.prototype, "fogEnabled", {
  35302. /**
  35303. * Gets the value of the fog enabled state
  35304. */
  35305. get: function () {
  35306. return this._fogEnabled;
  35307. },
  35308. /**
  35309. * Sets the state for enabling fog
  35310. */
  35311. set: function (value) {
  35312. if (this._fogEnabled === value) {
  35313. return;
  35314. }
  35315. this._fogEnabled = value;
  35316. this.markAsDirty(Material.MiscDirtyFlag);
  35317. },
  35318. enumerable: true,
  35319. configurable: true
  35320. });
  35321. Object.defineProperty(Material.prototype, "wireframe", {
  35322. /**
  35323. * Gets a value specifying if wireframe mode is enabled
  35324. */
  35325. get: function () {
  35326. switch (this._fillMode) {
  35327. case Material.WireFrameFillMode:
  35328. case Material.LineListDrawMode:
  35329. case Material.LineLoopDrawMode:
  35330. case Material.LineStripDrawMode:
  35331. return true;
  35332. }
  35333. return this._scene.forceWireframe;
  35334. },
  35335. /**
  35336. * Sets the state of wireframe mode
  35337. */
  35338. set: function (value) {
  35339. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35340. },
  35341. enumerable: true,
  35342. configurable: true
  35343. });
  35344. Object.defineProperty(Material.prototype, "pointsCloud", {
  35345. /**
  35346. * Gets the value specifying if point clouds are enabled
  35347. */
  35348. get: function () {
  35349. switch (this._fillMode) {
  35350. case Material.PointFillMode:
  35351. case Material.PointListDrawMode:
  35352. return true;
  35353. }
  35354. return this._scene.forcePointsCloud;
  35355. },
  35356. /**
  35357. * Sets the state of point cloud mode
  35358. */
  35359. set: function (value) {
  35360. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35361. },
  35362. enumerable: true,
  35363. configurable: true
  35364. });
  35365. Object.defineProperty(Material.prototype, "fillMode", {
  35366. /**
  35367. * Gets the material fill mode
  35368. */
  35369. get: function () {
  35370. return this._fillMode;
  35371. },
  35372. /**
  35373. * Sets the material fill mode
  35374. */
  35375. set: function (value) {
  35376. if (this._fillMode === value) {
  35377. return;
  35378. }
  35379. this._fillMode = value;
  35380. this.markAsDirty(Material.MiscDirtyFlag);
  35381. },
  35382. enumerable: true,
  35383. configurable: true
  35384. });
  35385. /**
  35386. * Returns a string representation of the current material
  35387. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35388. * @returns a string with material information
  35389. */
  35390. Material.prototype.toString = function (fullDetails) {
  35391. var ret = "Name: " + this.name;
  35392. if (fullDetails) {
  35393. }
  35394. return ret;
  35395. };
  35396. /**
  35397. * Gets the class name of the material
  35398. * @returns a string with the class name of the material
  35399. */
  35400. Material.prototype.getClassName = function () {
  35401. return "Material";
  35402. };
  35403. Object.defineProperty(Material.prototype, "isFrozen", {
  35404. /**
  35405. * Specifies if updates for the material been locked
  35406. */
  35407. get: function () {
  35408. return this.checkReadyOnlyOnce;
  35409. },
  35410. enumerable: true,
  35411. configurable: true
  35412. });
  35413. /**
  35414. * Locks updates for the material
  35415. */
  35416. Material.prototype.freeze = function () {
  35417. this.checkReadyOnlyOnce = true;
  35418. };
  35419. /**
  35420. * Unlocks updates for the material
  35421. */
  35422. Material.prototype.unfreeze = function () {
  35423. this.checkReadyOnlyOnce = false;
  35424. };
  35425. /**
  35426. * Specifies if the material is ready to be used
  35427. * @param mesh defines the mesh to check
  35428. * @param useInstances specifies if instances should be used
  35429. * @returns a boolean indicating if the material is ready to be used
  35430. */
  35431. Material.prototype.isReady = function (mesh, useInstances) {
  35432. return true;
  35433. };
  35434. /**
  35435. * Specifies that the submesh is ready to be used
  35436. * @param mesh defines the mesh to check
  35437. * @param subMesh defines which submesh to check
  35438. * @param useInstances specifies that instances should be used
  35439. * @returns a boolean indicating that the submesh is ready or not
  35440. */
  35441. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35442. return false;
  35443. };
  35444. /**
  35445. * Returns the material effect
  35446. * @returns the effect associated with the material
  35447. */
  35448. Material.prototype.getEffect = function () {
  35449. return this._effect;
  35450. };
  35451. /**
  35452. * Returns the current scene
  35453. * @returns a Scene
  35454. */
  35455. Material.prototype.getScene = function () {
  35456. return this._scene;
  35457. };
  35458. /**
  35459. * Specifies if the material will require alpha blending
  35460. * @returns a boolean specifying if alpha blending is needed
  35461. */
  35462. Material.prototype.needAlphaBlending = function () {
  35463. return (this.alpha < 1.0);
  35464. };
  35465. /**
  35466. * Specifies if the mesh will require alpha blending
  35467. * @param mesh defines the mesh to check
  35468. * @returns a boolean specifying if alpha blending is needed for the mesh
  35469. */
  35470. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35471. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35472. };
  35473. /**
  35474. * Specifies if this material should be rendered in alpha test mode
  35475. * @returns a boolean specifying if an alpha test is needed.
  35476. */
  35477. Material.prototype.needAlphaTesting = function () {
  35478. return false;
  35479. };
  35480. /**
  35481. * Gets the texture used for the alpha test
  35482. * @returns the texture to use for alpha testing
  35483. */
  35484. Material.prototype.getAlphaTestTexture = function () {
  35485. return null;
  35486. };
  35487. /**
  35488. * Marks the material to indicate that it needs to be re-calculated
  35489. */
  35490. Material.prototype.markDirty = function () {
  35491. this._wasPreviouslyReady = false;
  35492. };
  35493. /** @hidden */
  35494. Material.prototype._preBind = function (effect, overrideOrientation) {
  35495. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35496. var engine = this._scene.getEngine();
  35497. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35498. var reverse = orientation === Material.ClockWiseSideOrientation;
  35499. engine.enableEffect(effect ? effect : this._effect);
  35500. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35501. return reverse;
  35502. };
  35503. /**
  35504. * Binds the material to the mesh
  35505. * @param world defines the world transformation matrix
  35506. * @param mesh defines the mesh to bind the material to
  35507. */
  35508. Material.prototype.bind = function (world, mesh) {
  35509. };
  35510. /**
  35511. * Binds the submesh to the material
  35512. * @param world defines the world transformation matrix
  35513. * @param mesh defines the mesh containing the submesh
  35514. * @param subMesh defines the submesh to bind the material to
  35515. */
  35516. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35517. };
  35518. /**
  35519. * Binds the world matrix to the material
  35520. * @param world defines the world transformation matrix
  35521. */
  35522. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35523. };
  35524. /**
  35525. * Binds the scene's uniform buffer to the effect.
  35526. * @param effect defines the effect to bind to the scene uniform buffer
  35527. * @param sceneUbo defines the uniform buffer storing scene data
  35528. */
  35529. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35530. sceneUbo.bindToEffect(effect, "Scene");
  35531. };
  35532. /**
  35533. * Binds the view matrix to the effect
  35534. * @param effect defines the effect to bind the view matrix to
  35535. */
  35536. Material.prototype.bindView = function (effect) {
  35537. if (!this._useUBO) {
  35538. effect.setMatrix("view", this.getScene().getViewMatrix());
  35539. }
  35540. else {
  35541. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35542. }
  35543. };
  35544. /**
  35545. * Binds the view projection matrix to the effect
  35546. * @param effect defines the effect to bind the view projection matrix to
  35547. */
  35548. Material.prototype.bindViewProjection = function (effect) {
  35549. if (!this._useUBO) {
  35550. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35551. }
  35552. else {
  35553. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35554. }
  35555. };
  35556. /**
  35557. * Specifies if material alpha testing should be turned on for the mesh
  35558. * @param mesh defines the mesh to check
  35559. */
  35560. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35561. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35562. };
  35563. /**
  35564. * Processes to execute after binding the material to a mesh
  35565. * @param mesh defines the rendered mesh
  35566. */
  35567. Material.prototype._afterBind = function (mesh) {
  35568. this._scene._cachedMaterial = this;
  35569. if (mesh) {
  35570. this._scene._cachedVisibility = mesh.visibility;
  35571. }
  35572. else {
  35573. this._scene._cachedVisibility = 1;
  35574. }
  35575. if (this._onBindObservable && mesh) {
  35576. this._onBindObservable.notifyObservers(mesh);
  35577. }
  35578. if (this.disableDepthWrite) {
  35579. var engine = this._scene.getEngine();
  35580. this._cachedDepthWriteState = engine.getDepthWrite();
  35581. engine.setDepthWrite(false);
  35582. }
  35583. };
  35584. /**
  35585. * Unbinds the material from the mesh
  35586. */
  35587. Material.prototype.unbind = function () {
  35588. if (this._onUnBindObservable) {
  35589. this._onUnBindObservable.notifyObservers(this);
  35590. }
  35591. if (this.disableDepthWrite) {
  35592. var engine = this._scene.getEngine();
  35593. engine.setDepthWrite(this._cachedDepthWriteState);
  35594. }
  35595. };
  35596. /**
  35597. * Gets the active textures from the material
  35598. * @returns an array of textures
  35599. */
  35600. Material.prototype.getActiveTextures = function () {
  35601. return [];
  35602. };
  35603. /**
  35604. * Specifies if the material uses a texture
  35605. * @param texture defines the texture to check against the material
  35606. * @returns a boolean specifying if the material uses the texture
  35607. */
  35608. Material.prototype.hasTexture = function (texture) {
  35609. return false;
  35610. };
  35611. /**
  35612. * Makes a duplicate of the material, and gives it a new name
  35613. * @param name defines the new name for the duplicated material
  35614. * @returns the cloned material
  35615. */
  35616. Material.prototype.clone = function (name) {
  35617. return null;
  35618. };
  35619. /**
  35620. * Gets the meshes bound to the material
  35621. * @returns an array of meshes bound to the material
  35622. */
  35623. Material.prototype.getBindedMeshes = function () {
  35624. var result = new Array();
  35625. for (var index = 0; index < this._scene.meshes.length; index++) {
  35626. var mesh = this._scene.meshes[index];
  35627. if (mesh.material === this) {
  35628. result.push(mesh);
  35629. }
  35630. }
  35631. return result;
  35632. };
  35633. /**
  35634. * Force shader compilation
  35635. * @param mesh defines the mesh associated with this material
  35636. * @param onCompiled defines a function to execute once the material is compiled
  35637. * @param options defines the options to configure the compilation
  35638. */
  35639. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35640. var _this = this;
  35641. var localOptions = __assign({ clipPlane: false }, options);
  35642. var subMesh = new BABYLON.BaseSubMesh();
  35643. var scene = this.getScene();
  35644. var checkReady = function () {
  35645. if (!_this._scene || !_this._scene.getEngine()) {
  35646. return;
  35647. }
  35648. if (subMesh._materialDefines) {
  35649. subMesh._materialDefines._renderId = -1;
  35650. }
  35651. var clipPlaneState = scene.clipPlane;
  35652. if (localOptions.clipPlane) {
  35653. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35654. }
  35655. if (_this.storeEffectOnSubMeshes) {
  35656. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35657. if (onCompiled) {
  35658. onCompiled(_this);
  35659. }
  35660. }
  35661. else {
  35662. setTimeout(checkReady, 16);
  35663. }
  35664. }
  35665. else {
  35666. if (_this.isReady(mesh)) {
  35667. if (onCompiled) {
  35668. onCompiled(_this);
  35669. }
  35670. }
  35671. else {
  35672. setTimeout(checkReady, 16);
  35673. }
  35674. }
  35675. if (localOptions.clipPlane) {
  35676. scene.clipPlane = clipPlaneState;
  35677. }
  35678. };
  35679. checkReady();
  35680. };
  35681. /**
  35682. * Force shader compilation
  35683. * @param mesh defines the mesh that will use this material
  35684. * @param options defines additional options for compiling the shaders
  35685. * @returns a promise that resolves when the compilation completes
  35686. */
  35687. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35688. var _this = this;
  35689. return new Promise(function (resolve) {
  35690. _this.forceCompilation(mesh, function () {
  35691. resolve();
  35692. }, options);
  35693. });
  35694. };
  35695. /**
  35696. * Marks a define in the material to indicate that it needs to be re-computed
  35697. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35698. */
  35699. Material.prototype.markAsDirty = function (flag) {
  35700. if (flag & Material.TextureDirtyFlag) {
  35701. this._markAllSubMeshesAsTexturesDirty();
  35702. }
  35703. if (flag & Material.LightDirtyFlag) {
  35704. this._markAllSubMeshesAsLightsDirty();
  35705. }
  35706. if (flag & Material.FresnelDirtyFlag) {
  35707. this._markAllSubMeshesAsFresnelDirty();
  35708. }
  35709. if (flag & Material.AttributesDirtyFlag) {
  35710. this._markAllSubMeshesAsAttributesDirty();
  35711. }
  35712. if (flag & Material.MiscDirtyFlag) {
  35713. this._markAllSubMeshesAsMiscDirty();
  35714. }
  35715. this.getScene().resetCachedMaterial();
  35716. };
  35717. /**
  35718. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35719. * @param func defines a function which checks material defines against the submeshes
  35720. */
  35721. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35722. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35723. var mesh = _a[_i];
  35724. if (!mesh.subMeshes) {
  35725. continue;
  35726. }
  35727. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35728. var subMesh = _c[_b];
  35729. if (subMesh.getMaterial() !== this) {
  35730. continue;
  35731. }
  35732. if (!subMesh._materialDefines) {
  35733. continue;
  35734. }
  35735. func(subMesh._materialDefines);
  35736. }
  35737. }
  35738. };
  35739. /**
  35740. * Indicates that image processing needs to be re-calculated for all submeshes
  35741. */
  35742. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35743. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35744. };
  35745. /**
  35746. * Indicates that textures need to be re-calculated for all submeshes
  35747. */
  35748. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35749. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35750. };
  35751. /**
  35752. * Indicates that fresnel needs to be re-calculated for all submeshes
  35753. */
  35754. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35755. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35756. };
  35757. /**
  35758. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35759. */
  35760. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35761. this._markAllSubMeshesAsDirty(function (defines) {
  35762. defines.markAsFresnelDirty();
  35763. defines.markAsMiscDirty();
  35764. });
  35765. };
  35766. /**
  35767. * Indicates that lights need to be re-calculated for all submeshes
  35768. */
  35769. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35770. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35771. };
  35772. /**
  35773. * Indicates that attributes need to be re-calculated for all submeshes
  35774. */
  35775. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35776. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35777. };
  35778. /**
  35779. * Indicates that misc needs to be re-calculated for all submeshes
  35780. */
  35781. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35782. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35783. };
  35784. /**
  35785. * Indicates that textures and misc need to be re-calculated for all submeshes
  35786. */
  35787. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35788. this._markAllSubMeshesAsDirty(function (defines) {
  35789. defines.markAsTexturesDirty();
  35790. defines.markAsMiscDirty();
  35791. });
  35792. };
  35793. /**
  35794. * Disposes the material
  35795. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35796. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35797. */
  35798. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35799. // Animations
  35800. this.getScene().stopAnimation(this);
  35801. this.getScene().freeProcessedMaterials();
  35802. // Remove from scene
  35803. var index = this._scene.materials.indexOf(this);
  35804. if (index >= 0) {
  35805. this._scene.materials.splice(index, 1);
  35806. }
  35807. // Remove from meshes
  35808. for (index = 0; index < this._scene.meshes.length; index++) {
  35809. var mesh = this._scene.meshes[index];
  35810. if (mesh.material === this) {
  35811. mesh.material = null;
  35812. if (mesh.geometry) {
  35813. var geometry = (mesh.geometry);
  35814. if (this.storeEffectOnSubMeshes) {
  35815. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35816. var subMesh = _a[_i];
  35817. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35818. if (forceDisposeEffect && subMesh._materialEffect) {
  35819. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35820. }
  35821. }
  35822. }
  35823. else {
  35824. geometry._releaseVertexArrayObject(this._effect);
  35825. }
  35826. }
  35827. }
  35828. }
  35829. this._uniformBuffer.dispose();
  35830. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35831. if (forceDisposeEffect && this._effect) {
  35832. if (!this.storeEffectOnSubMeshes) {
  35833. this._scene.getEngine()._releaseEffect(this._effect);
  35834. }
  35835. this._effect = null;
  35836. }
  35837. // Callback
  35838. this.onDisposeObservable.notifyObservers(this);
  35839. this.onDisposeObservable.clear();
  35840. if (this._onBindObservable) {
  35841. this._onBindObservable.clear();
  35842. }
  35843. if (this._onUnBindObservable) {
  35844. this._onUnBindObservable.clear();
  35845. }
  35846. };
  35847. /**
  35848. * Serializes this material
  35849. * @returns the serialized material object
  35850. */
  35851. Material.prototype.serialize = function () {
  35852. return BABYLON.SerializationHelper.Serialize(this);
  35853. };
  35854. /**
  35855. * Creates a MultiMaterial from parsed MultiMaterial data.
  35856. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35857. * @param scene defines the hosting scene
  35858. * @returns a new MultiMaterial
  35859. */
  35860. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35861. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35862. multiMaterial.id = parsedMultiMaterial.id;
  35863. if (BABYLON.Tags) {
  35864. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35865. }
  35866. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35867. var subMatId = parsedMultiMaterial.materials[matIndex];
  35868. if (subMatId) {
  35869. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35870. }
  35871. else {
  35872. multiMaterial.subMaterials.push(null);
  35873. }
  35874. }
  35875. return multiMaterial;
  35876. };
  35877. /**
  35878. * Creates a material from parsed material data
  35879. * @param parsedMaterial defines parsed material data
  35880. * @param scene defines the hosting scene
  35881. * @param rootUrl defines the root URL to use to load textures
  35882. * @returns a new material
  35883. */
  35884. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35885. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35886. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35887. }
  35888. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35889. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35890. if (!BABYLON.LegacyPBRMaterial) {
  35891. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35892. return;
  35893. }
  35894. }
  35895. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35896. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35897. };
  35898. // Triangle views
  35899. Material._TriangleFillMode = 0;
  35900. Material._WireFrameFillMode = 1;
  35901. Material._PointFillMode = 2;
  35902. // Draw modes
  35903. Material._PointListDrawMode = 3;
  35904. Material._LineListDrawMode = 4;
  35905. Material._LineLoopDrawMode = 5;
  35906. Material._LineStripDrawMode = 6;
  35907. Material._TriangleStripDrawMode = 7;
  35908. Material._TriangleFanDrawMode = 8;
  35909. /**
  35910. * Stores the clock-wise side orientation
  35911. */
  35912. Material._ClockWiseSideOrientation = 0;
  35913. /**
  35914. * Stores the counter clock-wise side orientation
  35915. */
  35916. Material._CounterClockWiseSideOrientation = 1;
  35917. /**
  35918. * The dirty texture flag value
  35919. */
  35920. Material._TextureDirtyFlag = 1;
  35921. /**
  35922. * The dirty light flag value
  35923. */
  35924. Material._LightDirtyFlag = 2;
  35925. /**
  35926. * The dirty fresnel flag value
  35927. */
  35928. Material._FresnelDirtyFlag = 4;
  35929. /**
  35930. * The dirty attribute flag value
  35931. */
  35932. Material._AttributesDirtyFlag = 8;
  35933. /**
  35934. * The dirty misc flag value
  35935. */
  35936. Material._MiscDirtyFlag = 16;
  35937. __decorate([
  35938. BABYLON.serialize()
  35939. ], Material.prototype, "id", void 0);
  35940. __decorate([
  35941. BABYLON.serialize()
  35942. ], Material.prototype, "uniqueId", void 0);
  35943. __decorate([
  35944. BABYLON.serialize()
  35945. ], Material.prototype, "name", void 0);
  35946. __decorate([
  35947. BABYLON.serialize()
  35948. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35949. __decorate([
  35950. BABYLON.serialize()
  35951. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35952. __decorate([
  35953. BABYLON.serialize()
  35954. ], Material.prototype, "state", void 0);
  35955. __decorate([
  35956. BABYLON.serialize("alpha")
  35957. ], Material.prototype, "_alpha", void 0);
  35958. __decorate([
  35959. BABYLON.serialize("backFaceCulling")
  35960. ], Material.prototype, "_backFaceCulling", void 0);
  35961. __decorate([
  35962. BABYLON.serialize()
  35963. ], Material.prototype, "sideOrientation", void 0);
  35964. __decorate([
  35965. BABYLON.serialize("alphaMode")
  35966. ], Material.prototype, "_alphaMode", void 0);
  35967. __decorate([
  35968. BABYLON.serialize()
  35969. ], Material.prototype, "_needDepthPrePass", void 0);
  35970. __decorate([
  35971. BABYLON.serialize()
  35972. ], Material.prototype, "disableDepthWrite", void 0);
  35973. __decorate([
  35974. BABYLON.serialize()
  35975. ], Material.prototype, "forceDepthWrite", void 0);
  35976. __decorate([
  35977. BABYLON.serialize()
  35978. ], Material.prototype, "separateCullingPass", void 0);
  35979. __decorate([
  35980. BABYLON.serialize("fogEnabled")
  35981. ], Material.prototype, "_fogEnabled", void 0);
  35982. __decorate([
  35983. BABYLON.serialize()
  35984. ], Material.prototype, "pointSize", void 0);
  35985. __decorate([
  35986. BABYLON.serialize()
  35987. ], Material.prototype, "zOffset", void 0);
  35988. __decorate([
  35989. BABYLON.serialize()
  35990. ], Material.prototype, "wireframe", null);
  35991. __decorate([
  35992. BABYLON.serialize()
  35993. ], Material.prototype, "pointsCloud", null);
  35994. __decorate([
  35995. BABYLON.serialize()
  35996. ], Material.prototype, "fillMode", null);
  35997. return Material;
  35998. }());
  35999. BABYLON.Material = Material;
  36000. })(BABYLON || (BABYLON = {}));
  36001. //# sourceMappingURL=babylon.material.js.map
  36002. var BABYLON;
  36003. (function (BABYLON) {
  36004. var UniformBuffer = /** @class */ (function () {
  36005. /**
  36006. * Uniform buffer objects.
  36007. *
  36008. * Handles blocks of uniform on the GPU.
  36009. *
  36010. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  36011. *
  36012. * For more information, please refer to :
  36013. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  36014. */
  36015. function UniformBuffer(engine, data, dynamic) {
  36016. this._engine = engine;
  36017. this._noUBO = !engine.supportsUniformBuffers;
  36018. this._dynamic = dynamic;
  36019. this._data = data || [];
  36020. this._uniformLocations = {};
  36021. this._uniformSizes = {};
  36022. this._uniformLocationPointer = 0;
  36023. this._needSync = false;
  36024. if (this._noUBO) {
  36025. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  36026. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  36027. this.updateFloat = this._updateFloatForEffect;
  36028. this.updateFloat2 = this._updateFloat2ForEffect;
  36029. this.updateFloat3 = this._updateFloat3ForEffect;
  36030. this.updateFloat4 = this._updateFloat4ForEffect;
  36031. this.updateMatrix = this._updateMatrixForEffect;
  36032. this.updateVector3 = this._updateVector3ForEffect;
  36033. this.updateVector4 = this._updateVector4ForEffect;
  36034. this.updateColor3 = this._updateColor3ForEffect;
  36035. this.updateColor4 = this._updateColor4ForEffect;
  36036. }
  36037. else {
  36038. this._engine._uniformBuffers.push(this);
  36039. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  36040. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  36041. this.updateFloat = this._updateFloatForUniform;
  36042. this.updateFloat2 = this._updateFloat2ForUniform;
  36043. this.updateFloat3 = this._updateFloat3ForUniform;
  36044. this.updateFloat4 = this._updateFloat4ForUniform;
  36045. this.updateMatrix = this._updateMatrixForUniform;
  36046. this.updateVector3 = this._updateVector3ForUniform;
  36047. this.updateVector4 = this._updateVector4ForUniform;
  36048. this.updateColor3 = this._updateColor3ForUniform;
  36049. this.updateColor4 = this._updateColor4ForUniform;
  36050. }
  36051. }
  36052. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  36053. // Properties
  36054. /**
  36055. * Indicates if the buffer is using the WebGL2 UBO implementation,
  36056. * or just falling back on setUniformXXX calls.
  36057. */
  36058. get: function () {
  36059. return !this._noUBO;
  36060. },
  36061. enumerable: true,
  36062. configurable: true
  36063. });
  36064. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  36065. /**
  36066. * Indicates if the WebGL underlying uniform buffer is in sync
  36067. * with the javascript cache data.
  36068. */
  36069. get: function () {
  36070. return !this._needSync;
  36071. },
  36072. enumerable: true,
  36073. configurable: true
  36074. });
  36075. /**
  36076. * Indicates if the WebGL underlying uniform buffer is dynamic.
  36077. * Also, a dynamic UniformBuffer will disable cache verification and always
  36078. * update the underlying WebGL uniform buffer to the GPU.
  36079. */
  36080. UniformBuffer.prototype.isDynamic = function () {
  36081. return this._dynamic !== undefined;
  36082. };
  36083. /**
  36084. * The data cache on JS side.
  36085. */
  36086. UniformBuffer.prototype.getData = function () {
  36087. return this._bufferData;
  36088. };
  36089. /**
  36090. * The underlying WebGL Uniform buffer.
  36091. */
  36092. UniformBuffer.prototype.getBuffer = function () {
  36093. return this._buffer;
  36094. };
  36095. /**
  36096. * std140 layout specifies how to align data within an UBO structure.
  36097. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  36098. * for specs.
  36099. */
  36100. UniformBuffer.prototype._fillAlignment = function (size) {
  36101. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  36102. // and 4x4 matrices
  36103. // TODO : change if other types are used
  36104. var alignment;
  36105. if (size <= 2) {
  36106. alignment = size;
  36107. }
  36108. else {
  36109. alignment = 4;
  36110. }
  36111. if ((this._uniformLocationPointer % alignment) !== 0) {
  36112. var oldPointer = this._uniformLocationPointer;
  36113. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36114. var diff = this._uniformLocationPointer - oldPointer;
  36115. for (var i = 0; i < diff; i++) {
  36116. this._data.push(0);
  36117. }
  36118. }
  36119. };
  36120. /**
  36121. * Adds an uniform in the buffer.
  36122. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36123. * for the layout to be correct !
  36124. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36125. * @param {number|number[]} size Data size, or data directly.
  36126. */
  36127. UniformBuffer.prototype.addUniform = function (name, size) {
  36128. if (this._noUBO) {
  36129. return;
  36130. }
  36131. if (this._uniformLocations[name] !== undefined) {
  36132. // Already existing uniform
  36133. return;
  36134. }
  36135. // This function must be called in the order of the shader layout !
  36136. // size can be the size of the uniform, or data directly
  36137. var data;
  36138. if (size instanceof Array) {
  36139. data = size;
  36140. size = data.length;
  36141. }
  36142. else {
  36143. size = size;
  36144. data = [];
  36145. // Fill with zeros
  36146. for (var i = 0; i < size; i++) {
  36147. data.push(0);
  36148. }
  36149. }
  36150. this._fillAlignment(size);
  36151. this._uniformSizes[name] = size;
  36152. this._uniformLocations[name] = this._uniformLocationPointer;
  36153. this._uniformLocationPointer += size;
  36154. for (var i = 0; i < size; i++) {
  36155. this._data.push(data[i]);
  36156. }
  36157. this._needSync = true;
  36158. };
  36159. /**
  36160. * Wrapper for addUniform.
  36161. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36162. * @param {Matrix} mat A 4x4 matrix.
  36163. */
  36164. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36165. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36166. };
  36167. /**
  36168. * Wrapper for addUniform.
  36169. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36170. * @param {number} x
  36171. * @param {number} y
  36172. */
  36173. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36174. var temp = [x, y];
  36175. this.addUniform(name, temp);
  36176. };
  36177. /**
  36178. * Wrapper for addUniform.
  36179. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36180. * @param {number} x
  36181. * @param {number} y
  36182. * @param {number} z
  36183. */
  36184. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36185. var temp = [x, y, z];
  36186. this.addUniform(name, temp);
  36187. };
  36188. /**
  36189. * Wrapper for addUniform.
  36190. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36191. * @param {Color3} color
  36192. */
  36193. UniformBuffer.prototype.addColor3 = function (name, color) {
  36194. var temp = new Array();
  36195. color.toArray(temp);
  36196. this.addUniform(name, temp);
  36197. };
  36198. /**
  36199. * Wrapper for addUniform.
  36200. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36201. * @param {Color3} color
  36202. * @param {number} alpha
  36203. */
  36204. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36205. var temp = new Array();
  36206. color.toArray(temp);
  36207. temp.push(alpha);
  36208. this.addUniform(name, temp);
  36209. };
  36210. /**
  36211. * Wrapper for addUniform.
  36212. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36213. * @param {Vector3} vector
  36214. */
  36215. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36216. var temp = new Array();
  36217. vector.toArray(temp);
  36218. this.addUniform(name, temp);
  36219. };
  36220. /**
  36221. * Wrapper for addUniform.
  36222. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36223. */
  36224. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36225. this.addUniform(name, 12);
  36226. };
  36227. /**
  36228. * Wrapper for addUniform.
  36229. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36230. */
  36231. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36232. this.addUniform(name, 8);
  36233. };
  36234. /**
  36235. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36236. */
  36237. UniformBuffer.prototype.create = function () {
  36238. if (this._noUBO) {
  36239. return;
  36240. }
  36241. if (this._buffer) {
  36242. return; // nothing to do
  36243. }
  36244. // See spec, alignment must be filled as a vec4
  36245. this._fillAlignment(4);
  36246. this._bufferData = new Float32Array(this._data);
  36247. this._rebuild();
  36248. this._needSync = true;
  36249. };
  36250. /** @hidden */
  36251. UniformBuffer.prototype._rebuild = function () {
  36252. if (this._noUBO) {
  36253. return;
  36254. }
  36255. if (this._dynamic) {
  36256. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36257. }
  36258. else {
  36259. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36260. }
  36261. };
  36262. /**
  36263. * Updates the WebGL Uniform Buffer on the GPU.
  36264. * If the `dynamic` flag is set to true, no cache comparison is done.
  36265. * Otherwise, the buffer will be updated only if the cache differs.
  36266. */
  36267. UniformBuffer.prototype.update = function () {
  36268. if (!this._buffer) {
  36269. this.create();
  36270. return;
  36271. }
  36272. if (!this._dynamic && !this._needSync) {
  36273. return;
  36274. }
  36275. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36276. this._needSync = false;
  36277. };
  36278. /**
  36279. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36280. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36281. * @param {number[]|Float32Array} data Flattened data
  36282. * @param {number} size Size of the data.
  36283. */
  36284. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36285. var location = this._uniformLocations[uniformName];
  36286. if (location === undefined) {
  36287. if (this._buffer) {
  36288. // Cannot add an uniform if the buffer is already created
  36289. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36290. return;
  36291. }
  36292. this.addUniform(uniformName, size);
  36293. location = this._uniformLocations[uniformName];
  36294. }
  36295. if (!this._buffer) {
  36296. this.create();
  36297. }
  36298. if (!this._dynamic) {
  36299. // Cache for static uniform buffers
  36300. var changed = false;
  36301. for (var i = 0; i < size; i++) {
  36302. if (this._bufferData[location + i] !== data[i]) {
  36303. changed = true;
  36304. this._bufferData[location + i] = data[i];
  36305. }
  36306. }
  36307. this._needSync = this._needSync || changed;
  36308. }
  36309. else {
  36310. // No cache for dynamic
  36311. for (var i = 0; i < size; i++) {
  36312. this._bufferData[location + i] = data[i];
  36313. }
  36314. }
  36315. };
  36316. // Update methods
  36317. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36318. // To match std140, matrix must be realigned
  36319. for (var i = 0; i < 3; i++) {
  36320. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36321. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36322. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36323. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36324. }
  36325. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36326. };
  36327. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36328. this._currentEffect.setMatrix3x3(name, matrix);
  36329. };
  36330. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36331. this._currentEffect.setMatrix2x2(name, matrix);
  36332. };
  36333. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36334. // To match std140, matrix must be realigned
  36335. for (var i = 0; i < 2; i++) {
  36336. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36337. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36338. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36339. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36340. }
  36341. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36342. };
  36343. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36344. this._currentEffect.setFloat(name, x);
  36345. };
  36346. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36347. UniformBuffer._tempBuffer[0] = x;
  36348. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36349. };
  36350. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36351. if (suffix === void 0) { suffix = ""; }
  36352. this._currentEffect.setFloat2(name + suffix, x, y);
  36353. };
  36354. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36355. if (suffix === void 0) { suffix = ""; }
  36356. UniformBuffer._tempBuffer[0] = x;
  36357. UniformBuffer._tempBuffer[1] = y;
  36358. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36359. };
  36360. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36361. if (suffix === void 0) { suffix = ""; }
  36362. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36363. };
  36364. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36365. if (suffix === void 0) { suffix = ""; }
  36366. UniformBuffer._tempBuffer[0] = x;
  36367. UniformBuffer._tempBuffer[1] = y;
  36368. UniformBuffer._tempBuffer[2] = z;
  36369. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36370. };
  36371. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36372. if (suffix === void 0) { suffix = ""; }
  36373. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36374. };
  36375. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36376. if (suffix === void 0) { suffix = ""; }
  36377. UniformBuffer._tempBuffer[0] = x;
  36378. UniformBuffer._tempBuffer[1] = y;
  36379. UniformBuffer._tempBuffer[2] = z;
  36380. UniformBuffer._tempBuffer[3] = w;
  36381. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36382. };
  36383. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36384. this._currentEffect.setMatrix(name, mat);
  36385. };
  36386. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36387. this.updateUniform(name, mat.toArray(), 16);
  36388. };
  36389. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36390. this._currentEffect.setVector3(name, vector);
  36391. };
  36392. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36393. vector.toArray(UniformBuffer._tempBuffer);
  36394. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36395. };
  36396. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36397. this._currentEffect.setVector4(name, vector);
  36398. };
  36399. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36400. vector.toArray(UniformBuffer._tempBuffer);
  36401. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36402. };
  36403. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36404. if (suffix === void 0) { suffix = ""; }
  36405. this._currentEffect.setColor3(name + suffix, color);
  36406. };
  36407. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36408. if (suffix === void 0) { suffix = ""; }
  36409. color.toArray(UniformBuffer._tempBuffer);
  36410. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36411. };
  36412. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36413. if (suffix === void 0) { suffix = ""; }
  36414. this._currentEffect.setColor4(name + suffix, color, alpha);
  36415. };
  36416. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36417. if (suffix === void 0) { suffix = ""; }
  36418. color.toArray(UniformBuffer._tempBuffer);
  36419. UniformBuffer._tempBuffer[3] = alpha;
  36420. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36421. };
  36422. /**
  36423. * Sets a sampler uniform on the effect.
  36424. * @param {string} name Name of the sampler.
  36425. * @param {Texture} texture
  36426. */
  36427. UniformBuffer.prototype.setTexture = function (name, texture) {
  36428. this._currentEffect.setTexture(name, texture);
  36429. };
  36430. /**
  36431. * Directly updates the value of the uniform in the cache AND on the GPU.
  36432. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36433. * @param {number[]|Float32Array} data Flattened data
  36434. */
  36435. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36436. this.updateUniform(uniformName, data, data.length);
  36437. this.update();
  36438. };
  36439. /**
  36440. * Binds this uniform buffer to an effect.
  36441. * @param {Effect} effect
  36442. * @param {string} name Name of the uniform block in the shader.
  36443. */
  36444. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36445. this._currentEffect = effect;
  36446. if (this._noUBO || !this._buffer) {
  36447. return;
  36448. }
  36449. effect.bindUniformBuffer(this._buffer, name);
  36450. };
  36451. /**
  36452. * Disposes the uniform buffer.
  36453. */
  36454. UniformBuffer.prototype.dispose = function () {
  36455. if (this._noUBO) {
  36456. return;
  36457. }
  36458. var index = this._engine._uniformBuffers.indexOf(this);
  36459. if (index !== -1) {
  36460. this._engine._uniformBuffers.splice(index, 1);
  36461. }
  36462. if (!this._buffer) {
  36463. return;
  36464. }
  36465. if (this._engine._releaseBuffer(this._buffer)) {
  36466. this._buffer = null;
  36467. }
  36468. };
  36469. // Pool for avoiding memory leaks
  36470. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36471. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36472. return UniformBuffer;
  36473. }());
  36474. BABYLON.UniformBuffer = UniformBuffer;
  36475. })(BABYLON || (BABYLON = {}));
  36476. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36477. var BABYLON;
  36478. (function (BABYLON) {
  36479. /**
  36480. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36481. */
  36482. var VertexData = /** @class */ (function () {
  36483. function VertexData() {
  36484. }
  36485. /**
  36486. * Uses the passed data array to set the set the values for the specified kind of data
  36487. * @param data a linear array of floating numbers
  36488. * @param kind the type of data that is being set, eg positions, colors etc
  36489. */
  36490. VertexData.prototype.set = function (data, kind) {
  36491. switch (kind) {
  36492. case BABYLON.VertexBuffer.PositionKind:
  36493. this.positions = data;
  36494. break;
  36495. case BABYLON.VertexBuffer.NormalKind:
  36496. this.normals = data;
  36497. break;
  36498. case BABYLON.VertexBuffer.TangentKind:
  36499. this.tangents = data;
  36500. break;
  36501. case BABYLON.VertexBuffer.UVKind:
  36502. this.uvs = data;
  36503. break;
  36504. case BABYLON.VertexBuffer.UV2Kind:
  36505. this.uvs2 = data;
  36506. break;
  36507. case BABYLON.VertexBuffer.UV3Kind:
  36508. this.uvs3 = data;
  36509. break;
  36510. case BABYLON.VertexBuffer.UV4Kind:
  36511. this.uvs4 = data;
  36512. break;
  36513. case BABYLON.VertexBuffer.UV5Kind:
  36514. this.uvs5 = data;
  36515. break;
  36516. case BABYLON.VertexBuffer.UV6Kind:
  36517. this.uvs6 = data;
  36518. break;
  36519. case BABYLON.VertexBuffer.ColorKind:
  36520. this.colors = data;
  36521. break;
  36522. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36523. this.matricesIndices = data;
  36524. break;
  36525. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36526. this.matricesWeights = data;
  36527. break;
  36528. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36529. this.matricesIndicesExtra = data;
  36530. break;
  36531. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36532. this.matricesWeightsExtra = data;
  36533. break;
  36534. }
  36535. };
  36536. /**
  36537. * Associates the vertexData to the passed Mesh.
  36538. * Sets it as updatable or not (default `false`)
  36539. * @param mesh the mesh the vertexData is applied to
  36540. * @param updatable when used and having the value true allows new data to update the vertexData
  36541. * @returns the VertexData
  36542. */
  36543. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36544. this._applyTo(mesh, updatable);
  36545. return this;
  36546. };
  36547. /**
  36548. * Associates the vertexData to the passed Geometry.
  36549. * Sets it as updatable or not (default `false`)
  36550. * @param geometry the geometry the vertexData is applied to
  36551. * @param updatable when used and having the value true allows new data to update the vertexData
  36552. * @returns VertexData
  36553. */
  36554. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36555. this._applyTo(geometry, updatable);
  36556. return this;
  36557. };
  36558. /**
  36559. * Updates the associated mesh
  36560. * @param mesh the mesh to be updated
  36561. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36562. * @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
  36563. * @returns VertexData
  36564. */
  36565. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36566. this._update(mesh);
  36567. return this;
  36568. };
  36569. /**
  36570. * Updates the associated geometry
  36571. * @param geometry the geometry to be updated
  36572. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36573. * @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
  36574. * @returns VertexData.
  36575. */
  36576. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36577. this._update(geometry);
  36578. return this;
  36579. };
  36580. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36581. if (updatable === void 0) { updatable = false; }
  36582. if (this.positions) {
  36583. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36584. }
  36585. if (this.normals) {
  36586. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36587. }
  36588. if (this.tangents) {
  36589. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36590. }
  36591. if (this.uvs) {
  36592. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36593. }
  36594. if (this.uvs2) {
  36595. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36596. }
  36597. if (this.uvs3) {
  36598. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36599. }
  36600. if (this.uvs4) {
  36601. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36602. }
  36603. if (this.uvs5) {
  36604. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36605. }
  36606. if (this.uvs6) {
  36607. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36608. }
  36609. if (this.colors) {
  36610. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36611. }
  36612. if (this.matricesIndices) {
  36613. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36614. }
  36615. if (this.matricesWeights) {
  36616. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36617. }
  36618. if (this.matricesIndicesExtra) {
  36619. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36620. }
  36621. if (this.matricesWeightsExtra) {
  36622. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36623. }
  36624. if (this.indices) {
  36625. meshOrGeometry.setIndices(this.indices, null, updatable);
  36626. }
  36627. else {
  36628. meshOrGeometry.setIndices([], null);
  36629. }
  36630. return this;
  36631. };
  36632. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36633. if (this.positions) {
  36634. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36635. }
  36636. if (this.normals) {
  36637. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36638. }
  36639. if (this.tangents) {
  36640. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36641. }
  36642. if (this.uvs) {
  36643. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36644. }
  36645. if (this.uvs2) {
  36646. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36647. }
  36648. if (this.uvs3) {
  36649. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36650. }
  36651. if (this.uvs4) {
  36652. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36653. }
  36654. if (this.uvs5) {
  36655. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36656. }
  36657. if (this.uvs6) {
  36658. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36659. }
  36660. if (this.colors) {
  36661. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36662. }
  36663. if (this.matricesIndices) {
  36664. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36665. }
  36666. if (this.matricesWeights) {
  36667. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36668. }
  36669. if (this.matricesIndicesExtra) {
  36670. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36671. }
  36672. if (this.matricesWeightsExtra) {
  36673. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36674. }
  36675. if (this.indices) {
  36676. meshOrGeometry.setIndices(this.indices, null);
  36677. }
  36678. return this;
  36679. };
  36680. /**
  36681. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36682. * @param matrix the transforming matrix
  36683. * @returns the VertexData
  36684. */
  36685. VertexData.prototype.transform = function (matrix) {
  36686. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36687. var transformed = BABYLON.Vector3.Zero();
  36688. var index;
  36689. if (this.positions) {
  36690. var position = BABYLON.Vector3.Zero();
  36691. for (index = 0; index < this.positions.length; index += 3) {
  36692. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36693. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36694. this.positions[index] = transformed.x;
  36695. this.positions[index + 1] = transformed.y;
  36696. this.positions[index + 2] = transformed.z;
  36697. }
  36698. }
  36699. if (this.normals) {
  36700. var normal = BABYLON.Vector3.Zero();
  36701. for (index = 0; index < this.normals.length; index += 3) {
  36702. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36703. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36704. this.normals[index] = transformed.x;
  36705. this.normals[index + 1] = transformed.y;
  36706. this.normals[index + 2] = transformed.z;
  36707. }
  36708. }
  36709. if (this.tangents) {
  36710. var tangent = BABYLON.Vector4.Zero();
  36711. var tangentTransformed = BABYLON.Vector4.Zero();
  36712. for (index = 0; index < this.tangents.length; index += 4) {
  36713. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36714. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36715. this.tangents[index] = tangentTransformed.x;
  36716. this.tangents[index + 1] = tangentTransformed.y;
  36717. this.tangents[index + 2] = tangentTransformed.z;
  36718. this.tangents[index + 3] = tangentTransformed.w;
  36719. }
  36720. }
  36721. if (flip && this.indices) {
  36722. for (index = 0; index < this.indices.length; index += 3) {
  36723. var tmp = this.indices[index + 1];
  36724. this.indices[index + 1] = this.indices[index + 2];
  36725. this.indices[index + 2] = tmp;
  36726. }
  36727. }
  36728. return this;
  36729. };
  36730. /**
  36731. * Merges the passed VertexData into the current one
  36732. * @param other the VertexData to be merged into the current one
  36733. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  36734. * @returns the modified VertexData
  36735. */
  36736. VertexData.prototype.merge = function (other, use32BitsIndices) {
  36737. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  36738. this._validate();
  36739. other._validate();
  36740. if (!this.normals !== !other.normals ||
  36741. !this.tangents !== !other.tangents ||
  36742. !this.uvs !== !other.uvs ||
  36743. !this.uvs2 !== !other.uvs2 ||
  36744. !this.uvs3 !== !other.uvs3 ||
  36745. !this.uvs4 !== !other.uvs4 ||
  36746. !this.uvs5 !== !other.uvs5 ||
  36747. !this.uvs6 !== !other.uvs6 ||
  36748. !this.colors !== !other.colors ||
  36749. !this.matricesIndices !== !other.matricesIndices ||
  36750. !this.matricesWeights !== !other.matricesWeights ||
  36751. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36752. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36753. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36754. }
  36755. if (other.indices) {
  36756. if (!this.indices) {
  36757. this.indices = [];
  36758. }
  36759. var offset = this.positions ? this.positions.length / 3 : 0;
  36760. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  36761. if (isSrcTypedArray) {
  36762. var len = this.indices.length + other.indices.length;
  36763. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  36764. temp.set(this.indices);
  36765. var decal = this.indices.length;
  36766. for (var index = 0; index < other.indices.length; index++) {
  36767. temp[decal + index] = other.indices[index] + offset;
  36768. }
  36769. this.indices = temp;
  36770. }
  36771. else {
  36772. for (var index = 0; index < other.indices.length; index++) {
  36773. this.indices.push(other.indices[index] + offset);
  36774. }
  36775. }
  36776. }
  36777. this.positions = this._mergeElement(this.positions, other.positions);
  36778. this.normals = this._mergeElement(this.normals, other.normals);
  36779. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36780. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36781. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36782. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36783. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36784. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36785. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36786. this.colors = this._mergeElement(this.colors, other.colors);
  36787. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36788. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36789. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36790. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36791. return this;
  36792. };
  36793. VertexData.prototype._mergeElement = function (source, other) {
  36794. if (!source) {
  36795. return other;
  36796. }
  36797. if (!other) {
  36798. return source;
  36799. }
  36800. var len = other.length + source.length;
  36801. var isSrcTypedArray = source instanceof Float32Array;
  36802. var isOthTypedArray = other instanceof Float32Array;
  36803. // use non-loop method when the source is Float32Array
  36804. if (isSrcTypedArray) {
  36805. var ret32 = new Float32Array(len);
  36806. ret32.set(source);
  36807. ret32.set(other, source.length);
  36808. return ret32;
  36809. // source is number[], when other is also use concat
  36810. }
  36811. else if (!isOthTypedArray) {
  36812. return source.concat(other);
  36813. // source is a number[], but other is a Float32Array, loop required
  36814. }
  36815. else {
  36816. var ret = source.slice(0); // copy source to a separate array
  36817. for (var i = 0, len = other.length; i < len; i++) {
  36818. ret.push(other[i]);
  36819. }
  36820. return ret;
  36821. }
  36822. };
  36823. VertexData.prototype._validate = function () {
  36824. if (!this.positions) {
  36825. throw new Error("Positions are required");
  36826. }
  36827. var getElementCount = function (kind, values) {
  36828. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36829. if ((values.length % stride) !== 0) {
  36830. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36831. }
  36832. return values.length / stride;
  36833. };
  36834. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36835. var validateElementCount = function (kind, values) {
  36836. var elementCount = getElementCount(kind, values);
  36837. if (elementCount !== positionsElementCount) {
  36838. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36839. }
  36840. };
  36841. if (this.normals)
  36842. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36843. if (this.tangents)
  36844. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36845. if (this.uvs)
  36846. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36847. if (this.uvs2)
  36848. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36849. if (this.uvs3)
  36850. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36851. if (this.uvs4)
  36852. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36853. if (this.uvs5)
  36854. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36855. if (this.uvs6)
  36856. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36857. if (this.colors)
  36858. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36859. if (this.matricesIndices)
  36860. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36861. if (this.matricesWeights)
  36862. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36863. if (this.matricesIndicesExtra)
  36864. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36865. if (this.matricesWeightsExtra)
  36866. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36867. };
  36868. /**
  36869. * Serializes the VertexData
  36870. * @returns a serialized object
  36871. */
  36872. VertexData.prototype.serialize = function () {
  36873. var serializationObject = this.serialize();
  36874. if (this.positions) {
  36875. serializationObject.positions = this.positions;
  36876. }
  36877. if (this.normals) {
  36878. serializationObject.normals = this.normals;
  36879. }
  36880. if (this.tangents) {
  36881. serializationObject.tangents = this.tangents;
  36882. }
  36883. if (this.uvs) {
  36884. serializationObject.uvs = this.uvs;
  36885. }
  36886. if (this.uvs2) {
  36887. serializationObject.uvs2 = this.uvs2;
  36888. }
  36889. if (this.uvs3) {
  36890. serializationObject.uvs3 = this.uvs3;
  36891. }
  36892. if (this.uvs4) {
  36893. serializationObject.uvs4 = this.uvs4;
  36894. }
  36895. if (this.uvs5) {
  36896. serializationObject.uvs5 = this.uvs5;
  36897. }
  36898. if (this.uvs6) {
  36899. serializationObject.uvs6 = this.uvs6;
  36900. }
  36901. if (this.colors) {
  36902. serializationObject.colors = this.colors;
  36903. }
  36904. if (this.matricesIndices) {
  36905. serializationObject.matricesIndices = this.matricesIndices;
  36906. serializationObject.matricesIndices._isExpanded = true;
  36907. }
  36908. if (this.matricesWeights) {
  36909. serializationObject.matricesWeights = this.matricesWeights;
  36910. }
  36911. if (this.matricesIndicesExtra) {
  36912. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36913. serializationObject.matricesIndicesExtra._isExpanded = true;
  36914. }
  36915. if (this.matricesWeightsExtra) {
  36916. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36917. }
  36918. serializationObject.indices = this.indices;
  36919. return serializationObject;
  36920. };
  36921. // Statics
  36922. /**
  36923. * Extracts the vertexData from a mesh
  36924. * @param mesh the mesh from which to extract the VertexData
  36925. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36926. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36927. * @returns the object VertexData associated to the passed mesh
  36928. */
  36929. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36930. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36931. };
  36932. /**
  36933. * Extracts the vertexData from the geometry
  36934. * @param geometry the geometry from which to extract the VertexData
  36935. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36936. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36937. * @returns the object VertexData associated to the passed mesh
  36938. */
  36939. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36940. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36941. };
  36942. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36943. var result = new VertexData();
  36944. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36945. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36946. }
  36947. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36948. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36949. }
  36950. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36951. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36952. }
  36953. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36954. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36955. }
  36956. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36957. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36958. }
  36959. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36960. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36961. }
  36962. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36963. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36964. }
  36965. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36966. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36967. }
  36968. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36969. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36970. }
  36971. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36972. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36973. }
  36974. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36975. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36976. }
  36977. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36978. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36979. }
  36980. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36981. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36982. }
  36983. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36984. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36985. }
  36986. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  36987. return result;
  36988. };
  36989. /**
  36990. * Creates the VertexData for a Ribbon
  36991. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36992. * * pathArray array of paths, each of which an array of successive Vector3
  36993. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36994. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36995. * * 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
  36996. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36997. * * 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)
  36998. * * 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)
  36999. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  37000. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  37001. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  37002. * @returns the VertexData of the ribbon
  37003. */
  37004. VertexData.CreateRibbon = function (options) {
  37005. var pathArray = options.pathArray;
  37006. var closeArray = options.closeArray || false;
  37007. var closePath = options.closePath || false;
  37008. var invertUV = options.invertUV || false;
  37009. var defaultOffset = Math.floor(pathArray[0].length / 2);
  37010. var offset = options.offset || defaultOffset;
  37011. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  37012. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37013. var customUV = options.uvs;
  37014. var customColors = options.colors;
  37015. var positions = [];
  37016. var indices = [];
  37017. var normals = [];
  37018. var uvs = [];
  37019. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  37020. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  37021. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  37022. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  37023. var minlg; // minimal length among all paths from pathArray
  37024. var lg = []; // array of path lengths : nb of vertex per path
  37025. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  37026. var p; // path iterator
  37027. var i; // point iterator
  37028. var j; // point iterator
  37029. // if single path in pathArray
  37030. if (pathArray.length < 2) {
  37031. var ar1 = [];
  37032. var ar2 = [];
  37033. for (i = 0; i < pathArray[0].length - offset; i++) {
  37034. ar1.push(pathArray[0][i]);
  37035. ar2.push(pathArray[0][i + offset]);
  37036. }
  37037. pathArray = [ar1, ar2];
  37038. }
  37039. // positions and horizontal distances (u)
  37040. var idc = 0;
  37041. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  37042. var path;
  37043. var l;
  37044. minlg = pathArray[0].length;
  37045. var vectlg;
  37046. var dist;
  37047. for (p = 0; p < pathArray.length; p++) {
  37048. uTotalDistance[p] = 0;
  37049. us[p] = [0];
  37050. path = pathArray[p];
  37051. l = path.length;
  37052. minlg = (minlg < l) ? minlg : l;
  37053. j = 0;
  37054. while (j < l) {
  37055. positions.push(path[j].x, path[j].y, path[j].z);
  37056. if (j > 0) {
  37057. vectlg = path[j].subtract(path[j - 1]).length();
  37058. dist = vectlg + uTotalDistance[p];
  37059. us[p].push(dist);
  37060. uTotalDistance[p] = dist;
  37061. }
  37062. j++;
  37063. }
  37064. if (closePath) { // an extra hidden vertex is added in the "positions" array
  37065. j--;
  37066. positions.push(path[0].x, path[0].y, path[0].z);
  37067. vectlg = path[j].subtract(path[0]).length();
  37068. dist = vectlg + uTotalDistance[p];
  37069. us[p].push(dist);
  37070. uTotalDistance[p] = dist;
  37071. }
  37072. lg[p] = l + closePathCorr;
  37073. idx[p] = idc;
  37074. idc += (l + closePathCorr);
  37075. }
  37076. // vertical distances (v)
  37077. var path1;
  37078. var path2;
  37079. var vertex1 = null;
  37080. var vertex2 = null;
  37081. for (i = 0; i < minlg + closePathCorr; i++) {
  37082. vTotalDistance[i] = 0;
  37083. vs[i] = [0];
  37084. for (p = 0; p < pathArray.length - 1; p++) {
  37085. path1 = pathArray[p];
  37086. path2 = pathArray[p + 1];
  37087. if (i === minlg) { // closePath
  37088. vertex1 = path1[0];
  37089. vertex2 = path2[0];
  37090. }
  37091. else {
  37092. vertex1 = path1[i];
  37093. vertex2 = path2[i];
  37094. }
  37095. vectlg = vertex2.subtract(vertex1).length();
  37096. dist = vectlg + vTotalDistance[i];
  37097. vs[i].push(dist);
  37098. vTotalDistance[i] = dist;
  37099. }
  37100. if (closeArray && vertex2 && vertex1) {
  37101. path1 = pathArray[p];
  37102. path2 = pathArray[0];
  37103. if (i === minlg) { // closePath
  37104. vertex2 = path2[0];
  37105. }
  37106. vectlg = vertex2.subtract(vertex1).length();
  37107. dist = vectlg + vTotalDistance[i];
  37108. vTotalDistance[i] = dist;
  37109. }
  37110. }
  37111. // uvs
  37112. var u;
  37113. var v;
  37114. if (customUV) {
  37115. for (p = 0; p < customUV.length; p++) {
  37116. uvs.push(customUV[p].x, customUV[p].y);
  37117. }
  37118. }
  37119. else {
  37120. for (p = 0; p < pathArray.length; p++) {
  37121. for (i = 0; i < minlg + closePathCorr; i++) {
  37122. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37123. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37124. if (invertUV) {
  37125. uvs.push(v, u);
  37126. }
  37127. else {
  37128. uvs.push(u, v);
  37129. }
  37130. }
  37131. }
  37132. }
  37133. // indices
  37134. p = 0; // path index
  37135. var pi = 0; // positions array index
  37136. var l1 = lg[p] - 1; // path1 length
  37137. var l2 = lg[p + 1] - 1; // path2 length
  37138. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37139. var shft = idx[1] - idx[0]; // shift
  37140. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37141. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37142. // 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
  37143. indices.push(pi, pi + shft, pi + 1);
  37144. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37145. pi += 1;
  37146. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37147. p++;
  37148. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37149. shft = idx[0] - idx[p];
  37150. l1 = lg[p] - 1;
  37151. l2 = lg[0] - 1;
  37152. }
  37153. else {
  37154. shft = idx[p + 1] - idx[p];
  37155. l1 = lg[p] - 1;
  37156. l2 = lg[p + 1] - 1;
  37157. }
  37158. pi = idx[p];
  37159. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37160. }
  37161. }
  37162. // normals
  37163. VertexData.ComputeNormals(positions, indices, normals);
  37164. if (closePath) { // update both the first and last vertex normals to their average value
  37165. var indexFirst = 0;
  37166. var indexLast = 0;
  37167. for (p = 0; p < pathArray.length; p++) {
  37168. indexFirst = idx[p] * 3;
  37169. if (p + 1 < pathArray.length) {
  37170. indexLast = (idx[p + 1] - 1) * 3;
  37171. }
  37172. else {
  37173. indexLast = normals.length - 3;
  37174. }
  37175. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37176. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37177. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37178. normals[indexLast] = normals[indexFirst];
  37179. normals[indexLast + 1] = normals[indexFirst + 1];
  37180. normals[indexLast + 2] = normals[indexFirst + 2];
  37181. }
  37182. }
  37183. // sides
  37184. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37185. // Colors
  37186. var colors = null;
  37187. if (customColors) {
  37188. colors = new Float32Array(customColors.length * 4);
  37189. for (var c = 0; c < customColors.length; c++) {
  37190. colors[c * 4] = customColors[c].r;
  37191. colors[c * 4 + 1] = customColors[c].g;
  37192. colors[c * 4 + 2] = customColors[c].b;
  37193. colors[c * 4 + 3] = customColors[c].a;
  37194. }
  37195. }
  37196. // Result
  37197. var vertexData = new VertexData();
  37198. var positions32 = new Float32Array(positions);
  37199. var normals32 = new Float32Array(normals);
  37200. var uvs32 = new Float32Array(uvs);
  37201. vertexData.indices = indices;
  37202. vertexData.positions = positions32;
  37203. vertexData.normals = normals32;
  37204. vertexData.uvs = uvs32;
  37205. if (colors) {
  37206. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37207. }
  37208. if (closePath) {
  37209. vertexData._idx = idx;
  37210. }
  37211. return vertexData;
  37212. };
  37213. /**
  37214. * Creates the VertexData for a box
  37215. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37216. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37217. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37218. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37219. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37220. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37221. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37222. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37223. * * 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)
  37224. * * 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)
  37225. * @returns the VertexData of the box
  37226. */
  37227. VertexData.CreateBox = function (options) {
  37228. var normalsSource = [
  37229. new BABYLON.Vector3(0, 0, 1),
  37230. new BABYLON.Vector3(0, 0, -1),
  37231. new BABYLON.Vector3(1, 0, 0),
  37232. new BABYLON.Vector3(-1, 0, 0),
  37233. new BABYLON.Vector3(0, 1, 0),
  37234. new BABYLON.Vector3(0, -1, 0)
  37235. ];
  37236. var indices = [];
  37237. var positions = [];
  37238. var normals = [];
  37239. var uvs = [];
  37240. var width = options.width || options.size || 1;
  37241. var height = options.height || options.size || 1;
  37242. var depth = options.depth || options.size || 1;
  37243. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37244. var faceUV = options.faceUV || new Array(6);
  37245. var faceColors = options.faceColors;
  37246. var colors = [];
  37247. // default face colors and UV if undefined
  37248. for (var f = 0; f < 6; f++) {
  37249. if (faceUV[f] === undefined) {
  37250. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37251. }
  37252. if (faceColors && faceColors[f] === undefined) {
  37253. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37254. }
  37255. }
  37256. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37257. // Create each face in turn.
  37258. for (var index = 0; index < normalsSource.length; index++) {
  37259. var normal = normalsSource[index];
  37260. // Get two vectors perpendicular to the face normal and to each other.
  37261. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37262. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37263. // Six indices (two triangles) per face.
  37264. var verticesLength = positions.length / 3;
  37265. indices.push(verticesLength);
  37266. indices.push(verticesLength + 1);
  37267. indices.push(verticesLength + 2);
  37268. indices.push(verticesLength);
  37269. indices.push(verticesLength + 2);
  37270. indices.push(verticesLength + 3);
  37271. // Four vertices per face.
  37272. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37273. positions.push(vertex.x, vertex.y, vertex.z);
  37274. normals.push(normal.x, normal.y, normal.z);
  37275. uvs.push(faceUV[index].z, faceUV[index].w);
  37276. if (faceColors) {
  37277. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37278. }
  37279. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37280. positions.push(vertex.x, vertex.y, vertex.z);
  37281. normals.push(normal.x, normal.y, normal.z);
  37282. uvs.push(faceUV[index].x, faceUV[index].w);
  37283. if (faceColors) {
  37284. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37285. }
  37286. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37287. positions.push(vertex.x, vertex.y, vertex.z);
  37288. normals.push(normal.x, normal.y, normal.z);
  37289. uvs.push(faceUV[index].x, faceUV[index].y);
  37290. if (faceColors) {
  37291. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37292. }
  37293. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37294. positions.push(vertex.x, vertex.y, vertex.z);
  37295. normals.push(normal.x, normal.y, normal.z);
  37296. uvs.push(faceUV[index].z, faceUV[index].y);
  37297. if (faceColors) {
  37298. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37299. }
  37300. }
  37301. // sides
  37302. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37303. // Result
  37304. var vertexData = new VertexData();
  37305. vertexData.indices = indices;
  37306. vertexData.positions = positions;
  37307. vertexData.normals = normals;
  37308. vertexData.uvs = uvs;
  37309. if (faceColors) {
  37310. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37311. vertexData.colors = totalColors;
  37312. }
  37313. return vertexData;
  37314. };
  37315. /**
  37316. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37317. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37318. * * segments sets the number of horizontal strips optional, default 32
  37319. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37320. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37321. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37322. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37323. * * 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
  37324. * * 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
  37325. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37326. * * 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)
  37327. * * 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)
  37328. * @returns the VertexData of the ellipsoid
  37329. */
  37330. VertexData.CreateSphere = function (options) {
  37331. var segments = options.segments || 32;
  37332. var diameterX = options.diameterX || options.diameter || 1;
  37333. var diameterY = options.diameterY || options.diameter || 1;
  37334. var diameterZ = options.diameterZ || options.diameter || 1;
  37335. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37336. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37337. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37338. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37339. var totalZRotationSteps = 2 + segments;
  37340. var totalYRotationSteps = 2 * totalZRotationSteps;
  37341. var indices = [];
  37342. var positions = [];
  37343. var normals = [];
  37344. var uvs = [];
  37345. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37346. var normalizedZ = zRotationStep / totalZRotationSteps;
  37347. var angleZ = normalizedZ * Math.PI * slice;
  37348. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37349. var normalizedY = yRotationStep / totalYRotationSteps;
  37350. var angleY = normalizedY * Math.PI * 2 * arc;
  37351. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37352. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37353. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37354. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37355. var vertex = complete.multiply(radius);
  37356. var normal = complete.divide(radius).normalize();
  37357. positions.push(vertex.x, vertex.y, vertex.z);
  37358. normals.push(normal.x, normal.y, normal.z);
  37359. uvs.push(normalizedY, normalizedZ);
  37360. }
  37361. if (zRotationStep > 0) {
  37362. var verticesCount = positions.length / 3;
  37363. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37364. indices.push((firstIndex));
  37365. indices.push((firstIndex + 1));
  37366. indices.push(firstIndex + totalYRotationSteps + 1);
  37367. indices.push((firstIndex + totalYRotationSteps + 1));
  37368. indices.push((firstIndex + 1));
  37369. indices.push((firstIndex + totalYRotationSteps + 2));
  37370. }
  37371. }
  37372. }
  37373. // Sides
  37374. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37375. // Result
  37376. var vertexData = new VertexData();
  37377. vertexData.indices = indices;
  37378. vertexData.positions = positions;
  37379. vertexData.normals = normals;
  37380. vertexData.uvs = uvs;
  37381. return vertexData;
  37382. };
  37383. /**
  37384. * Creates the VertexData for a cylinder, cone or prism
  37385. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37386. * * height sets the height (y direction) of the cylinder, optional, default 2
  37387. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37388. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37389. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37390. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37391. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37392. * * 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
  37393. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37394. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37395. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37396. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37397. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37398. * * 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)
  37399. * * 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)
  37400. * @returns the VertexData of the cylinder, cone or prism
  37401. */
  37402. VertexData.CreateCylinder = function (options) {
  37403. var height = options.height || 2;
  37404. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37405. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37406. var tessellation = options.tessellation || 24;
  37407. var subdivisions = options.subdivisions || 1;
  37408. var hasRings = options.hasRings ? true : false;
  37409. var enclose = options.enclose ? true : false;
  37410. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37411. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37412. var faceUV = options.faceUV || new Array(3);
  37413. var faceColors = options.faceColors;
  37414. // default face colors and UV if undefined
  37415. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37416. var ringNb = (hasRings) ? subdivisions : 1;
  37417. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37418. var f;
  37419. for (f = 0; f < surfaceNb; f++) {
  37420. if (faceColors && faceColors[f] === undefined) {
  37421. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37422. }
  37423. }
  37424. for (f = 0; f < surfaceNb; f++) {
  37425. if (faceUV && faceUV[f] === undefined) {
  37426. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37427. }
  37428. }
  37429. var indices = new Array();
  37430. var positions = new Array();
  37431. var normals = new Array();
  37432. var uvs = new Array();
  37433. var colors = new Array();
  37434. var angle_step = Math.PI * 2 * arc / tessellation;
  37435. var angle;
  37436. var h;
  37437. var radius;
  37438. var tan = (diameterBottom - diameterTop) / 2 / height;
  37439. var ringVertex = BABYLON.Vector3.Zero();
  37440. var ringNormal = BABYLON.Vector3.Zero();
  37441. var ringFirstVertex = BABYLON.Vector3.Zero();
  37442. var ringFirstNormal = BABYLON.Vector3.Zero();
  37443. var quadNormal = BABYLON.Vector3.Zero();
  37444. var Y = BABYLON.Axis.Y;
  37445. // positions, normals, uvs
  37446. var i;
  37447. var j;
  37448. var r;
  37449. var ringIdx = 1;
  37450. var s = 1; // surface index
  37451. var cs = 0;
  37452. var v = 0;
  37453. for (i = 0; i <= subdivisions; i++) {
  37454. h = i / subdivisions;
  37455. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37456. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37457. for (r = 0; r < ringIdx; r++) {
  37458. if (hasRings) {
  37459. s += r;
  37460. }
  37461. if (enclose) {
  37462. s += 2 * r;
  37463. }
  37464. for (j = 0; j <= tessellation; j++) {
  37465. angle = j * angle_step;
  37466. // position
  37467. ringVertex.x = Math.cos(-angle) * radius;
  37468. ringVertex.y = -height / 2 + h * height;
  37469. ringVertex.z = Math.sin(-angle) * radius;
  37470. // normal
  37471. if (diameterTop === 0 && i === subdivisions) {
  37472. // if no top cap, reuse former normals
  37473. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37474. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37475. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37476. }
  37477. else {
  37478. ringNormal.x = ringVertex.x;
  37479. ringNormal.z = ringVertex.z;
  37480. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37481. ringNormal.normalize();
  37482. }
  37483. // keep first ring vertex values for enclose
  37484. if (j === 0) {
  37485. ringFirstVertex.copyFrom(ringVertex);
  37486. ringFirstNormal.copyFrom(ringNormal);
  37487. }
  37488. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37489. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37490. if (hasRings) {
  37491. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37492. }
  37493. else {
  37494. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37495. }
  37496. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37497. if (faceColors) {
  37498. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37499. }
  37500. }
  37501. // if enclose, add four vertices and their dedicated normals
  37502. if (arc !== 1 && enclose) {
  37503. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37504. positions.push(0, ringVertex.y, 0);
  37505. positions.push(0, ringVertex.y, 0);
  37506. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37507. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37508. quadNormal.normalize();
  37509. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37510. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37511. quadNormal.normalize();
  37512. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37513. if (hasRings) {
  37514. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37515. }
  37516. else {
  37517. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37518. }
  37519. uvs.push(faceUV[s + 1].x, v);
  37520. uvs.push(faceUV[s + 1].z, v);
  37521. if (hasRings) {
  37522. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37523. }
  37524. else {
  37525. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37526. }
  37527. uvs.push(faceUV[s + 2].x, v);
  37528. uvs.push(faceUV[s + 2].z, v);
  37529. if (faceColors) {
  37530. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37531. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37532. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37533. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37534. }
  37535. }
  37536. if (cs !== s) {
  37537. cs = s;
  37538. }
  37539. }
  37540. }
  37541. // indices
  37542. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37543. var s;
  37544. i = 0;
  37545. for (s = 0; s < subdivisions; s++) {
  37546. var i0 = 0;
  37547. var i1 = 0;
  37548. var i2 = 0;
  37549. var i3 = 0;
  37550. for (j = 0; j < tessellation; j++) {
  37551. i0 = i * (e + 1) + j;
  37552. i1 = (i + 1) * (e + 1) + j;
  37553. i2 = i * (e + 1) + (j + 1);
  37554. i3 = (i + 1) * (e + 1) + (j + 1);
  37555. indices.push(i0, i1, i2);
  37556. indices.push(i3, i2, i1);
  37557. }
  37558. if (arc !== 1 && enclose) { // if enclose, add two quads
  37559. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37560. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37561. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37562. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37563. }
  37564. i = (hasRings) ? (i + 2) : (i + 1);
  37565. }
  37566. // Caps
  37567. var createCylinderCap = function (isTop) {
  37568. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37569. if (radius === 0) {
  37570. return;
  37571. }
  37572. // Cap positions, normals & uvs
  37573. var angle;
  37574. var circleVector;
  37575. var i;
  37576. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37577. var c = null;
  37578. if (faceColors) {
  37579. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37580. }
  37581. // cap center
  37582. var vbase = positions.length / 3;
  37583. var offset = isTop ? height / 2 : -height / 2;
  37584. var center = new BABYLON.Vector3(0, offset, 0);
  37585. positions.push(center.x, center.y, center.z);
  37586. normals.push(0, isTop ? 1 : -1, 0);
  37587. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37588. if (c) {
  37589. colors.push(c.r, c.g, c.b, c.a);
  37590. }
  37591. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37592. for (i = 0; i <= tessellation; i++) {
  37593. angle = Math.PI * 2 * i * arc / tessellation;
  37594. var cos = Math.cos(-angle);
  37595. var sin = Math.sin(-angle);
  37596. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37597. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37598. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37599. normals.push(0, isTop ? 1 : -1, 0);
  37600. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37601. if (c) {
  37602. colors.push(c.r, c.g, c.b, c.a);
  37603. }
  37604. }
  37605. // Cap indices
  37606. for (i = 0; i < tessellation; i++) {
  37607. if (!isTop) {
  37608. indices.push(vbase);
  37609. indices.push(vbase + (i + 1));
  37610. indices.push(vbase + (i + 2));
  37611. }
  37612. else {
  37613. indices.push(vbase);
  37614. indices.push(vbase + (i + 2));
  37615. indices.push(vbase + (i + 1));
  37616. }
  37617. }
  37618. };
  37619. // add caps to geometry
  37620. createCylinderCap(false);
  37621. createCylinderCap(true);
  37622. // Sides
  37623. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37624. var vertexData = new VertexData();
  37625. vertexData.indices = indices;
  37626. vertexData.positions = positions;
  37627. vertexData.normals = normals;
  37628. vertexData.uvs = uvs;
  37629. if (faceColors) {
  37630. vertexData.colors = colors;
  37631. }
  37632. return vertexData;
  37633. };
  37634. /**
  37635. * Creates the VertexData for a torus
  37636. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37637. * * diameter the diameter of the torus, optional default 1
  37638. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37639. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37640. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37641. * * 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)
  37642. * * 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)
  37643. * @returns the VertexData of the torus
  37644. */
  37645. VertexData.CreateTorus = function (options) {
  37646. var indices = [];
  37647. var positions = [];
  37648. var normals = [];
  37649. var uvs = [];
  37650. var diameter = options.diameter || 1;
  37651. var thickness = options.thickness || 0.5;
  37652. var tessellation = options.tessellation || 16;
  37653. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37654. var stride = tessellation + 1;
  37655. for (var i = 0; i <= tessellation; i++) {
  37656. var u = i / tessellation;
  37657. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37658. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37659. for (var j = 0; j <= tessellation; j++) {
  37660. var v = 1 - j / tessellation;
  37661. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37662. var dx = Math.cos(innerAngle);
  37663. var dy = Math.sin(innerAngle);
  37664. // Create a vertex.
  37665. var normal = new BABYLON.Vector3(dx, dy, 0);
  37666. var position = normal.scale(thickness / 2);
  37667. var textureCoordinate = new BABYLON.Vector2(u, v);
  37668. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37669. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37670. positions.push(position.x, position.y, position.z);
  37671. normals.push(normal.x, normal.y, normal.z);
  37672. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37673. // And create indices for two triangles.
  37674. var nextI = (i + 1) % stride;
  37675. var nextJ = (j + 1) % stride;
  37676. indices.push(i * stride + j);
  37677. indices.push(i * stride + nextJ);
  37678. indices.push(nextI * stride + j);
  37679. indices.push(i * stride + nextJ);
  37680. indices.push(nextI * stride + nextJ);
  37681. indices.push(nextI * stride + j);
  37682. }
  37683. }
  37684. // Sides
  37685. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37686. // Result
  37687. var vertexData = new VertexData();
  37688. vertexData.indices = indices;
  37689. vertexData.positions = positions;
  37690. vertexData.normals = normals;
  37691. vertexData.uvs = uvs;
  37692. return vertexData;
  37693. };
  37694. /**
  37695. * Creates the VertexData of the LineSystem
  37696. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37697. * - lines an array of lines, each line being an array of successive Vector3
  37698. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37699. * @returns the VertexData of the LineSystem
  37700. */
  37701. VertexData.CreateLineSystem = function (options) {
  37702. var indices = [];
  37703. var positions = [];
  37704. var lines = options.lines;
  37705. var colors = options.colors;
  37706. var vertexColors = [];
  37707. var idx = 0;
  37708. for (var l = 0; l < lines.length; l++) {
  37709. var points = lines[l];
  37710. for (var index = 0; index < points.length; index++) {
  37711. positions.push(points[index].x, points[index].y, points[index].z);
  37712. if (colors) {
  37713. var color = colors[l];
  37714. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37715. }
  37716. if (index > 0) {
  37717. indices.push(idx - 1);
  37718. indices.push(idx);
  37719. }
  37720. idx++;
  37721. }
  37722. }
  37723. var vertexData = new VertexData();
  37724. vertexData.indices = indices;
  37725. vertexData.positions = positions;
  37726. if (colors) {
  37727. vertexData.colors = vertexColors;
  37728. }
  37729. return vertexData;
  37730. };
  37731. /**
  37732. * Create the VertexData for a DashedLines
  37733. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37734. * - points an array successive Vector3
  37735. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37736. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37737. * - dashNb the intended total number of dashes, optional, default 200
  37738. * @returns the VertexData for the DashedLines
  37739. */
  37740. VertexData.CreateDashedLines = function (options) {
  37741. var dashSize = options.dashSize || 3;
  37742. var gapSize = options.gapSize || 1;
  37743. var dashNb = options.dashNb || 200;
  37744. var points = options.points;
  37745. var positions = new Array();
  37746. var indices = new Array();
  37747. var curvect = BABYLON.Vector3.Zero();
  37748. var lg = 0;
  37749. var nb = 0;
  37750. var shft = 0;
  37751. var dashshft = 0;
  37752. var curshft = 0;
  37753. var idx = 0;
  37754. var i = 0;
  37755. for (i = 0; i < points.length - 1; i++) {
  37756. points[i + 1].subtractToRef(points[i], curvect);
  37757. lg += curvect.length();
  37758. }
  37759. shft = lg / dashNb;
  37760. dashshft = dashSize * shft / (dashSize + gapSize);
  37761. for (i = 0; i < points.length - 1; i++) {
  37762. points[i + 1].subtractToRef(points[i], curvect);
  37763. nb = Math.floor(curvect.length() / shft);
  37764. curvect.normalize();
  37765. for (var j = 0; j < nb; j++) {
  37766. curshft = shft * j;
  37767. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37768. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37769. indices.push(idx, idx + 1);
  37770. idx += 2;
  37771. }
  37772. }
  37773. // Result
  37774. var vertexData = new VertexData();
  37775. vertexData.positions = positions;
  37776. vertexData.indices = indices;
  37777. return vertexData;
  37778. };
  37779. /**
  37780. * Creates the VertexData for a Ground
  37781. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37782. * - width the width (x direction) of the ground, optional, default 1
  37783. * - height the height (z direction) of the ground, optional, default 1
  37784. * - subdivisions the number of subdivisions per side, optional, default 1
  37785. * @returns the VertexData of the Ground
  37786. */
  37787. VertexData.CreateGround = function (options) {
  37788. var indices = [];
  37789. var positions = [];
  37790. var normals = [];
  37791. var uvs = [];
  37792. var row, col;
  37793. var width = options.width || 1;
  37794. var height = options.height || 1;
  37795. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37796. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37797. for (row = 0; row <= subdivisionsY; row++) {
  37798. for (col = 0; col <= subdivisionsX; col++) {
  37799. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37800. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37801. positions.push(position.x, position.y, position.z);
  37802. normals.push(normal.x, normal.y, normal.z);
  37803. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37804. }
  37805. }
  37806. for (row = 0; row < subdivisionsY; row++) {
  37807. for (col = 0; col < subdivisionsX; col++) {
  37808. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37809. indices.push(col + 1 + row * (subdivisionsX + 1));
  37810. indices.push(col + row * (subdivisionsX + 1));
  37811. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37812. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37813. indices.push(col + row * (subdivisionsX + 1));
  37814. }
  37815. }
  37816. // Result
  37817. var vertexData = new VertexData();
  37818. vertexData.indices = indices;
  37819. vertexData.positions = positions;
  37820. vertexData.normals = normals;
  37821. vertexData.uvs = uvs;
  37822. return vertexData;
  37823. };
  37824. /**
  37825. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37826. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37827. * * xmin the ground minimum X coordinate, optional, default -1
  37828. * * zmin the ground minimum Z coordinate, optional, default -1
  37829. * * xmax the ground maximum X coordinate, optional, default 1
  37830. * * zmax the ground maximum Z coordinate, optional, default 1
  37831. * * 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}
  37832. * * 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}
  37833. * @returns the VertexData of the TiledGround
  37834. */
  37835. VertexData.CreateTiledGround = function (options) {
  37836. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37837. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37838. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37839. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37840. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37841. var precision = options.precision || { w: 1, h: 1 };
  37842. var indices = new Array();
  37843. var positions = new Array();
  37844. var normals = new Array();
  37845. var uvs = new Array();
  37846. var row, col, tileRow, tileCol;
  37847. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37848. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37849. precision.w = (precision.w < 1) ? 1 : precision.w;
  37850. precision.h = (precision.h < 1) ? 1 : precision.h;
  37851. var tileSize = {
  37852. 'w': (xmax - xmin) / subdivisions.w,
  37853. 'h': (zmax - zmin) / subdivisions.h
  37854. };
  37855. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37856. // Indices
  37857. var base = positions.length / 3;
  37858. var rowLength = precision.w + 1;
  37859. for (row = 0; row < precision.h; row++) {
  37860. for (col = 0; col < precision.w; col++) {
  37861. var square = [
  37862. base + col + row * rowLength,
  37863. base + (col + 1) + row * rowLength,
  37864. base + (col + 1) + (row + 1) * rowLength,
  37865. base + col + (row + 1) * rowLength
  37866. ];
  37867. indices.push(square[1]);
  37868. indices.push(square[2]);
  37869. indices.push(square[3]);
  37870. indices.push(square[0]);
  37871. indices.push(square[1]);
  37872. indices.push(square[3]);
  37873. }
  37874. }
  37875. // Position, normals and uvs
  37876. var position = BABYLON.Vector3.Zero();
  37877. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37878. for (row = 0; row <= precision.h; row++) {
  37879. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37880. for (col = 0; col <= precision.w; col++) {
  37881. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37882. position.y = 0;
  37883. positions.push(position.x, position.y, position.z);
  37884. normals.push(normal.x, normal.y, normal.z);
  37885. uvs.push(col / precision.w, row / precision.h);
  37886. }
  37887. }
  37888. }
  37889. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37890. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37891. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37892. }
  37893. }
  37894. // Result
  37895. var vertexData = new VertexData();
  37896. vertexData.indices = indices;
  37897. vertexData.positions = positions;
  37898. vertexData.normals = normals;
  37899. vertexData.uvs = uvs;
  37900. return vertexData;
  37901. };
  37902. /**
  37903. * Creates the VertexData of the Ground designed from a heightmap
  37904. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37905. * * width the width (x direction) of the ground
  37906. * * height the height (z direction) of the ground
  37907. * * subdivisions the number of subdivisions per side
  37908. * * minHeight the minimum altitude on the ground, optional, default 0
  37909. * * maxHeight the maximum altitude on the ground, optional default 1
  37910. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37911. * * buffer the array holding the image color data
  37912. * * bufferWidth the width of image
  37913. * * bufferHeight the height of image
  37914. * @returns the VertexData of the Ground designed from a heightmap
  37915. */
  37916. VertexData.CreateGroundFromHeightMap = function (options) {
  37917. var indices = [];
  37918. var positions = [];
  37919. var normals = [];
  37920. var uvs = [];
  37921. var row, col;
  37922. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37923. // Vertices
  37924. for (row = 0; row <= options.subdivisions; row++) {
  37925. for (col = 0; col <= options.subdivisions; col++) {
  37926. 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));
  37927. // Compute height
  37928. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37929. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37930. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37931. var r = options.buffer[pos] / 255.0;
  37932. var g = options.buffer[pos + 1] / 255.0;
  37933. var b = options.buffer[pos + 2] / 255.0;
  37934. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37935. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37936. // Add vertex
  37937. positions.push(position.x, position.y, position.z);
  37938. normals.push(0, 0, 0);
  37939. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37940. }
  37941. }
  37942. // Indices
  37943. for (row = 0; row < options.subdivisions; row++) {
  37944. for (col = 0; col < options.subdivisions; col++) {
  37945. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37946. indices.push(col + 1 + row * (options.subdivisions + 1));
  37947. indices.push(col + row * (options.subdivisions + 1));
  37948. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37949. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37950. indices.push(col + row * (options.subdivisions + 1));
  37951. }
  37952. }
  37953. // Normals
  37954. VertexData.ComputeNormals(positions, indices, normals);
  37955. // Result
  37956. var vertexData = new VertexData();
  37957. vertexData.indices = indices;
  37958. vertexData.positions = positions;
  37959. vertexData.normals = normals;
  37960. vertexData.uvs = uvs;
  37961. return vertexData;
  37962. };
  37963. /**
  37964. * Creates the VertexData for a Plane
  37965. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37966. * * size sets the width and height of the plane to the value of size, optional default 1
  37967. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37968. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37969. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37970. * * 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)
  37971. * * 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)
  37972. * @returns the VertexData of the box
  37973. */
  37974. VertexData.CreatePlane = function (options) {
  37975. var indices = [];
  37976. var positions = [];
  37977. var normals = [];
  37978. var uvs = [];
  37979. var width = options.width || options.size || 1;
  37980. var height = options.height || options.size || 1;
  37981. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37982. // Vertices
  37983. var halfWidth = width / 2.0;
  37984. var halfHeight = height / 2.0;
  37985. positions.push(-halfWidth, -halfHeight, 0);
  37986. normals.push(0, 0, -1.0);
  37987. uvs.push(0.0, 0.0);
  37988. positions.push(halfWidth, -halfHeight, 0);
  37989. normals.push(0, 0, -1.0);
  37990. uvs.push(1.0, 0.0);
  37991. positions.push(halfWidth, halfHeight, 0);
  37992. normals.push(0, 0, -1.0);
  37993. uvs.push(1.0, 1.0);
  37994. positions.push(-halfWidth, halfHeight, 0);
  37995. normals.push(0, 0, -1.0);
  37996. uvs.push(0.0, 1.0);
  37997. // Indices
  37998. indices.push(0);
  37999. indices.push(1);
  38000. indices.push(2);
  38001. indices.push(0);
  38002. indices.push(2);
  38003. indices.push(3);
  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. /**
  38015. * Creates the VertexData of the Disc or regular Polygon
  38016. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  38017. * * radius the radius of the disc, optional default 0.5
  38018. * * tessellation the number of polygon sides, optional, default 64
  38019. * * 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
  38020. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38021. * * 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)
  38022. * * 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)
  38023. * @returns the VertexData of the box
  38024. */
  38025. VertexData.CreateDisc = function (options) {
  38026. var positions = new Array();
  38027. var indices = new Array();
  38028. var normals = new Array();
  38029. var uvs = new Array();
  38030. var radius = options.radius || 0.5;
  38031. var tessellation = options.tessellation || 64;
  38032. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38033. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38034. // positions and uvs
  38035. positions.push(0, 0, 0); // disc center first
  38036. uvs.push(0.5, 0.5);
  38037. var theta = Math.PI * 2 * arc;
  38038. var step = theta / tessellation;
  38039. for (var a = 0; a < theta; a += step) {
  38040. var x = Math.cos(a);
  38041. var y = Math.sin(a);
  38042. var u = (x + 1) / 2;
  38043. var v = (1 - y) / 2;
  38044. positions.push(radius * x, radius * y, 0);
  38045. uvs.push(u, v);
  38046. }
  38047. if (arc === 1) {
  38048. positions.push(positions[3], positions[4], positions[5]); // close the circle
  38049. uvs.push(uvs[2], uvs[3]);
  38050. }
  38051. //indices
  38052. var vertexNb = positions.length / 3;
  38053. for (var i = 1; i < vertexNb - 1; i++) {
  38054. indices.push(i + 1, 0, i);
  38055. }
  38056. // result
  38057. VertexData.ComputeNormals(positions, indices, normals);
  38058. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38059. var vertexData = new VertexData();
  38060. vertexData.indices = indices;
  38061. vertexData.positions = positions;
  38062. vertexData.normals = normals;
  38063. vertexData.uvs = uvs;
  38064. return vertexData;
  38065. };
  38066. /**
  38067. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  38068. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  38069. * @param polygon a mesh built from polygonTriangulation.build()
  38070. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38071. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38072. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38073. * @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)
  38074. * @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)
  38075. * @returns the VertexData of the Polygon
  38076. */
  38077. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  38078. var faceUV = fUV || new Array(3);
  38079. var faceColors = fColors;
  38080. var colors = [];
  38081. // default face colors and UV if undefined
  38082. for (var f = 0; f < 3; f++) {
  38083. if (faceUV[f] === undefined) {
  38084. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38085. }
  38086. if (faceColors && faceColors[f] === undefined) {
  38087. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38088. }
  38089. }
  38090. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38091. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38092. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38093. var indices = polygon.getIndices();
  38094. // set face colours and textures
  38095. var idx = 0;
  38096. var face = 0;
  38097. for (var index = 0; index < normals.length; index += 3) {
  38098. //Edge Face no. 1
  38099. if (Math.abs(normals[index + 1]) < 0.001) {
  38100. face = 1;
  38101. }
  38102. //Top Face no. 0
  38103. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  38104. face = 0;
  38105. }
  38106. //Bottom Face no. 2
  38107. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  38108. face = 2;
  38109. }
  38110. idx = index / 3;
  38111. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  38112. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  38113. if (faceColors) {
  38114. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  38115. }
  38116. }
  38117. // sides
  38118. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  38119. // Result
  38120. var vertexData = new VertexData();
  38121. vertexData.indices = indices;
  38122. vertexData.positions = positions;
  38123. vertexData.normals = normals;
  38124. vertexData.uvs = uvs;
  38125. if (faceColors) {
  38126. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38127. vertexData.colors = totalColors;
  38128. }
  38129. return vertexData;
  38130. };
  38131. /**
  38132. * Creates the VertexData of the IcoSphere
  38133. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38134. * * radius the radius of the IcoSphere, optional default 1
  38135. * * radiusX allows stretching in the x direction, optional, default radius
  38136. * * radiusY allows stretching in the y direction, optional, default radius
  38137. * * radiusZ allows stretching in the z direction, optional, default radius
  38138. * * flat when true creates a flat shaded mesh, optional, default true
  38139. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38140. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38141. * * 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)
  38142. * * 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)
  38143. * @returns the VertexData of the IcoSphere
  38144. */
  38145. VertexData.CreateIcoSphere = function (options) {
  38146. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38147. var radius = options.radius || 1;
  38148. var flat = (options.flat === undefined) ? true : options.flat;
  38149. var subdivisions = options.subdivisions || 4;
  38150. var radiusX = options.radiusX || radius;
  38151. var radiusY = options.radiusY || radius;
  38152. var radiusZ = options.radiusZ || radius;
  38153. var t = (1 + Math.sqrt(5)) / 2;
  38154. // 12 vertex x,y,z
  38155. var ico_vertices = [
  38156. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38157. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38158. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38159. ];
  38160. // index of 3 vertex makes a face of icopshere
  38161. var ico_indices = [
  38162. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38163. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38164. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38165. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38166. ];
  38167. // vertex for uv have aliased position, not for UV
  38168. var vertices_unalias_id = [
  38169. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38170. // vertex alias
  38171. 0,
  38172. 2,
  38173. 3,
  38174. 3,
  38175. 3,
  38176. 4,
  38177. 7,
  38178. 8,
  38179. 9,
  38180. 9,
  38181. 10,
  38182. 11 // 23: B + 12
  38183. ];
  38184. // uv as integer step (not pixels !)
  38185. var ico_vertexuv = [
  38186. 5, 1, 3, 1, 6, 4, 0, 0,
  38187. 5, 3, 4, 2, 2, 2, 4, 0,
  38188. 2, 0, 1, 1, 6, 0, 6, 2,
  38189. // vertex alias (for same vertex on different faces)
  38190. 0, 4,
  38191. 3, 3,
  38192. 4, 4,
  38193. 3, 1,
  38194. 4, 2,
  38195. 4, 4,
  38196. 0, 2,
  38197. 1, 1,
  38198. 2, 2,
  38199. 3, 3,
  38200. 1, 3,
  38201. 2, 4 // 23: B + 12
  38202. ];
  38203. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38204. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38205. // First island of uv mapping
  38206. // v = 4h 3+ 2
  38207. // v = 3h 9+ 4
  38208. // v = 2h 9+ 5 B
  38209. // v = 1h 9 1 0
  38210. // v = 0h 3 8 7 A
  38211. // u = 0 1 2 3 4 5 6 *a
  38212. // Second island of uv mapping
  38213. // v = 4h 0+ B+ 4+
  38214. // v = 3h A+ 2+
  38215. // v = 2h 7+ 6 3+
  38216. // v = 1h 8+ 3+
  38217. // v = 0h
  38218. // u = 0 1 2 3 4 5 6 *a
  38219. // Face layout on texture UV mapping
  38220. // ============
  38221. // \ 4 /\ 16 / ======
  38222. // \ / \ / /\ 11 /
  38223. // \/ 7 \/ / \ /
  38224. // ======= / 10 \/
  38225. // /\ 17 /\ =======
  38226. // / \ / \ \ 15 /\
  38227. // / 8 \/ 12 \ \ / \
  38228. // ============ \/ 6 \
  38229. // \ 18 /\ ============
  38230. // \ / \ \ 5 /\ 0 /
  38231. // \/ 13 \ \ / \ /
  38232. // ======= \/ 1 \/
  38233. // =============
  38234. // /\ 19 /\ 2 /\
  38235. // / \ / \ / \
  38236. // / 14 \/ 9 \/ 3 \
  38237. // ===================
  38238. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38239. var ustep = 138 / 1024;
  38240. var vstep = 239 / 1024;
  38241. var uoffset = 60 / 1024;
  38242. var voffset = 26 / 1024;
  38243. // Second island should have margin, not to touch the first island
  38244. // avoid any borderline artefact in pixel rounding
  38245. var island_u_offset = -40 / 1024;
  38246. var island_v_offset = +20 / 1024;
  38247. // face is either island 0 or 1 :
  38248. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38249. var island = [
  38250. 0, 0, 0, 0, 1,
  38251. 0, 0, 1, 1, 0,
  38252. 0, 0, 1, 1, 0,
  38253. 0, 1, 1, 1, 0 // 15 - 19
  38254. ];
  38255. var indices = new Array();
  38256. var positions = new Array();
  38257. var normals = new Array();
  38258. var uvs = new Array();
  38259. var current_indice = 0;
  38260. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38261. var face_vertex_pos = new Array(3);
  38262. var face_vertex_uv = new Array(3);
  38263. var v012;
  38264. for (v012 = 0; v012 < 3; v012++) {
  38265. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38266. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38267. }
  38268. // create all with normals
  38269. for (var face = 0; face < 20; face++) {
  38270. // 3 vertex per face
  38271. for (v012 = 0; v012 < 3; v012++) {
  38272. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38273. var v_id = ico_indices[3 * face + v012];
  38274. // vertex have 3D position (x,y,z)
  38275. 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]);
  38276. // Normalize to get normal, then scale to radius
  38277. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38278. // uv Coordinates from vertex ID
  38279. 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);
  38280. }
  38281. // Subdivide the face (interpolate pos, norm, uv)
  38282. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38283. // - norm is linear interpolation of vertex corner normal
  38284. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38285. // - uv is linear interpolation
  38286. //
  38287. // Topology is as below for sub-divide by 2
  38288. // vertex shown as v0,v1,v2
  38289. // interp index is i1 to progress in range [v0,v1[
  38290. // interp index is i2 to progress in range [v0,v2[
  38291. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38292. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38293. //
  38294. //
  38295. // i2 v2
  38296. // ^ ^
  38297. // / / \
  38298. // / / \
  38299. // / / \
  38300. // / / (0,1) \
  38301. // / #---------\
  38302. // / / \ (0,0)'/ \
  38303. // / / \ / \
  38304. // / / \ / \
  38305. // / / (0,0) \ / (1,0) \
  38306. // / #---------#---------\
  38307. // v0 v1
  38308. //
  38309. // --------------------> i1
  38310. //
  38311. // interp of (i1,i2):
  38312. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38313. // along i1 : lerp(x0,x1, i1/(S-i2))
  38314. //
  38315. // centroid of triangle is needed to get help normal computation
  38316. // (c1,c2) are used for centroid location
  38317. var interp_vertex = function (i1, i2, c1, c2) {
  38318. // vertex is interpolated from
  38319. // - face_vertex_pos[0..2]
  38320. // - face_vertex_uv[0..2]
  38321. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38322. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38323. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38324. pos_interp.normalize();
  38325. var vertex_normal;
  38326. if (flat) {
  38327. // in flat mode, recalculate normal as face centroid normal
  38328. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38329. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38330. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38331. }
  38332. else {
  38333. // in smooth mode, recalculate normal from each single vertex position
  38334. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38335. }
  38336. // Vertex normal need correction due to X,Y,Z radius scaling
  38337. vertex_normal.x /= radiusX;
  38338. vertex_normal.y /= radiusY;
  38339. vertex_normal.z /= radiusZ;
  38340. vertex_normal.normalize();
  38341. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38342. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38343. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38344. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38345. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38346. uvs.push(uv_interp.x, uv_interp.y);
  38347. // push each vertex has member of a face
  38348. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38349. indices.push(current_indice);
  38350. current_indice++;
  38351. };
  38352. for (var i2 = 0; i2 < subdivisions; i2++) {
  38353. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38354. // face : (i1,i2) for /\ :
  38355. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38356. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38357. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38358. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38359. if (i1 + i2 + 1 < subdivisions) {
  38360. // face : (i1,i2)' for \/ :
  38361. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38362. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38363. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38364. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38365. }
  38366. }
  38367. }
  38368. }
  38369. // Sides
  38370. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38371. // Result
  38372. var vertexData = new VertexData();
  38373. vertexData.indices = indices;
  38374. vertexData.positions = positions;
  38375. vertexData.normals = normals;
  38376. vertexData.uvs = uvs;
  38377. return vertexData;
  38378. };
  38379. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38380. /**
  38381. * Creates the VertexData for a Polyhedron
  38382. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38383. * * type provided types are:
  38384. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38385. * * 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)
  38386. * * size the size of the IcoSphere, optional default 1
  38387. * * sizeX allows stretching in the x direction, optional, default size
  38388. * * sizeY allows stretching in the y direction, optional, default size
  38389. * * sizeZ allows stretching in the z direction, optional, default size
  38390. * * 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
  38391. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38392. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38393. * * flat when true creates a flat shaded mesh, optional, default true
  38394. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38395. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38396. * * 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)
  38397. * * 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)
  38398. * @returns the VertexData of the Polyhedron
  38399. */
  38400. VertexData.CreatePolyhedron = function (options) {
  38401. // provided polyhedron types :
  38402. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38403. // 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)
  38404. var polyhedra = [];
  38405. 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]] };
  38406. 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]] };
  38407. polyhedra[2] = {
  38408. 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]],
  38409. 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]]
  38410. };
  38411. polyhedra[3] = {
  38412. 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]],
  38413. 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]]
  38414. };
  38415. polyhedra[4] = {
  38416. 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]],
  38417. 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]]
  38418. };
  38419. 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]] };
  38420. 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]] };
  38421. 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]] };
  38422. 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]] };
  38423. 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]] };
  38424. 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]] };
  38425. 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]] };
  38426. 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]] };
  38427. 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]] };
  38428. polyhedra[14] = {
  38429. 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]],
  38430. 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]]
  38431. };
  38432. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38433. var size = options.size;
  38434. var sizeX = options.sizeX || size || 1;
  38435. var sizeY = options.sizeY || size || 1;
  38436. var sizeZ = options.sizeZ || size || 1;
  38437. var data = options.custom || polyhedra[type];
  38438. var nbfaces = data.face.length;
  38439. var faceUV = options.faceUV || new Array(nbfaces);
  38440. var faceColors = options.faceColors;
  38441. var flat = (options.flat === undefined) ? true : options.flat;
  38442. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38443. var positions = new Array();
  38444. var indices = new Array();
  38445. var normals = new Array();
  38446. var uvs = new Array();
  38447. var colors = new Array();
  38448. var index = 0;
  38449. var faceIdx = 0; // face cursor in the array "indexes"
  38450. var indexes = new Array();
  38451. var i = 0;
  38452. var f = 0;
  38453. var u, v, ang, x, y, tmp;
  38454. // default face colors and UV if undefined
  38455. if (flat) {
  38456. for (f = 0; f < nbfaces; f++) {
  38457. if (faceColors && faceColors[f] === undefined) {
  38458. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38459. }
  38460. if (faceUV && faceUV[f] === undefined) {
  38461. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38462. }
  38463. }
  38464. }
  38465. if (!flat) {
  38466. for (i = 0; i < data.vertex.length; i++) {
  38467. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38468. uvs.push(0, 0);
  38469. }
  38470. for (f = 0; f < nbfaces; f++) {
  38471. for (i = 0; i < data.face[f].length - 2; i++) {
  38472. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38473. }
  38474. }
  38475. }
  38476. else {
  38477. for (f = 0; f < nbfaces; f++) {
  38478. var fl = data.face[f].length; // number of vertices of the current face
  38479. ang = 2 * Math.PI / fl;
  38480. x = 0.5 * Math.tan(ang / 2);
  38481. y = 0.5;
  38482. // positions, uvs, colors
  38483. for (i = 0; i < fl; i++) {
  38484. // positions
  38485. 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);
  38486. indexes.push(index);
  38487. index++;
  38488. // uvs
  38489. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38490. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38491. uvs.push(u, v);
  38492. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38493. y = x * Math.sin(ang) + y * Math.cos(ang);
  38494. x = tmp;
  38495. // colors
  38496. if (faceColors) {
  38497. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38498. }
  38499. }
  38500. // indices from indexes
  38501. for (i = 0; i < fl - 2; i++) {
  38502. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38503. }
  38504. faceIdx += fl;
  38505. }
  38506. }
  38507. VertexData.ComputeNormals(positions, indices, normals);
  38508. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38509. var vertexData = new VertexData();
  38510. vertexData.positions = positions;
  38511. vertexData.indices = indices;
  38512. vertexData.normals = normals;
  38513. vertexData.uvs = uvs;
  38514. if (faceColors && flat) {
  38515. vertexData.colors = colors;
  38516. }
  38517. return vertexData;
  38518. };
  38519. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38520. /**
  38521. * Creates the VertexData for a TorusKnot
  38522. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38523. * * radius the radius of the torus knot, optional, default 2
  38524. * * tube the thickness of the tube, optional, default 0.5
  38525. * * radialSegments the number of sides on each tube segments, optional, default 32
  38526. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38527. * * p the number of windings around the z axis, optional, default 2
  38528. * * q the number of windings around the x axis, optional, default 3
  38529. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38530. * * 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)
  38531. * * 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)
  38532. * @returns the VertexData of the Torus Knot
  38533. */
  38534. VertexData.CreateTorusKnot = function (options) {
  38535. var indices = new Array();
  38536. var positions = new Array();
  38537. var normals = new Array();
  38538. var uvs = new Array();
  38539. var radius = options.radius || 2;
  38540. var tube = options.tube || 0.5;
  38541. var radialSegments = options.radialSegments || 32;
  38542. var tubularSegments = options.tubularSegments || 32;
  38543. var p = options.p || 2;
  38544. var q = options.q || 3;
  38545. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38546. // Helper
  38547. var getPos = function (angle) {
  38548. var cu = Math.cos(angle);
  38549. var su = Math.sin(angle);
  38550. var quOverP = q / p * angle;
  38551. var cs = Math.cos(quOverP);
  38552. var tx = radius * (2 + cs) * 0.5 * cu;
  38553. var ty = radius * (2 + cs) * su * 0.5;
  38554. var tz = radius * Math.sin(quOverP) * 0.5;
  38555. return new BABYLON.Vector3(tx, ty, tz);
  38556. };
  38557. // Vertices
  38558. var i;
  38559. var j;
  38560. for (i = 0; i <= radialSegments; i++) {
  38561. var modI = i % radialSegments;
  38562. var u = modI / radialSegments * 2 * p * Math.PI;
  38563. var p1 = getPos(u);
  38564. var p2 = getPos(u + 0.01);
  38565. var tang = p2.subtract(p1);
  38566. var n = p2.add(p1);
  38567. var bitan = BABYLON.Vector3.Cross(tang, n);
  38568. n = BABYLON.Vector3.Cross(bitan, tang);
  38569. bitan.normalize();
  38570. n.normalize();
  38571. for (j = 0; j < tubularSegments; j++) {
  38572. var modJ = j % tubularSegments;
  38573. var v = modJ / tubularSegments * 2 * Math.PI;
  38574. var cx = -tube * Math.cos(v);
  38575. var cy = tube * Math.sin(v);
  38576. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38577. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38578. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38579. uvs.push(i / radialSegments);
  38580. uvs.push(j / tubularSegments);
  38581. }
  38582. }
  38583. for (i = 0; i < radialSegments; i++) {
  38584. for (j = 0; j < tubularSegments; j++) {
  38585. var jNext = (j + 1) % tubularSegments;
  38586. var a = i * tubularSegments + j;
  38587. var b = (i + 1) * tubularSegments + j;
  38588. var c = (i + 1) * tubularSegments + jNext;
  38589. var d = i * tubularSegments + jNext;
  38590. indices.push(d);
  38591. indices.push(b);
  38592. indices.push(a);
  38593. indices.push(d);
  38594. indices.push(c);
  38595. indices.push(b);
  38596. }
  38597. }
  38598. // Normals
  38599. VertexData.ComputeNormals(positions, indices, normals);
  38600. // Sides
  38601. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38602. // Result
  38603. var vertexData = new VertexData();
  38604. vertexData.indices = indices;
  38605. vertexData.positions = positions;
  38606. vertexData.normals = normals;
  38607. vertexData.uvs = uvs;
  38608. return vertexData;
  38609. };
  38610. // Tools
  38611. /**
  38612. * Compute normals for given positions and indices
  38613. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38614. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38615. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38616. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38617. * * facetNormals : optional array of facet normals (vector3)
  38618. * * facetPositions : optional array of facet positions (vector3)
  38619. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38620. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38621. * * bInfo : optional bounding info, required for facetPartitioning computation
  38622. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38623. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38624. * * useRightHandedSystem: optional boolean to for right handed system computation
  38625. * * depthSort : optional boolean to enable the facet depth sort computation
  38626. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38627. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38628. */
  38629. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38630. // temporary scalar variables
  38631. var index = 0; // facet index
  38632. var p1p2x = 0.0; // p1p2 vector x coordinate
  38633. var p1p2y = 0.0; // p1p2 vector y coordinate
  38634. var p1p2z = 0.0; // p1p2 vector z coordinate
  38635. var p3p2x = 0.0; // p3p2 vector x coordinate
  38636. var p3p2y = 0.0; // p3p2 vector y coordinate
  38637. var p3p2z = 0.0; // p3p2 vector z coordinate
  38638. var faceNormalx = 0.0; // facet normal x coordinate
  38639. var faceNormaly = 0.0; // facet normal y coordinate
  38640. var faceNormalz = 0.0; // facet normal z coordinate
  38641. var length = 0.0; // facet normal length before normalization
  38642. var v1x = 0; // vector1 x index in the positions array
  38643. var v1y = 0; // vector1 y index in the positions array
  38644. var v1z = 0; // vector1 z index in the positions array
  38645. var v2x = 0; // vector2 x index in the positions array
  38646. var v2y = 0; // vector2 y index in the positions array
  38647. var v2z = 0; // vector2 z index in the positions array
  38648. var v3x = 0; // vector3 x index in the positions array
  38649. var v3y = 0; // vector3 y index in the positions array
  38650. var v3z = 0; // vector3 z index in the positions array
  38651. var computeFacetNormals = false;
  38652. var computeFacetPositions = false;
  38653. var computeFacetPartitioning = false;
  38654. var computeDepthSort = false;
  38655. var faceNormalSign = 1;
  38656. var ratio = 0;
  38657. var distanceTo = null;
  38658. if (options) {
  38659. computeFacetNormals = (options.facetNormals) ? true : false;
  38660. computeFacetPositions = (options.facetPositions) ? true : false;
  38661. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38662. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38663. ratio = options.ratio || 0;
  38664. computeDepthSort = (options.depthSort) ? true : false;
  38665. distanceTo = (options.distanceTo);
  38666. if (computeDepthSort) {
  38667. if (distanceTo === undefined) {
  38668. distanceTo = BABYLON.Vector3.Zero();
  38669. }
  38670. var depthSortedFacets = options.depthSortedFacets;
  38671. }
  38672. }
  38673. // facetPartitioning reinit if needed
  38674. var xSubRatio = 0;
  38675. var ySubRatio = 0;
  38676. var zSubRatio = 0;
  38677. var subSq = 0;
  38678. if (computeFacetPartitioning && options && options.bbSize) {
  38679. var ox = 0; // X partitioning index for facet position
  38680. var oy = 0; // Y partinioning index for facet position
  38681. var oz = 0; // Z partinioning index for facet position
  38682. var b1x = 0; // X partitioning index for facet v1 vertex
  38683. var b1y = 0; // Y partitioning index for facet v1 vertex
  38684. var b1z = 0; // z partitioning index for facet v1 vertex
  38685. var b2x = 0; // X partitioning index for facet v2 vertex
  38686. var b2y = 0; // Y partitioning index for facet v2 vertex
  38687. var b2z = 0; // Z partitioning index for facet v2 vertex
  38688. var b3x = 0; // X partitioning index for facet v3 vertex
  38689. var b3y = 0; // Y partitioning index for facet v3 vertex
  38690. var b3z = 0; // Z partitioning index for facet v3 vertex
  38691. var block_idx_o = 0; // facet barycenter block index
  38692. var block_idx_v1 = 0; // v1 vertex block index
  38693. var block_idx_v2 = 0; // v2 vertex block index
  38694. var block_idx_v3 = 0; // v3 vertex block index
  38695. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38696. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38697. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38698. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38699. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38700. subSq = options.subDiv.max * options.subDiv.max;
  38701. options.facetPartitioning.length = 0;
  38702. }
  38703. // reset the normals
  38704. for (index = 0; index < positions.length; index++) {
  38705. normals[index] = 0.0;
  38706. }
  38707. // Loop : 1 indice triplet = 1 facet
  38708. var nbFaces = (indices.length / 3) | 0;
  38709. for (index = 0; index < nbFaces; index++) {
  38710. // get the indexes of the coordinates of each vertex of the facet
  38711. v1x = indices[index * 3] * 3;
  38712. v1y = v1x + 1;
  38713. v1z = v1x + 2;
  38714. v2x = indices[index * 3 + 1] * 3;
  38715. v2y = v2x + 1;
  38716. v2z = v2x + 2;
  38717. v3x = indices[index * 3 + 2] * 3;
  38718. v3y = v3x + 1;
  38719. v3z = v3x + 2;
  38720. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38721. p1p2y = positions[v1y] - positions[v2y];
  38722. p1p2z = positions[v1z] - positions[v2z];
  38723. p3p2x = positions[v3x] - positions[v2x];
  38724. p3p2y = positions[v3y] - positions[v2y];
  38725. p3p2z = positions[v3z] - positions[v2z];
  38726. // compute the face normal with the cross product
  38727. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38728. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38729. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38730. // normalize this normal and store it in the array facetData
  38731. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38732. length = (length === 0) ? 1.0 : length;
  38733. faceNormalx /= length;
  38734. faceNormaly /= length;
  38735. faceNormalz /= length;
  38736. if (computeFacetNormals && options) {
  38737. options.facetNormals[index].x = faceNormalx;
  38738. options.facetNormals[index].y = faceNormaly;
  38739. options.facetNormals[index].z = faceNormalz;
  38740. }
  38741. if (computeFacetPositions && options) {
  38742. // compute and the facet barycenter coordinates in the array facetPositions
  38743. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38744. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38745. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38746. }
  38747. if (computeFacetPartitioning && options) {
  38748. // store the facet indexes in arrays in the main facetPartitioning array :
  38749. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38750. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38751. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38752. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38753. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38754. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38755. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38756. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38757. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38758. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38759. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38760. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38761. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38762. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38763. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38764. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38765. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38766. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38767. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38768. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38769. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38770. // push each facet index in each block containing the vertex
  38771. options.facetPartitioning[block_idx_v1].push(index);
  38772. if (block_idx_v2 != block_idx_v1) {
  38773. options.facetPartitioning[block_idx_v2].push(index);
  38774. }
  38775. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38776. options.facetPartitioning[block_idx_v3].push(index);
  38777. }
  38778. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38779. options.facetPartitioning[block_idx_o].push(index);
  38780. }
  38781. }
  38782. if (computeDepthSort && options && options.facetPositions) {
  38783. var dsf = depthSortedFacets[index];
  38784. dsf.ind = index * 3;
  38785. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38786. }
  38787. // compute the normals anyway
  38788. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38789. normals[v1y] += faceNormaly;
  38790. normals[v1z] += faceNormalz;
  38791. normals[v2x] += faceNormalx;
  38792. normals[v2y] += faceNormaly;
  38793. normals[v2z] += faceNormalz;
  38794. normals[v3x] += faceNormalx;
  38795. normals[v3y] += faceNormaly;
  38796. normals[v3z] += faceNormalz;
  38797. }
  38798. // last normalization of each normal
  38799. for (index = 0; index < normals.length / 3; index++) {
  38800. faceNormalx = normals[index * 3];
  38801. faceNormaly = normals[index * 3 + 1];
  38802. faceNormalz = normals[index * 3 + 2];
  38803. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38804. length = (length === 0) ? 1.0 : length;
  38805. faceNormalx /= length;
  38806. faceNormaly /= length;
  38807. faceNormalz /= length;
  38808. normals[index * 3] = faceNormalx;
  38809. normals[index * 3 + 1] = faceNormaly;
  38810. normals[index * 3 + 2] = faceNormalz;
  38811. }
  38812. };
  38813. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38814. var li = indices.length;
  38815. var ln = normals.length;
  38816. var i;
  38817. var n;
  38818. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38819. switch (sideOrientation) {
  38820. case BABYLON.Mesh.FRONTSIDE:
  38821. // nothing changed
  38822. break;
  38823. case BABYLON.Mesh.BACKSIDE:
  38824. var tmp;
  38825. // indices
  38826. for (i = 0; i < li; i += 3) {
  38827. tmp = indices[i];
  38828. indices[i] = indices[i + 2];
  38829. indices[i + 2] = tmp;
  38830. }
  38831. // normals
  38832. for (n = 0; n < ln; n++) {
  38833. normals[n] = -normals[n];
  38834. }
  38835. break;
  38836. case BABYLON.Mesh.DOUBLESIDE:
  38837. // positions
  38838. var lp = positions.length;
  38839. var l = lp / 3;
  38840. for (var p = 0; p < lp; p++) {
  38841. positions[lp + p] = positions[p];
  38842. }
  38843. // indices
  38844. for (i = 0; i < li; i += 3) {
  38845. indices[i + li] = indices[i + 2] + l;
  38846. indices[i + 1 + li] = indices[i + 1] + l;
  38847. indices[i + 2 + li] = indices[i] + l;
  38848. }
  38849. // normals
  38850. for (n = 0; n < ln; n++) {
  38851. normals[ln + n] = -normals[n];
  38852. }
  38853. // uvs
  38854. var lu = uvs.length;
  38855. var u = 0;
  38856. for (u = 0; u < lu; u++) {
  38857. uvs[u + lu] = uvs[u];
  38858. }
  38859. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38860. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38861. u = 0;
  38862. for (i = 0; i < lu / 2; i++) {
  38863. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38864. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38865. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38866. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38867. u += 2;
  38868. }
  38869. break;
  38870. }
  38871. };
  38872. /**
  38873. * Applies VertexData created from the imported parameters to the geometry
  38874. * @param parsedVertexData the parsed data from an imported file
  38875. * @param geometry the geometry to apply the VertexData to
  38876. */
  38877. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38878. var vertexData = new VertexData();
  38879. // positions
  38880. var positions = parsedVertexData.positions;
  38881. if (positions) {
  38882. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38883. }
  38884. // normals
  38885. var normals = parsedVertexData.normals;
  38886. if (normals) {
  38887. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38888. }
  38889. // tangents
  38890. var tangents = parsedVertexData.tangents;
  38891. if (tangents) {
  38892. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38893. }
  38894. // uvs
  38895. var uvs = parsedVertexData.uvs;
  38896. if (uvs) {
  38897. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38898. }
  38899. // uv2s
  38900. var uv2s = parsedVertexData.uv2s;
  38901. if (uv2s) {
  38902. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38903. }
  38904. // uv3s
  38905. var uv3s = parsedVertexData.uv3s;
  38906. if (uv3s) {
  38907. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38908. }
  38909. // uv4s
  38910. var uv4s = parsedVertexData.uv4s;
  38911. if (uv4s) {
  38912. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38913. }
  38914. // uv5s
  38915. var uv5s = parsedVertexData.uv5s;
  38916. if (uv5s) {
  38917. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38918. }
  38919. // uv6s
  38920. var uv6s = parsedVertexData.uv6s;
  38921. if (uv6s) {
  38922. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38923. }
  38924. // colors
  38925. var colors = parsedVertexData.colors;
  38926. if (colors) {
  38927. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38928. }
  38929. // matricesIndices
  38930. var matricesIndices = parsedVertexData.matricesIndices;
  38931. if (matricesIndices) {
  38932. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38933. }
  38934. // matricesWeights
  38935. var matricesWeights = parsedVertexData.matricesWeights;
  38936. if (matricesWeights) {
  38937. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38938. }
  38939. // indices
  38940. var indices = parsedVertexData.indices;
  38941. if (indices) {
  38942. vertexData.indices = indices;
  38943. }
  38944. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38945. };
  38946. return VertexData;
  38947. }());
  38948. BABYLON.VertexData = VertexData;
  38949. })(BABYLON || (BABYLON = {}));
  38950. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38951. var BABYLON;
  38952. (function (BABYLON) {
  38953. /**
  38954. * Class used to store geometry data (vertex buffers + index buffer)
  38955. */
  38956. var Geometry = /** @class */ (function () {
  38957. /**
  38958. * Creates a new geometry
  38959. * @param id defines the unique ID
  38960. * @param scene defines the hosting scene
  38961. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38962. * @param updatable defines if geometry must be updatable (false by default)
  38963. * @param mesh defines the mesh that will be associated with the geometry
  38964. */
  38965. function Geometry(id, scene, vertexData, updatable, mesh) {
  38966. if (updatable === void 0) { updatable = false; }
  38967. if (mesh === void 0) { mesh = null; }
  38968. /**
  38969. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38970. */
  38971. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38972. this._totalVertices = 0;
  38973. this._isDisposed = false;
  38974. this._indexBufferIsUpdatable = false;
  38975. this.id = id;
  38976. this._engine = scene.getEngine();
  38977. this._meshes = [];
  38978. this._scene = scene;
  38979. //Init vertex buffer cache
  38980. this._vertexBuffers = {};
  38981. this._indices = [];
  38982. this._updatable = updatable;
  38983. // vertexData
  38984. if (vertexData) {
  38985. this.setAllVerticesData(vertexData, updatable);
  38986. }
  38987. else {
  38988. this._totalVertices = 0;
  38989. this._indices = [];
  38990. }
  38991. if (this._engine.getCaps().vertexArrayObject) {
  38992. this._vertexArrayObjects = {};
  38993. }
  38994. // applyToMesh
  38995. if (mesh) {
  38996. if (mesh.getClassName() === "LinesMesh") {
  38997. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38998. this._updateExtend();
  38999. }
  39000. this.applyToMesh(mesh);
  39001. mesh.computeWorldMatrix(true);
  39002. }
  39003. }
  39004. Object.defineProperty(Geometry.prototype, "boundingBias", {
  39005. /**
  39006. * 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
  39007. */
  39008. get: function () {
  39009. return this._boundingBias;
  39010. },
  39011. /**
  39012. * 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
  39013. */
  39014. set: function (value) {
  39015. if (this._boundingBias && this._boundingBias.equals(value)) {
  39016. return;
  39017. }
  39018. this._boundingBias = value.clone();
  39019. this._updateBoundingInfo(true, null);
  39020. },
  39021. enumerable: true,
  39022. configurable: true
  39023. });
  39024. /**
  39025. * Static function used to attach a new empty geometry to a mesh
  39026. * @param mesh defines the mesh to attach the geometry to
  39027. * @returns the new {BABYLON.Geometry}
  39028. */
  39029. Geometry.CreateGeometryForMesh = function (mesh) {
  39030. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  39031. geometry.applyToMesh(mesh);
  39032. return geometry;
  39033. };
  39034. Object.defineProperty(Geometry.prototype, "extend", {
  39035. /**
  39036. * Gets the current extend of the geometry
  39037. */
  39038. get: function () {
  39039. return this._extend;
  39040. },
  39041. enumerable: true,
  39042. configurable: true
  39043. });
  39044. /**
  39045. * Gets the hosting scene
  39046. * @returns the hosting {BABYLON.Scene}
  39047. */
  39048. Geometry.prototype.getScene = function () {
  39049. return this._scene;
  39050. };
  39051. /**
  39052. * Gets the hosting engine
  39053. * @returns the hosting {BABYLON.Engine}
  39054. */
  39055. Geometry.prototype.getEngine = function () {
  39056. return this._engine;
  39057. };
  39058. /**
  39059. * Defines if the geometry is ready to use
  39060. * @returns true if the geometry is ready to be used
  39061. */
  39062. Geometry.prototype.isReady = function () {
  39063. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  39064. };
  39065. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  39066. /**
  39067. * Gets a value indicating that the geometry should not be serialized
  39068. */
  39069. get: function () {
  39070. for (var index = 0; index < this._meshes.length; index++) {
  39071. if (!this._meshes[index].doNotSerialize) {
  39072. return false;
  39073. }
  39074. }
  39075. return true;
  39076. },
  39077. enumerable: true,
  39078. configurable: true
  39079. });
  39080. /** @hidden */
  39081. Geometry.prototype._rebuild = function () {
  39082. if (this._vertexArrayObjects) {
  39083. this._vertexArrayObjects = {};
  39084. }
  39085. // Index buffer
  39086. if (this._meshes.length !== 0 && this._indices) {
  39087. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39088. }
  39089. // Vertex buffers
  39090. for (var key in this._vertexBuffers) {
  39091. var vertexBuffer = this._vertexBuffers[key];
  39092. vertexBuffer._rebuild();
  39093. }
  39094. };
  39095. /**
  39096. * Affects all geometry data in one call
  39097. * @param vertexData defines the geometry data
  39098. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  39099. */
  39100. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39101. vertexData.applyToGeometry(this, updatable);
  39102. this.notifyUpdate();
  39103. };
  39104. /**
  39105. * Set specific vertex data
  39106. * @param kind defines the data kind (Position, normal, etc...)
  39107. * @param data defines the vertex data to use
  39108. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  39109. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  39110. */
  39111. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39112. if (updatable === void 0) { updatable = false; }
  39113. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39114. this.setVerticesBuffer(buffer);
  39115. };
  39116. /**
  39117. * Removes a specific vertex data
  39118. * @param kind defines the data kind (Position, normal, etc...)
  39119. */
  39120. Geometry.prototype.removeVerticesData = function (kind) {
  39121. if (this._vertexBuffers[kind]) {
  39122. this._vertexBuffers[kind].dispose();
  39123. delete this._vertexBuffers[kind];
  39124. }
  39125. };
  39126. /**
  39127. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  39128. * @param buffer defines the vertex buffer to use
  39129. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39130. */
  39131. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39132. if (totalVertices === void 0) { totalVertices = null; }
  39133. var kind = buffer.getKind();
  39134. if (this._vertexBuffers[kind]) {
  39135. this._vertexBuffers[kind].dispose();
  39136. }
  39137. this._vertexBuffers[kind] = buffer;
  39138. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39139. var data = buffer.getData();
  39140. if (totalVertices != null) {
  39141. this._totalVertices = totalVertices;
  39142. }
  39143. else {
  39144. if (data != null) {
  39145. this._totalVertices = data.length / (buffer.byteStride / 4);
  39146. }
  39147. }
  39148. this._updateExtend(data);
  39149. this._resetPointsArrayCache();
  39150. var meshes = this._meshes;
  39151. var numOfMeshes = meshes.length;
  39152. for (var index = 0; index < numOfMeshes; index++) {
  39153. var mesh = meshes[index];
  39154. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39155. mesh._createGlobalSubMesh(false);
  39156. mesh.computeWorldMatrix(true);
  39157. }
  39158. }
  39159. this.notifyUpdate(kind);
  39160. if (this._vertexArrayObjects) {
  39161. this._disposeVertexArrayObjects();
  39162. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39163. }
  39164. };
  39165. /**
  39166. * Update a specific vertex buffer
  39167. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39168. * It will do nothing if the buffer is not updatable
  39169. * @param kind defines the data kind (Position, normal, etc...)
  39170. * @param data defines the data to use
  39171. * @param offset defines the offset in the target buffer where to store the data
  39172. * @param useBytes set to true if the offset is in bytes
  39173. */
  39174. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39175. if (useBytes === void 0) { useBytes = false; }
  39176. var vertexBuffer = this.getVertexBuffer(kind);
  39177. if (!vertexBuffer) {
  39178. return;
  39179. }
  39180. vertexBuffer.updateDirectly(data, offset, useBytes);
  39181. this.notifyUpdate(kind);
  39182. };
  39183. /**
  39184. * Update a specific vertex buffer
  39185. * This function will create a new buffer if the current one is not updatable
  39186. * @param kind defines the data kind (Position, normal, etc...)
  39187. * @param data defines the data to use
  39188. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39189. */
  39190. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39191. if (updateExtends === void 0) { updateExtends = false; }
  39192. var vertexBuffer = this.getVertexBuffer(kind);
  39193. if (!vertexBuffer) {
  39194. return;
  39195. }
  39196. vertexBuffer.update(data);
  39197. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39198. this._updateBoundingInfo(updateExtends, data);
  39199. }
  39200. this.notifyUpdate(kind);
  39201. };
  39202. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39203. if (updateExtends) {
  39204. this._updateExtend(data);
  39205. }
  39206. var meshes = this._meshes;
  39207. var numOfMeshes = meshes.length;
  39208. this._resetPointsArrayCache();
  39209. for (var index = 0; index < numOfMeshes; index++) {
  39210. var mesh = meshes[index];
  39211. if (updateExtends) {
  39212. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39213. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39214. var subMesh = mesh.subMeshes[subIndex];
  39215. subMesh.refreshBoundingInfo();
  39216. }
  39217. }
  39218. }
  39219. };
  39220. /** @hidden */
  39221. Geometry.prototype._bind = function (effect, indexToBind) {
  39222. if (!effect) {
  39223. return;
  39224. }
  39225. if (indexToBind === undefined) {
  39226. indexToBind = this._indexBuffer;
  39227. }
  39228. var vbs = this.getVertexBuffers();
  39229. if (!vbs) {
  39230. return;
  39231. }
  39232. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39233. this._engine.bindBuffers(vbs, indexToBind, effect);
  39234. return;
  39235. }
  39236. // Using VAO
  39237. if (!this._vertexArrayObjects[effect.key]) {
  39238. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39239. }
  39240. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39241. };
  39242. /**
  39243. * Gets total number of vertices
  39244. * @returns the total number of vertices
  39245. */
  39246. Geometry.prototype.getTotalVertices = function () {
  39247. if (!this.isReady()) {
  39248. return 0;
  39249. }
  39250. return this._totalVertices;
  39251. };
  39252. /**
  39253. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39254. * @param kind defines the data kind (Position, normal, etc...)
  39255. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39256. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39257. * @returns a float array containing vertex data
  39258. */
  39259. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39260. var vertexBuffer = this.getVertexBuffer(kind);
  39261. if (!vertexBuffer) {
  39262. return null;
  39263. }
  39264. var data = vertexBuffer.getData();
  39265. if (!data) {
  39266. return null;
  39267. }
  39268. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39269. var count = this._totalVertices * vertexBuffer.getSize();
  39270. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39271. var copy_1 = new Array(count);
  39272. vertexBuffer.forEach(count, function (value, index) {
  39273. copy_1[index] = value;
  39274. });
  39275. return copy_1;
  39276. }
  39277. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39278. if (data instanceof Array) {
  39279. var offset = vertexBuffer.byteOffset / 4;
  39280. return BABYLON.Tools.Slice(data, offset, offset + count);
  39281. }
  39282. else if (data instanceof ArrayBuffer) {
  39283. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39284. }
  39285. else {
  39286. var offset = data.byteOffset + vertexBuffer.byteOffset;
  39287. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39288. var result = new Float32Array(count);
  39289. var source = new Float32Array(data.buffer, offset, count);
  39290. result.set(source);
  39291. return result;
  39292. }
  39293. return new Float32Array(data.buffer, offset, count);
  39294. }
  39295. }
  39296. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39297. return BABYLON.Tools.Slice(data);
  39298. }
  39299. return data;
  39300. };
  39301. /**
  39302. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39303. * @param kind defines the data kind (Position, normal, etc...)
  39304. * @returns true if the vertex buffer with the specified kind is updatable
  39305. */
  39306. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39307. var vb = this._vertexBuffers[kind];
  39308. if (!vb) {
  39309. return false;
  39310. }
  39311. return vb.isUpdatable();
  39312. };
  39313. /**
  39314. * Gets a specific vertex buffer
  39315. * @param kind defines the data kind (Position, normal, etc...)
  39316. * @returns a {BABYLON.VertexBuffer}
  39317. */
  39318. Geometry.prototype.getVertexBuffer = function (kind) {
  39319. if (!this.isReady()) {
  39320. return null;
  39321. }
  39322. return this._vertexBuffers[kind];
  39323. };
  39324. /**
  39325. * Returns all vertex buffers
  39326. * @return an object holding all vertex buffers indexed by kind
  39327. */
  39328. Geometry.prototype.getVertexBuffers = function () {
  39329. if (!this.isReady()) {
  39330. return null;
  39331. }
  39332. return this._vertexBuffers;
  39333. };
  39334. /**
  39335. * Gets a boolean indicating if specific vertex buffer is present
  39336. * @param kind defines the data kind (Position, normal, etc...)
  39337. * @returns true if data is present
  39338. */
  39339. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39340. if (!this._vertexBuffers) {
  39341. if (this._delayInfo) {
  39342. return this._delayInfo.indexOf(kind) !== -1;
  39343. }
  39344. return false;
  39345. }
  39346. return this._vertexBuffers[kind] !== undefined;
  39347. };
  39348. /**
  39349. * Gets a list of all attached data kinds (Position, normal, etc...)
  39350. * @returns a list of string containing all kinds
  39351. */
  39352. Geometry.prototype.getVerticesDataKinds = function () {
  39353. var result = [];
  39354. var kind;
  39355. if (!this._vertexBuffers && this._delayInfo) {
  39356. for (kind in this._delayInfo) {
  39357. result.push(kind);
  39358. }
  39359. }
  39360. else {
  39361. for (kind in this._vertexBuffers) {
  39362. result.push(kind);
  39363. }
  39364. }
  39365. return result;
  39366. };
  39367. /**
  39368. * Update index buffer
  39369. * @param indices defines the indices to store in the index buffer
  39370. * @param offset defines the offset in the target buffer where to store the data
  39371. */
  39372. Geometry.prototype.updateIndices = function (indices, offset) {
  39373. if (!this._indexBuffer) {
  39374. return;
  39375. }
  39376. if (!this._indexBufferIsUpdatable) {
  39377. this.setIndices(indices, null, true);
  39378. }
  39379. else {
  39380. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39381. }
  39382. };
  39383. /**
  39384. * Creates a new index buffer
  39385. * @param indices defines the indices to store in the index buffer
  39386. * @param totalVertices defines the total number of vertices (could be null)
  39387. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39388. */
  39389. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39390. if (totalVertices === void 0) { totalVertices = null; }
  39391. if (updatable === void 0) { updatable = false; }
  39392. if (this._indexBuffer) {
  39393. this._engine._releaseBuffer(this._indexBuffer);
  39394. }
  39395. this._disposeVertexArrayObjects();
  39396. this._indices = indices;
  39397. this._indexBufferIsUpdatable = updatable;
  39398. if (this._meshes.length !== 0 && this._indices) {
  39399. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39400. }
  39401. if (totalVertices != undefined) { // including null and undefined
  39402. this._totalVertices = totalVertices;
  39403. }
  39404. var meshes = this._meshes;
  39405. var numOfMeshes = meshes.length;
  39406. for (var index = 0; index < numOfMeshes; index++) {
  39407. meshes[index]._createGlobalSubMesh(true);
  39408. }
  39409. this.notifyUpdate();
  39410. };
  39411. /**
  39412. * Return the total number of indices
  39413. * @returns the total number of indices
  39414. */
  39415. Geometry.prototype.getTotalIndices = function () {
  39416. if (!this.isReady()) {
  39417. return 0;
  39418. }
  39419. return this._indices.length;
  39420. };
  39421. /**
  39422. * Gets the index buffer array
  39423. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39424. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39425. * @returns the index buffer array
  39426. */
  39427. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  39428. if (!this.isReady()) {
  39429. return null;
  39430. }
  39431. var orig = this._indices;
  39432. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  39433. return orig;
  39434. }
  39435. else {
  39436. var len = orig.length;
  39437. var copy = [];
  39438. for (var i = 0; i < len; i++) {
  39439. copy.push(orig[i]);
  39440. }
  39441. return copy;
  39442. }
  39443. };
  39444. /**
  39445. * Gets the index buffer
  39446. * @return the index buffer
  39447. */
  39448. Geometry.prototype.getIndexBuffer = function () {
  39449. if (!this.isReady()) {
  39450. return null;
  39451. }
  39452. return this._indexBuffer;
  39453. };
  39454. /** @hidden */
  39455. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39456. if (effect === void 0) { effect = null; }
  39457. if (!effect || !this._vertexArrayObjects) {
  39458. return;
  39459. }
  39460. if (this._vertexArrayObjects[effect.key]) {
  39461. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39462. delete this._vertexArrayObjects[effect.key];
  39463. }
  39464. };
  39465. /**
  39466. * Release the associated resources for a specific mesh
  39467. * @param mesh defines the source mesh
  39468. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39469. */
  39470. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39471. var meshes = this._meshes;
  39472. var index = meshes.indexOf(mesh);
  39473. if (index === -1) {
  39474. return;
  39475. }
  39476. meshes.splice(index, 1);
  39477. mesh._geometry = null;
  39478. if (meshes.length === 0 && shouldDispose) {
  39479. this.dispose();
  39480. }
  39481. };
  39482. /**
  39483. * Apply current geometry to a given mesh
  39484. * @param mesh defines the mesh to apply geometry to
  39485. */
  39486. Geometry.prototype.applyToMesh = function (mesh) {
  39487. if (mesh._geometry === this) {
  39488. return;
  39489. }
  39490. var previousGeometry = mesh._geometry;
  39491. if (previousGeometry) {
  39492. previousGeometry.releaseForMesh(mesh);
  39493. }
  39494. var meshes = this._meshes;
  39495. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39496. mesh._geometry = this;
  39497. this._scene.pushGeometry(this);
  39498. meshes.push(mesh);
  39499. if (this.isReady()) {
  39500. this._applyToMesh(mesh);
  39501. }
  39502. else {
  39503. mesh._boundingInfo = this._boundingInfo;
  39504. }
  39505. };
  39506. Geometry.prototype._updateExtend = function (data) {
  39507. if (data === void 0) { data = null; }
  39508. if (!data) {
  39509. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39510. }
  39511. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39512. };
  39513. Geometry.prototype._applyToMesh = function (mesh) {
  39514. var numOfMeshes = this._meshes.length;
  39515. // vertexBuffers
  39516. for (var kind in this._vertexBuffers) {
  39517. if (numOfMeshes === 1) {
  39518. this._vertexBuffers[kind].create();
  39519. }
  39520. var buffer = this._vertexBuffers[kind].getBuffer();
  39521. if (buffer)
  39522. buffer.references = numOfMeshes;
  39523. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39524. if (!this._extend) {
  39525. this._updateExtend();
  39526. }
  39527. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39528. mesh._createGlobalSubMesh(false);
  39529. //bounding info was just created again, world matrix should be applied again.
  39530. mesh._updateBoundingInfo();
  39531. }
  39532. }
  39533. // indexBuffer
  39534. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39535. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39536. }
  39537. if (this._indexBuffer) {
  39538. this._indexBuffer.references = numOfMeshes;
  39539. }
  39540. };
  39541. Geometry.prototype.notifyUpdate = function (kind) {
  39542. if (this.onGeometryUpdated) {
  39543. this.onGeometryUpdated(this, kind);
  39544. }
  39545. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39546. var mesh = _a[_i];
  39547. mesh._markSubMeshesAsAttributesDirty();
  39548. }
  39549. };
  39550. /**
  39551. * Load the geometry if it was flagged as delay loaded
  39552. * @param scene defines the hosting scene
  39553. * @param onLoaded defines a callback called when the geometry is loaded
  39554. */
  39555. Geometry.prototype.load = function (scene, onLoaded) {
  39556. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39557. return;
  39558. }
  39559. if (this.isReady()) {
  39560. if (onLoaded) {
  39561. onLoaded();
  39562. }
  39563. return;
  39564. }
  39565. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39566. this._queueLoad(scene, onLoaded);
  39567. };
  39568. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39569. var _this = this;
  39570. if (!this.delayLoadingFile) {
  39571. return;
  39572. }
  39573. scene._addPendingData(this);
  39574. scene._loadFile(this.delayLoadingFile, function (data) {
  39575. if (!_this._delayLoadingFunction) {
  39576. return;
  39577. }
  39578. _this._delayLoadingFunction(JSON.parse(data), _this);
  39579. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39580. _this._delayInfo = [];
  39581. scene._removePendingData(_this);
  39582. var meshes = _this._meshes;
  39583. var numOfMeshes = meshes.length;
  39584. for (var index = 0; index < numOfMeshes; index++) {
  39585. _this._applyToMesh(meshes[index]);
  39586. }
  39587. if (onLoaded) {
  39588. onLoaded();
  39589. }
  39590. }, undefined, true);
  39591. };
  39592. /**
  39593. * Invert the geometry to move from a right handed system to a left handed one.
  39594. */
  39595. Geometry.prototype.toLeftHanded = function () {
  39596. // Flip faces
  39597. var tIndices = this.getIndices(false);
  39598. if (tIndices != null && tIndices.length > 0) {
  39599. for (var i = 0; i < tIndices.length; i += 3) {
  39600. var tTemp = tIndices[i + 0];
  39601. tIndices[i + 0] = tIndices[i + 2];
  39602. tIndices[i + 2] = tTemp;
  39603. }
  39604. this.setIndices(tIndices);
  39605. }
  39606. // Negate position.z
  39607. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39608. if (tPositions != null && tPositions.length > 0) {
  39609. for (var i = 0; i < tPositions.length; i += 3) {
  39610. tPositions[i + 2] = -tPositions[i + 2];
  39611. }
  39612. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39613. }
  39614. // Negate normal.z
  39615. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39616. if (tNormals != null && tNormals.length > 0) {
  39617. for (var i = 0; i < tNormals.length; i += 3) {
  39618. tNormals[i + 2] = -tNormals[i + 2];
  39619. }
  39620. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39621. }
  39622. };
  39623. // Cache
  39624. /** @hidden */
  39625. Geometry.prototype._resetPointsArrayCache = function () {
  39626. this._positions = null;
  39627. };
  39628. /** @hidden */
  39629. Geometry.prototype._generatePointsArray = function () {
  39630. if (this._positions)
  39631. return true;
  39632. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39633. if (!data || data.length === 0) {
  39634. return false;
  39635. }
  39636. this._positions = [];
  39637. for (var index = 0; index < data.length; index += 3) {
  39638. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39639. }
  39640. return true;
  39641. };
  39642. /**
  39643. * Gets a value indicating if the geometry is disposed
  39644. * @returns true if the geometry was disposed
  39645. */
  39646. Geometry.prototype.isDisposed = function () {
  39647. return this._isDisposed;
  39648. };
  39649. Geometry.prototype._disposeVertexArrayObjects = function () {
  39650. if (this._vertexArrayObjects) {
  39651. for (var kind in this._vertexArrayObjects) {
  39652. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39653. }
  39654. this._vertexArrayObjects = {};
  39655. }
  39656. };
  39657. /**
  39658. * Free all associated resources
  39659. */
  39660. Geometry.prototype.dispose = function () {
  39661. var meshes = this._meshes;
  39662. var numOfMeshes = meshes.length;
  39663. var index;
  39664. for (index = 0; index < numOfMeshes; index++) {
  39665. this.releaseForMesh(meshes[index]);
  39666. }
  39667. this._meshes = [];
  39668. this._disposeVertexArrayObjects();
  39669. for (var kind in this._vertexBuffers) {
  39670. this._vertexBuffers[kind].dispose();
  39671. }
  39672. this._vertexBuffers = {};
  39673. this._totalVertices = 0;
  39674. if (this._indexBuffer) {
  39675. this._engine._releaseBuffer(this._indexBuffer);
  39676. }
  39677. this._indexBuffer = null;
  39678. this._indices = [];
  39679. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39680. this.delayLoadingFile = null;
  39681. this._delayLoadingFunction = null;
  39682. this._delayInfo = [];
  39683. this._boundingInfo = null;
  39684. this._scene.removeGeometry(this);
  39685. this._isDisposed = true;
  39686. };
  39687. /**
  39688. * Clone the current geometry into a new geometry
  39689. * @param id defines the unique ID of the new geometry
  39690. * @returns a new geometry object
  39691. */
  39692. Geometry.prototype.copy = function (id) {
  39693. var vertexData = new BABYLON.VertexData();
  39694. vertexData.indices = [];
  39695. var indices = this.getIndices();
  39696. if (indices) {
  39697. for (var index = 0; index < indices.length; index++) {
  39698. vertexData.indices.push(indices[index]);
  39699. }
  39700. }
  39701. var updatable = false;
  39702. var stopChecking = false;
  39703. var kind;
  39704. for (kind in this._vertexBuffers) {
  39705. // using slice() to make a copy of the array and not just reference it
  39706. var data = this.getVerticesData(kind);
  39707. if (data instanceof Float32Array) {
  39708. vertexData.set(new Float32Array(data), kind);
  39709. }
  39710. else {
  39711. vertexData.set(data.slice(0), kind);
  39712. }
  39713. if (!stopChecking) {
  39714. var vb = this.getVertexBuffer(kind);
  39715. if (vb) {
  39716. updatable = vb.isUpdatable();
  39717. stopChecking = !updatable;
  39718. }
  39719. }
  39720. }
  39721. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39722. geometry.delayLoadState = this.delayLoadState;
  39723. geometry.delayLoadingFile = this.delayLoadingFile;
  39724. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39725. for (kind in this._delayInfo) {
  39726. geometry._delayInfo = geometry._delayInfo || [];
  39727. geometry._delayInfo.push(kind);
  39728. }
  39729. // Bounding info
  39730. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39731. return geometry;
  39732. };
  39733. /**
  39734. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39735. * @return a JSON representation of the current geometry data (without the vertices data)
  39736. */
  39737. Geometry.prototype.serialize = function () {
  39738. var serializationObject = {};
  39739. serializationObject.id = this.id;
  39740. serializationObject.updatable = this._updatable;
  39741. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39742. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39743. }
  39744. return serializationObject;
  39745. };
  39746. Geometry.prototype.toNumberArray = function (origin) {
  39747. if (Array.isArray(origin)) {
  39748. return origin;
  39749. }
  39750. else {
  39751. return Array.prototype.slice.call(origin);
  39752. }
  39753. };
  39754. /**
  39755. * Serialize all vertices data into a JSON oject
  39756. * @returns a JSON representation of the current geometry data
  39757. */
  39758. Geometry.prototype.serializeVerticeData = function () {
  39759. var serializationObject = this.serialize();
  39760. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39761. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39762. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39763. serializationObject.positions._updatable = true;
  39764. }
  39765. }
  39766. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39767. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39768. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39769. serializationObject.normals._updatable = true;
  39770. }
  39771. }
  39772. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39773. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39774. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39775. serializationObject.tangets._updatable = true;
  39776. }
  39777. }
  39778. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39779. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39780. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39781. serializationObject.uvs._updatable = true;
  39782. }
  39783. }
  39784. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39785. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39786. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39787. serializationObject.uv2s._updatable = true;
  39788. }
  39789. }
  39790. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39791. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39792. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39793. serializationObject.uv3s._updatable = true;
  39794. }
  39795. }
  39796. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39797. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39798. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39799. serializationObject.uv4s._updatable = true;
  39800. }
  39801. }
  39802. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39803. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39804. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39805. serializationObject.uv5s._updatable = true;
  39806. }
  39807. }
  39808. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39809. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39810. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39811. serializationObject.uv6s._updatable = true;
  39812. }
  39813. }
  39814. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39815. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39816. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39817. serializationObject.colors._updatable = true;
  39818. }
  39819. }
  39820. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39821. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39822. serializationObject.matricesIndices._isExpanded = true;
  39823. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39824. serializationObject.matricesIndices._updatable = true;
  39825. }
  39826. }
  39827. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39828. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39829. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39830. serializationObject.matricesWeights._updatable = true;
  39831. }
  39832. }
  39833. serializationObject.indices = this.toNumberArray(this.getIndices());
  39834. return serializationObject;
  39835. };
  39836. // Statics
  39837. /**
  39838. * Extracts a clone of a mesh geometry
  39839. * @param mesh defines the source mesh
  39840. * @param id defines the unique ID of the new geometry object
  39841. * @returns the new geometry object
  39842. */
  39843. Geometry.ExtractFromMesh = function (mesh, id) {
  39844. var geometry = mesh._geometry;
  39845. if (!geometry) {
  39846. return null;
  39847. }
  39848. return geometry.copy(id);
  39849. };
  39850. /**
  39851. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39852. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39853. * Be aware Math.random() could cause collisions, but:
  39854. * "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"
  39855. * @returns a string containing a new GUID
  39856. */
  39857. Geometry.RandomId = function () {
  39858. return BABYLON.Tools.RandomId();
  39859. };
  39860. /** @hidden */
  39861. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39862. var scene = mesh.getScene();
  39863. // Geometry
  39864. var geometryId = parsedGeometry.geometryId;
  39865. if (geometryId) {
  39866. var geometry = scene.getGeometryByID(geometryId);
  39867. if (geometry) {
  39868. geometry.applyToMesh(mesh);
  39869. }
  39870. }
  39871. else if (parsedGeometry instanceof ArrayBuffer) {
  39872. var binaryInfo = mesh._binaryInfo;
  39873. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39874. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39875. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39876. }
  39877. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39878. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39879. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39880. }
  39881. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39882. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39883. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39884. }
  39885. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39886. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39887. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39888. }
  39889. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39890. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39891. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39892. }
  39893. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39894. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39895. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39896. }
  39897. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39898. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39899. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39900. }
  39901. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39902. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39903. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39904. }
  39905. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39906. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39907. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39908. }
  39909. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39910. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39911. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39912. }
  39913. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39914. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39915. var floatIndices = [];
  39916. for (var i = 0; i < matricesIndicesData.length; i++) {
  39917. var index = matricesIndicesData[i];
  39918. floatIndices.push(index & 0x000000FF);
  39919. floatIndices.push((index & 0x0000FF00) >> 8);
  39920. floatIndices.push((index & 0x00FF0000) >> 16);
  39921. floatIndices.push(index >> 24);
  39922. }
  39923. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39924. }
  39925. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39926. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39927. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39928. }
  39929. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39930. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39931. mesh.setIndices(indicesData, null);
  39932. }
  39933. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39934. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39935. mesh.subMeshes = [];
  39936. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39937. var materialIndex = subMeshesData[(i * 5) + 0];
  39938. var verticesStart = subMeshesData[(i * 5) + 1];
  39939. var verticesCount = subMeshesData[(i * 5) + 2];
  39940. var indexStart = subMeshesData[(i * 5) + 3];
  39941. var indexCount = subMeshesData[(i * 5) + 4];
  39942. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39943. }
  39944. }
  39945. }
  39946. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39947. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39948. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39949. if (parsedGeometry.tangents) {
  39950. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39951. }
  39952. if (parsedGeometry.uvs) {
  39953. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39954. }
  39955. if (parsedGeometry.uvs2) {
  39956. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39957. }
  39958. if (parsedGeometry.uvs3) {
  39959. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39960. }
  39961. if (parsedGeometry.uvs4) {
  39962. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39963. }
  39964. if (parsedGeometry.uvs5) {
  39965. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39966. }
  39967. if (parsedGeometry.uvs6) {
  39968. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39969. }
  39970. if (parsedGeometry.colors) {
  39971. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39972. }
  39973. if (parsedGeometry.matricesIndices) {
  39974. if (!parsedGeometry.matricesIndices._isExpanded) {
  39975. var floatIndices = [];
  39976. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39977. var matricesIndex = parsedGeometry.matricesIndices[i];
  39978. floatIndices.push(matricesIndex & 0x000000FF);
  39979. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39980. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39981. floatIndices.push(matricesIndex >> 24);
  39982. }
  39983. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39984. }
  39985. else {
  39986. delete parsedGeometry.matricesIndices._isExpanded;
  39987. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39988. }
  39989. }
  39990. if (parsedGeometry.matricesIndicesExtra) {
  39991. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39992. var floatIndices = [];
  39993. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39994. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39995. floatIndices.push(matricesIndex & 0x000000FF);
  39996. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39997. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39998. floatIndices.push(matricesIndex >> 24);
  39999. }
  40000. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  40001. }
  40002. else {
  40003. delete parsedGeometry.matricesIndices._isExpanded;
  40004. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  40005. }
  40006. }
  40007. if (parsedGeometry.matricesWeights) {
  40008. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  40009. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  40010. }
  40011. if (parsedGeometry.matricesWeightsExtra) {
  40012. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  40013. }
  40014. mesh.setIndices(parsedGeometry.indices, null);
  40015. }
  40016. // SubMeshes
  40017. if (parsedGeometry.subMeshes) {
  40018. mesh.subMeshes = [];
  40019. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  40020. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  40021. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  40022. }
  40023. }
  40024. // Flat shading
  40025. if (mesh._shouldGenerateFlatShading) {
  40026. mesh.convertToFlatShadedMesh();
  40027. delete mesh._shouldGenerateFlatShading;
  40028. }
  40029. // Update
  40030. mesh.computeWorldMatrix(true);
  40031. // Octree
  40032. var sceneOctree = scene.selectionOctree;
  40033. if (sceneOctree !== undefined && sceneOctree !== null) {
  40034. sceneOctree.addMesh(mesh);
  40035. }
  40036. };
  40037. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  40038. var epsilon = 1e-3;
  40039. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  40040. return;
  40041. }
  40042. var noInfluenceBoneIndex = 0.0;
  40043. if (parsedGeometry.skeletonId > -1) {
  40044. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  40045. if (!skeleton) {
  40046. return;
  40047. }
  40048. noInfluenceBoneIndex = skeleton.bones.length;
  40049. }
  40050. else {
  40051. return;
  40052. }
  40053. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  40054. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40055. var matricesWeights = parsedGeometry.matricesWeights;
  40056. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  40057. var influencers = parsedGeometry.numBoneInfluencer;
  40058. var size = matricesWeights.length;
  40059. for (var i = 0; i < size; i += 4) {
  40060. var weight = 0.0;
  40061. var firstZeroWeight = -1;
  40062. for (var j = 0; j < 4; j++) {
  40063. var w = matricesWeights[i + j];
  40064. weight += w;
  40065. if (w < epsilon && firstZeroWeight < 0) {
  40066. firstZeroWeight = j;
  40067. }
  40068. }
  40069. if (matricesWeightsExtra) {
  40070. for (var j = 0; j < 4; j++) {
  40071. var w = matricesWeightsExtra[i + j];
  40072. weight += w;
  40073. if (w < epsilon && firstZeroWeight < 0) {
  40074. firstZeroWeight = j + 4;
  40075. }
  40076. }
  40077. }
  40078. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  40079. firstZeroWeight = influencers - 1;
  40080. }
  40081. if (weight > epsilon) {
  40082. var mweight = 1.0 / weight;
  40083. for (var j = 0; j < 4; j++) {
  40084. matricesWeights[i + j] *= mweight;
  40085. }
  40086. if (matricesWeightsExtra) {
  40087. for (var j = 0; j < 4; j++) {
  40088. matricesWeightsExtra[i + j] *= mweight;
  40089. }
  40090. }
  40091. }
  40092. else {
  40093. if (firstZeroWeight >= 4) {
  40094. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  40095. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  40096. }
  40097. else {
  40098. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  40099. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  40100. }
  40101. }
  40102. }
  40103. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  40104. if (parsedGeometry.matricesWeightsExtra) {
  40105. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  40106. }
  40107. };
  40108. /**
  40109. * Create a new geometry from persisted data (Using .babylon file format)
  40110. * @param parsedVertexData defines the persisted data
  40111. * @param scene defines the hosting scene
  40112. * @param rootUrl defines the root url to use to load assets (like delayed data)
  40113. * @returns the new geometry object
  40114. */
  40115. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40116. if (scene.getGeometryByID(parsedVertexData.id)) {
  40117. return null; // null since geometry could be something else than a box...
  40118. }
  40119. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  40120. if (BABYLON.Tags) {
  40121. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40122. }
  40123. if (parsedVertexData.delayLoadingFile) {
  40124. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40125. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40126. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40127. geometry._delayInfo = [];
  40128. if (parsedVertexData.hasUVs) {
  40129. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40130. }
  40131. if (parsedVertexData.hasUVs2) {
  40132. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40133. }
  40134. if (parsedVertexData.hasUVs3) {
  40135. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40136. }
  40137. if (parsedVertexData.hasUVs4) {
  40138. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40139. }
  40140. if (parsedVertexData.hasUVs5) {
  40141. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40142. }
  40143. if (parsedVertexData.hasUVs6) {
  40144. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40145. }
  40146. if (parsedVertexData.hasColors) {
  40147. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40148. }
  40149. if (parsedVertexData.hasMatricesIndices) {
  40150. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40151. }
  40152. if (parsedVertexData.hasMatricesWeights) {
  40153. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40154. }
  40155. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40156. }
  40157. else {
  40158. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40159. }
  40160. scene.pushGeometry(geometry, true);
  40161. return geometry;
  40162. };
  40163. return Geometry;
  40164. }());
  40165. BABYLON.Geometry = Geometry;
  40166. // Primitives
  40167. /// Abstract class
  40168. /**
  40169. * Abstract class used to provide common services for all typed geometries
  40170. * @hidden
  40171. */
  40172. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40173. __extends(_PrimitiveGeometry, _super);
  40174. /**
  40175. * Creates a new typed geometry
  40176. * @param id defines the unique ID of the geometry
  40177. * @param scene defines the hosting scene
  40178. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40179. * @param mesh defines the hosting mesh (can be null)
  40180. */
  40181. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40182. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40183. if (mesh === void 0) { mesh = null; }
  40184. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40185. _this._canBeRegenerated = _canBeRegenerated;
  40186. _this._beingRegenerated = true;
  40187. _this.regenerate();
  40188. _this._beingRegenerated = false;
  40189. return _this;
  40190. }
  40191. /**
  40192. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40193. * @returns true if the geometry can be regenerated
  40194. */
  40195. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40196. return this._canBeRegenerated;
  40197. };
  40198. /**
  40199. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40200. */
  40201. _PrimitiveGeometry.prototype.regenerate = function () {
  40202. if (!this._canBeRegenerated) {
  40203. return;
  40204. }
  40205. this._beingRegenerated = true;
  40206. this.setAllVerticesData(this._regenerateVertexData(), false);
  40207. this._beingRegenerated = false;
  40208. };
  40209. /**
  40210. * Clone the geometry
  40211. * @param id defines the unique ID of the new geometry
  40212. * @returns the new geometry
  40213. */
  40214. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40215. return _super.prototype.copy.call(this, id);
  40216. };
  40217. // overrides
  40218. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40219. if (!this._beingRegenerated) {
  40220. return;
  40221. }
  40222. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40223. };
  40224. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40225. if (!this._beingRegenerated) {
  40226. return;
  40227. }
  40228. _super.prototype.setVerticesData.call(this, kind, data, false);
  40229. };
  40230. // to override
  40231. /** @hidden */
  40232. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40233. throw new Error("Abstract method");
  40234. };
  40235. _PrimitiveGeometry.prototype.copy = function (id) {
  40236. throw new Error("Must be overriden in sub-classes.");
  40237. };
  40238. _PrimitiveGeometry.prototype.serialize = function () {
  40239. var serializationObject = _super.prototype.serialize.call(this);
  40240. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40241. return serializationObject;
  40242. };
  40243. return _PrimitiveGeometry;
  40244. }(Geometry));
  40245. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40246. /**
  40247. * Creates a ribbon geometry
  40248. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40249. */
  40250. var RibbonGeometry = /** @class */ (function (_super) {
  40251. __extends(RibbonGeometry, _super);
  40252. /**
  40253. * Creates a ribbon geometry
  40254. * @param id defines the unique ID of the geometry
  40255. * @param scene defines the hosting scene
  40256. * @param pathArray defines the array of paths to use
  40257. * @param closeArray defines if the last path and the first path must be joined
  40258. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40259. * @param offset defines the offset between points
  40260. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40261. * @param mesh defines the hosting mesh (can be null)
  40262. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40263. */
  40264. function RibbonGeometry(id, scene,
  40265. /**
  40266. * Defines the array of paths to use
  40267. */
  40268. pathArray,
  40269. /**
  40270. * Defines if the last and first points of each path in your pathArray must be joined
  40271. */
  40272. closeArray,
  40273. /**
  40274. * Defines if the last and first points of each path in your pathArray must be joined
  40275. */
  40276. closePath,
  40277. /**
  40278. * Defines the offset between points
  40279. */
  40280. offset, canBeRegenerated, mesh,
  40281. /**
  40282. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40283. */
  40284. side) {
  40285. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40286. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40287. _this.pathArray = pathArray;
  40288. _this.closeArray = closeArray;
  40289. _this.closePath = closePath;
  40290. _this.offset = offset;
  40291. _this.side = side;
  40292. return _this;
  40293. }
  40294. /** @hidden */
  40295. RibbonGeometry.prototype._regenerateVertexData = function () {
  40296. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40297. };
  40298. RibbonGeometry.prototype.copy = function (id) {
  40299. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40300. };
  40301. return RibbonGeometry;
  40302. }(_PrimitiveGeometry));
  40303. BABYLON.RibbonGeometry = RibbonGeometry;
  40304. /**
  40305. * Creates a box geometry
  40306. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40307. */
  40308. var BoxGeometry = /** @class */ (function (_super) {
  40309. __extends(BoxGeometry, _super);
  40310. /**
  40311. * Creates a box geometry
  40312. * @param id defines the unique ID of the geometry
  40313. * @param scene defines the hosting scene
  40314. * @param size defines the zise of the box (width, height and depth are the same)
  40315. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40316. * @param mesh defines the hosting mesh (can be null)
  40317. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40318. */
  40319. function BoxGeometry(id, scene,
  40320. /**
  40321. * Defines the zise of the box (width, height and depth are the same)
  40322. */
  40323. size, canBeRegenerated, mesh,
  40324. /**
  40325. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40326. */
  40327. side) {
  40328. if (mesh === void 0) { mesh = null; }
  40329. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40330. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40331. _this.size = size;
  40332. _this.side = side;
  40333. return _this;
  40334. }
  40335. /** @hidden */
  40336. BoxGeometry.prototype._regenerateVertexData = function () {
  40337. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40338. };
  40339. BoxGeometry.prototype.copy = function (id) {
  40340. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40341. };
  40342. BoxGeometry.prototype.serialize = function () {
  40343. var serializationObject = _super.prototype.serialize.call(this);
  40344. serializationObject.size = this.size;
  40345. return serializationObject;
  40346. };
  40347. BoxGeometry.Parse = function (parsedBox, scene) {
  40348. if (scene.getGeometryByID(parsedBox.id)) {
  40349. return null; // null since geometry could be something else than a box...
  40350. }
  40351. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40352. if (BABYLON.Tags) {
  40353. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40354. }
  40355. scene.pushGeometry(box, true);
  40356. return box;
  40357. };
  40358. return BoxGeometry;
  40359. }(_PrimitiveGeometry));
  40360. BABYLON.BoxGeometry = BoxGeometry;
  40361. /**
  40362. * Creates a sphere geometry
  40363. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40364. */
  40365. var SphereGeometry = /** @class */ (function (_super) {
  40366. __extends(SphereGeometry, _super);
  40367. /**
  40368. * Create a new sphere geometry
  40369. * @param id defines the unique ID of the geometry
  40370. * @param scene defines the hosting scene
  40371. * @param segments defines the number of segments to use to create the sphere
  40372. * @param diameter defines the diameter of the sphere
  40373. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40374. * @param mesh defines the hosting mesh (can be null)
  40375. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40376. */
  40377. function SphereGeometry(id, scene,
  40378. /**
  40379. * Defines the number of segments to use to create the sphere
  40380. */
  40381. segments,
  40382. /**
  40383. * Defines the diameter of the sphere
  40384. */
  40385. diameter, canBeRegenerated, mesh,
  40386. /**
  40387. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40388. */
  40389. side) {
  40390. if (mesh === void 0) { mesh = null; }
  40391. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40392. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40393. _this.segments = segments;
  40394. _this.diameter = diameter;
  40395. _this.side = side;
  40396. return _this;
  40397. }
  40398. /** @hidden */
  40399. SphereGeometry.prototype._regenerateVertexData = function () {
  40400. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40401. };
  40402. SphereGeometry.prototype.copy = function (id) {
  40403. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40404. };
  40405. SphereGeometry.prototype.serialize = function () {
  40406. var serializationObject = _super.prototype.serialize.call(this);
  40407. serializationObject.segments = this.segments;
  40408. serializationObject.diameter = this.diameter;
  40409. return serializationObject;
  40410. };
  40411. SphereGeometry.Parse = function (parsedSphere, scene) {
  40412. if (scene.getGeometryByID(parsedSphere.id)) {
  40413. return null; // null since geometry could be something else than a sphere...
  40414. }
  40415. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40416. if (BABYLON.Tags) {
  40417. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40418. }
  40419. scene.pushGeometry(sphere, true);
  40420. return sphere;
  40421. };
  40422. return SphereGeometry;
  40423. }(_PrimitiveGeometry));
  40424. BABYLON.SphereGeometry = SphereGeometry;
  40425. /**
  40426. * Creates a disc geometry
  40427. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40428. */
  40429. var DiscGeometry = /** @class */ (function (_super) {
  40430. __extends(DiscGeometry, _super);
  40431. /**
  40432. * Creates a new disc geometry
  40433. * @param id defines the unique ID of the geometry
  40434. * @param scene defines the hosting scene
  40435. * @param radius defines the radius of the disc
  40436. * @param tessellation defines the tesselation factor to apply to the disc
  40437. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40438. * @param mesh defines the hosting mesh (can be null)
  40439. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40440. */
  40441. function DiscGeometry(id, scene,
  40442. /**
  40443. * Defines the radius of the disc
  40444. */
  40445. radius,
  40446. /**
  40447. * Defines the tesselation factor to apply to the disc
  40448. */
  40449. tessellation, canBeRegenerated, mesh,
  40450. /**
  40451. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40452. */
  40453. side) {
  40454. if (mesh === void 0) { mesh = null; }
  40455. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40456. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40457. _this.radius = radius;
  40458. _this.tessellation = tessellation;
  40459. _this.side = side;
  40460. return _this;
  40461. }
  40462. /** @hidden */
  40463. DiscGeometry.prototype._regenerateVertexData = function () {
  40464. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40465. };
  40466. DiscGeometry.prototype.copy = function (id) {
  40467. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40468. };
  40469. return DiscGeometry;
  40470. }(_PrimitiveGeometry));
  40471. BABYLON.DiscGeometry = DiscGeometry;
  40472. /**
  40473. * Creates a new cylinder geometry
  40474. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40475. */
  40476. var CylinderGeometry = /** @class */ (function (_super) {
  40477. __extends(CylinderGeometry, _super);
  40478. /**
  40479. * Creates a new cylinder geometry
  40480. * @param id defines the unique ID of the geometry
  40481. * @param scene defines the hosting scene
  40482. * @param height defines the height of the cylinder
  40483. * @param diameterTop defines the diameter of the cylinder's top cap
  40484. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40485. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40486. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40487. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40488. * @param mesh defines the hosting mesh (can be null)
  40489. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40490. */
  40491. function CylinderGeometry(id, scene,
  40492. /**
  40493. * Defines the height of the cylinder
  40494. */
  40495. height,
  40496. /**
  40497. * Defines the diameter of the cylinder's top cap
  40498. */
  40499. diameterTop,
  40500. /**
  40501. * Defines the diameter of the cylinder's bottom cap
  40502. */
  40503. diameterBottom,
  40504. /**
  40505. * Defines the tessellation factor to apply to the cylinder
  40506. */
  40507. tessellation,
  40508. /**
  40509. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40510. */
  40511. subdivisions, canBeRegenerated, mesh,
  40512. /**
  40513. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40514. */
  40515. side) {
  40516. if (subdivisions === void 0) { subdivisions = 1; }
  40517. if (mesh === void 0) { mesh = null; }
  40518. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40519. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40520. _this.height = height;
  40521. _this.diameterTop = diameterTop;
  40522. _this.diameterBottom = diameterBottom;
  40523. _this.tessellation = tessellation;
  40524. _this.subdivisions = subdivisions;
  40525. _this.side = side;
  40526. return _this;
  40527. }
  40528. /** @hidden */
  40529. CylinderGeometry.prototype._regenerateVertexData = function () {
  40530. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40531. };
  40532. CylinderGeometry.prototype.copy = function (id) {
  40533. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40534. };
  40535. CylinderGeometry.prototype.serialize = function () {
  40536. var serializationObject = _super.prototype.serialize.call(this);
  40537. serializationObject.height = this.height;
  40538. serializationObject.diameterTop = this.diameterTop;
  40539. serializationObject.diameterBottom = this.diameterBottom;
  40540. serializationObject.tessellation = this.tessellation;
  40541. return serializationObject;
  40542. };
  40543. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40544. if (scene.getGeometryByID(parsedCylinder.id)) {
  40545. return null; // null since geometry could be something else than a cylinder...
  40546. }
  40547. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40548. if (BABYLON.Tags) {
  40549. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40550. }
  40551. scene.pushGeometry(cylinder, true);
  40552. return cylinder;
  40553. };
  40554. return CylinderGeometry;
  40555. }(_PrimitiveGeometry));
  40556. BABYLON.CylinderGeometry = CylinderGeometry;
  40557. /**
  40558. * Creates a new torus geometry
  40559. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40560. */
  40561. var TorusGeometry = /** @class */ (function (_super) {
  40562. __extends(TorusGeometry, _super);
  40563. /**
  40564. * Creates a new torus geometry
  40565. * @param id defines the unique ID of the geometry
  40566. * @param scene defines the hosting scene
  40567. * @param diameter defines the diameter of the torus
  40568. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40569. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40570. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40571. * @param mesh defines the hosting mesh (can be null)
  40572. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40573. */
  40574. function TorusGeometry(id, scene,
  40575. /**
  40576. * Defines the diameter of the torus
  40577. */
  40578. diameter,
  40579. /**
  40580. * Defines the thickness of the torus (ie. internal diameter)
  40581. */
  40582. thickness,
  40583. /**
  40584. * Defines the tesselation factor to apply to the torus
  40585. */
  40586. tessellation, canBeRegenerated, mesh,
  40587. /**
  40588. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40589. */
  40590. side) {
  40591. if (mesh === void 0) { mesh = null; }
  40592. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40593. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40594. _this.diameter = diameter;
  40595. _this.thickness = thickness;
  40596. _this.tessellation = tessellation;
  40597. _this.side = side;
  40598. return _this;
  40599. }
  40600. /** @hidden */
  40601. TorusGeometry.prototype._regenerateVertexData = function () {
  40602. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40603. };
  40604. TorusGeometry.prototype.copy = function (id) {
  40605. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40606. };
  40607. TorusGeometry.prototype.serialize = function () {
  40608. var serializationObject = _super.prototype.serialize.call(this);
  40609. serializationObject.diameter = this.diameter;
  40610. serializationObject.thickness = this.thickness;
  40611. serializationObject.tessellation = this.tessellation;
  40612. return serializationObject;
  40613. };
  40614. TorusGeometry.Parse = function (parsedTorus, scene) {
  40615. if (scene.getGeometryByID(parsedTorus.id)) {
  40616. return null; // null since geometry could be something else than a torus...
  40617. }
  40618. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40619. if (BABYLON.Tags) {
  40620. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40621. }
  40622. scene.pushGeometry(torus, true);
  40623. return torus;
  40624. };
  40625. return TorusGeometry;
  40626. }(_PrimitiveGeometry));
  40627. BABYLON.TorusGeometry = TorusGeometry;
  40628. /**
  40629. * Creates a new ground geometry
  40630. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40631. */
  40632. var GroundGeometry = /** @class */ (function (_super) {
  40633. __extends(GroundGeometry, _super);
  40634. /**
  40635. * Creates a new ground geometry
  40636. * @param id defines the unique ID of the geometry
  40637. * @param scene defines the hosting scene
  40638. * @param width defines the width of the ground
  40639. * @param height defines the height of the ground
  40640. * @param subdivisions defines the subdivisions to apply to the ground
  40641. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40642. * @param mesh defines the hosting mesh (can be null)
  40643. */
  40644. function GroundGeometry(id, scene,
  40645. /**
  40646. * Defines the width of the ground
  40647. */
  40648. width,
  40649. /**
  40650. * Defines the height of the ground
  40651. */
  40652. height,
  40653. /**
  40654. * Defines the subdivisions to apply to the ground
  40655. */
  40656. subdivisions, canBeRegenerated, mesh) {
  40657. if (mesh === void 0) { mesh = null; }
  40658. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40659. _this.width = width;
  40660. _this.height = height;
  40661. _this.subdivisions = subdivisions;
  40662. return _this;
  40663. }
  40664. /** @hidden */
  40665. GroundGeometry.prototype._regenerateVertexData = function () {
  40666. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40667. };
  40668. GroundGeometry.prototype.copy = function (id) {
  40669. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40670. };
  40671. GroundGeometry.prototype.serialize = function () {
  40672. var serializationObject = _super.prototype.serialize.call(this);
  40673. serializationObject.width = this.width;
  40674. serializationObject.height = this.height;
  40675. serializationObject.subdivisions = this.subdivisions;
  40676. return serializationObject;
  40677. };
  40678. GroundGeometry.Parse = function (parsedGround, scene) {
  40679. if (scene.getGeometryByID(parsedGround.id)) {
  40680. return null; // null since geometry could be something else than a ground...
  40681. }
  40682. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40683. if (BABYLON.Tags) {
  40684. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40685. }
  40686. scene.pushGeometry(ground, true);
  40687. return ground;
  40688. };
  40689. return GroundGeometry;
  40690. }(_PrimitiveGeometry));
  40691. BABYLON.GroundGeometry = GroundGeometry;
  40692. /**
  40693. * Creates a tiled ground geometry
  40694. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40695. */
  40696. var TiledGroundGeometry = /** @class */ (function (_super) {
  40697. __extends(TiledGroundGeometry, _super);
  40698. /**
  40699. * Creates a tiled ground geometry
  40700. * @param id defines the unique ID of the geometry
  40701. * @param scene defines the hosting scene
  40702. * @param xmin defines the minimum value on X axis
  40703. * @param zmin defines the minimum value on Z axis
  40704. * @param xmax defines the maximum value on X axis
  40705. * @param zmax defines the maximum value on Z axis
  40706. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40707. * @param precision defines the precision to use when computing the tiles
  40708. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40709. * @param mesh defines the hosting mesh (can be null)
  40710. */
  40711. function TiledGroundGeometry(id, scene,
  40712. /**
  40713. * Defines the minimum value on X axis
  40714. */
  40715. xmin,
  40716. /**
  40717. * Defines the minimum value on Z axis
  40718. */
  40719. zmin,
  40720. /**
  40721. * Defines the maximum value on X axis
  40722. */
  40723. xmax,
  40724. /**
  40725. * Defines the maximum value on Z axis
  40726. */
  40727. zmax,
  40728. /**
  40729. * Defines the subdivisions to apply to the ground
  40730. */
  40731. subdivisions,
  40732. /**
  40733. * Defines the precision to use when computing the tiles
  40734. */
  40735. precision, canBeRegenerated, mesh) {
  40736. if (mesh === void 0) { mesh = null; }
  40737. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40738. _this.xmin = xmin;
  40739. _this.zmin = zmin;
  40740. _this.xmax = xmax;
  40741. _this.zmax = zmax;
  40742. _this.subdivisions = subdivisions;
  40743. _this.precision = precision;
  40744. return _this;
  40745. }
  40746. /** @hidden */
  40747. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40748. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40749. };
  40750. TiledGroundGeometry.prototype.copy = function (id) {
  40751. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40752. };
  40753. return TiledGroundGeometry;
  40754. }(_PrimitiveGeometry));
  40755. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40756. /**
  40757. * Creates a plane geometry
  40758. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40759. */
  40760. var PlaneGeometry = /** @class */ (function (_super) {
  40761. __extends(PlaneGeometry, _super);
  40762. /**
  40763. * Creates a plane geometry
  40764. * @param id defines the unique ID of the geometry
  40765. * @param scene defines the hosting scene
  40766. * @param size defines the size of the plane (width === height)
  40767. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40768. * @param mesh defines the hosting mesh (can be null)
  40769. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40770. */
  40771. function PlaneGeometry(id, scene,
  40772. /**
  40773. * Defines the size of the plane (width === height)
  40774. */
  40775. size, canBeRegenerated, mesh,
  40776. /**
  40777. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40778. */
  40779. side) {
  40780. if (mesh === void 0) { mesh = null; }
  40781. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40782. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40783. _this.size = size;
  40784. _this.side = side;
  40785. return _this;
  40786. }
  40787. /** @hidden */
  40788. PlaneGeometry.prototype._regenerateVertexData = function () {
  40789. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40790. };
  40791. PlaneGeometry.prototype.copy = function (id) {
  40792. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40793. };
  40794. PlaneGeometry.prototype.serialize = function () {
  40795. var serializationObject = _super.prototype.serialize.call(this);
  40796. serializationObject.size = this.size;
  40797. return serializationObject;
  40798. };
  40799. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40800. if (scene.getGeometryByID(parsedPlane.id)) {
  40801. return null; // null since geometry could be something else than a ground...
  40802. }
  40803. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40804. if (BABYLON.Tags) {
  40805. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40806. }
  40807. scene.pushGeometry(plane, true);
  40808. return plane;
  40809. };
  40810. return PlaneGeometry;
  40811. }(_PrimitiveGeometry));
  40812. BABYLON.PlaneGeometry = PlaneGeometry;
  40813. /**
  40814. * Creates a torus knot geometry
  40815. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40816. */
  40817. var TorusKnotGeometry = /** @class */ (function (_super) {
  40818. __extends(TorusKnotGeometry, _super);
  40819. /**
  40820. * Creates a torus knot geometry
  40821. * @param id defines the unique ID of the geometry
  40822. * @param scene defines the hosting scene
  40823. * @param radius defines the radius of the torus knot
  40824. * @param tube defines the thickness of the torus knot tube
  40825. * @param radialSegments defines the number of radial segments
  40826. * @param tubularSegments defines the number of tubular segments
  40827. * @param p defines the first number of windings
  40828. * @param q defines the second number of windings
  40829. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40830. * @param mesh defines the hosting mesh (can be null)
  40831. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40832. */
  40833. function TorusKnotGeometry(id, scene,
  40834. /**
  40835. * Defines the radius of the torus knot
  40836. */
  40837. radius,
  40838. /**
  40839. * Defines the thickness of the torus knot tube
  40840. */
  40841. tube,
  40842. /**
  40843. * Defines the number of radial segments
  40844. */
  40845. radialSegments,
  40846. /**
  40847. * Defines the number of tubular segments
  40848. */
  40849. tubularSegments,
  40850. /**
  40851. * Defines the first number of windings
  40852. */
  40853. p,
  40854. /**
  40855. * Defines the second number of windings
  40856. */
  40857. q, canBeRegenerated, mesh,
  40858. /**
  40859. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40860. */
  40861. side) {
  40862. if (mesh === void 0) { mesh = null; }
  40863. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40864. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40865. _this.radius = radius;
  40866. _this.tube = tube;
  40867. _this.radialSegments = radialSegments;
  40868. _this.tubularSegments = tubularSegments;
  40869. _this.p = p;
  40870. _this.q = q;
  40871. _this.side = side;
  40872. return _this;
  40873. }
  40874. /** @hidden */
  40875. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40876. 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 });
  40877. };
  40878. TorusKnotGeometry.prototype.copy = function (id) {
  40879. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40880. };
  40881. TorusKnotGeometry.prototype.serialize = function () {
  40882. var serializationObject = _super.prototype.serialize.call(this);
  40883. serializationObject.radius = this.radius;
  40884. serializationObject.tube = this.tube;
  40885. serializationObject.radialSegments = this.radialSegments;
  40886. serializationObject.tubularSegments = this.tubularSegments;
  40887. serializationObject.p = this.p;
  40888. serializationObject.q = this.q;
  40889. return serializationObject;
  40890. };
  40891. ;
  40892. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40893. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40894. return null; // null since geometry could be something else than a ground...
  40895. }
  40896. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40897. if (BABYLON.Tags) {
  40898. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40899. }
  40900. scene.pushGeometry(torusKnot, true);
  40901. return torusKnot;
  40902. };
  40903. return TorusKnotGeometry;
  40904. }(_PrimitiveGeometry));
  40905. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40906. //}
  40907. })(BABYLON || (BABYLON = {}));
  40908. //# sourceMappingURL=babylon.geometry.js.map
  40909. var BABYLON;
  40910. (function (BABYLON) {
  40911. /**
  40912. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40913. */
  40914. var PerformanceMonitor = /** @class */ (function () {
  40915. /**
  40916. * constructor
  40917. * @param frameSampleSize The number of samples required to saturate the sliding window
  40918. */
  40919. function PerformanceMonitor(frameSampleSize) {
  40920. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40921. this._enabled = true;
  40922. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40923. }
  40924. /**
  40925. * Samples current frame
  40926. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40927. */
  40928. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40929. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40930. if (!this._enabled)
  40931. return;
  40932. if (this._lastFrameTimeMs != null) {
  40933. var dt = timeMs - this._lastFrameTimeMs;
  40934. this._rollingFrameTime.add(dt);
  40935. }
  40936. this._lastFrameTimeMs = timeMs;
  40937. };
  40938. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40939. /**
  40940. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40941. * @return Average frame time in milliseconds
  40942. */
  40943. get: function () {
  40944. return this._rollingFrameTime.average;
  40945. },
  40946. enumerable: true,
  40947. configurable: true
  40948. });
  40949. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40950. /**
  40951. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40952. * @return Frame time variance in milliseconds squared
  40953. */
  40954. get: function () {
  40955. return this._rollingFrameTime.variance;
  40956. },
  40957. enumerable: true,
  40958. configurable: true
  40959. });
  40960. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40961. /**
  40962. * Returns the frame time of the most recent frame
  40963. * @return Frame time in milliseconds
  40964. */
  40965. get: function () {
  40966. return this._rollingFrameTime.history(0);
  40967. },
  40968. enumerable: true,
  40969. configurable: true
  40970. });
  40971. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40972. /**
  40973. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40974. * @return Framerate in frames per second
  40975. */
  40976. get: function () {
  40977. return 1000.0 / this._rollingFrameTime.average;
  40978. },
  40979. enumerable: true,
  40980. configurable: true
  40981. });
  40982. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40983. /**
  40984. * Returns the average framerate in frames per second using the most recent frame time
  40985. * @return Framerate in frames per second
  40986. */
  40987. get: function () {
  40988. var history = this._rollingFrameTime.history(0);
  40989. if (history === 0) {
  40990. return 0;
  40991. }
  40992. return 1000.0 / history;
  40993. },
  40994. enumerable: true,
  40995. configurable: true
  40996. });
  40997. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40998. /**
  40999. * Returns true if enough samples have been taken to completely fill the sliding window
  41000. * @return true if saturated
  41001. */
  41002. get: function () {
  41003. return this._rollingFrameTime.isSaturated();
  41004. },
  41005. enumerable: true,
  41006. configurable: true
  41007. });
  41008. /**
  41009. * Enables contributions to the sliding window sample set
  41010. */
  41011. PerformanceMonitor.prototype.enable = function () {
  41012. this._enabled = true;
  41013. };
  41014. /**
  41015. * Disables contributions to the sliding window sample set
  41016. * Samples will not be interpolated over the disabled period
  41017. */
  41018. PerformanceMonitor.prototype.disable = function () {
  41019. this._enabled = false;
  41020. //clear last sample to avoid interpolating over the disabled period when next enabled
  41021. this._lastFrameTimeMs = null;
  41022. };
  41023. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  41024. /**
  41025. * Returns true if sampling is enabled
  41026. * @return true if enabled
  41027. */
  41028. get: function () {
  41029. return this._enabled;
  41030. },
  41031. enumerable: true,
  41032. configurable: true
  41033. });
  41034. /**
  41035. * Resets performance monitor
  41036. */
  41037. PerformanceMonitor.prototype.reset = function () {
  41038. //clear last sample to avoid interpolating over the disabled period when next enabled
  41039. this._lastFrameTimeMs = null;
  41040. //wipe record
  41041. this._rollingFrameTime.reset();
  41042. };
  41043. return PerformanceMonitor;
  41044. }());
  41045. BABYLON.PerformanceMonitor = PerformanceMonitor;
  41046. /**
  41047. * RollingAverage
  41048. *
  41049. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  41050. */
  41051. var RollingAverage = /** @class */ (function () {
  41052. /**
  41053. * constructor
  41054. * @param length The number of samples required to saturate the sliding window
  41055. */
  41056. function RollingAverage(length) {
  41057. this._samples = new Array(length);
  41058. this.reset();
  41059. }
  41060. /**
  41061. * Adds a sample to the sample set
  41062. * @param v The sample value
  41063. */
  41064. RollingAverage.prototype.add = function (v) {
  41065. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  41066. var delta;
  41067. //we need to check if we've already wrapped round
  41068. if (this.isSaturated()) {
  41069. //remove bottom of stack from mean
  41070. var bottomValue = this._samples[this._pos];
  41071. delta = bottomValue - this.average;
  41072. this.average -= delta / (this._sampleCount - 1);
  41073. this._m2 -= delta * (bottomValue - this.average);
  41074. }
  41075. else {
  41076. this._sampleCount++;
  41077. }
  41078. //add new value to mean
  41079. delta = v - this.average;
  41080. this.average += delta / (this._sampleCount);
  41081. this._m2 += delta * (v - this.average);
  41082. //set the new variance
  41083. this.variance = this._m2 / (this._sampleCount - 1);
  41084. this._samples[this._pos] = v;
  41085. this._pos++;
  41086. this._pos %= this._samples.length; //positive wrap around
  41087. };
  41088. /**
  41089. * Returns previously added values or null if outside of history or outside the sliding window domain
  41090. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41091. * @return Value previously recorded with add() or null if outside of range
  41092. */
  41093. RollingAverage.prototype.history = function (i) {
  41094. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41095. return 0;
  41096. }
  41097. var i0 = this._wrapPosition(this._pos - 1.0);
  41098. return this._samples[this._wrapPosition(i0 - i)];
  41099. };
  41100. /**
  41101. * Returns true if enough samples have been taken to completely fill the sliding window
  41102. * @return true if sample-set saturated
  41103. */
  41104. RollingAverage.prototype.isSaturated = function () {
  41105. return this._sampleCount >= this._samples.length;
  41106. };
  41107. /**
  41108. * Resets the rolling average (equivalent to 0 samples taken so far)
  41109. */
  41110. RollingAverage.prototype.reset = function () {
  41111. this.average = 0;
  41112. this.variance = 0;
  41113. this._sampleCount = 0;
  41114. this._pos = 0;
  41115. this._m2 = 0;
  41116. };
  41117. /**
  41118. * Wraps a value around the sample range boundaries
  41119. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41120. * @return Wrapped position in sample range
  41121. */
  41122. RollingAverage.prototype._wrapPosition = function (i) {
  41123. var max = this._samples.length;
  41124. return ((i % max) + max) % max;
  41125. };
  41126. return RollingAverage;
  41127. }());
  41128. BABYLON.RollingAverage = RollingAverage;
  41129. })(BABYLON || (BABYLON = {}));
  41130. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41131. var BABYLON;
  41132. (function (BABYLON) {
  41133. /**
  41134. * "Static Class" containing the most commonly used helper while dealing with material for
  41135. * rendering purpose.
  41136. *
  41137. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41138. *
  41139. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41140. */
  41141. var MaterialHelper = /** @class */ (function () {
  41142. function MaterialHelper() {
  41143. }
  41144. /**
  41145. * Bind the current view position to an effect.
  41146. * @param effect The effect to be bound
  41147. * @param scene The scene the eyes position is used from
  41148. */
  41149. MaterialHelper.BindEyePosition = function (effect, scene) {
  41150. if (scene._forcedViewPosition) {
  41151. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41152. return;
  41153. }
  41154. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41155. };
  41156. /**
  41157. * Helps preparing the defines values about the UVs in used in the effect.
  41158. * UVs are shared as much as we can accross chanels in the shaders.
  41159. * @param texture The texture we are preparing the UVs for
  41160. * @param defines The defines to update
  41161. * @param key The chanel key "diffuse", "specular"... used in the shader
  41162. */
  41163. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41164. defines._needUVs = true;
  41165. defines[key] = true;
  41166. if (texture.getTextureMatrix().isIdentity(true)) {
  41167. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41168. if (texture.coordinatesIndex === 0) {
  41169. defines["MAINUV1"] = true;
  41170. }
  41171. else {
  41172. defines["MAINUV2"] = true;
  41173. }
  41174. }
  41175. else {
  41176. defines[key + "DIRECTUV"] = 0;
  41177. }
  41178. };
  41179. /**
  41180. * Binds a texture matrix value to its corrsponding uniform
  41181. * @param texture The texture to bind the matrix for
  41182. * @param uniformBuffer The uniform buffer receivin the data
  41183. * @param key The chanel key "diffuse", "specular"... used in the shader
  41184. */
  41185. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41186. var matrix = texture.getTextureMatrix();
  41187. if (!matrix.isIdentity(true)) {
  41188. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41189. }
  41190. };
  41191. /**
  41192. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41193. * @param mesh defines the current mesh
  41194. * @param scene defines the current scene
  41195. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41196. * @param pointsCloud defines if point cloud rendering has to be turned on
  41197. * @param fogEnabled defines if fog has to be turned on
  41198. * @param alphaTest defines if alpha testing has to be turned on
  41199. * @param defines defines the current list of defines
  41200. */
  41201. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41202. if (defines._areMiscDirty) {
  41203. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41204. defines["POINTSIZE"] = pointsCloud;
  41205. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41206. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41207. defines["ALPHATEST"] = alphaTest;
  41208. }
  41209. };
  41210. /**
  41211. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41212. * @param scene defines the current scene
  41213. * @param engine defines the current engine
  41214. * @param defines specifies the list of active defines
  41215. * @param useInstances defines if instances have to be turned on
  41216. * @param useClipPlane defines if clip plane have to be turned on
  41217. */
  41218. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41219. if (useClipPlane === void 0) { useClipPlane = null; }
  41220. var changed = false;
  41221. var useClipPlane1 = false;
  41222. var useClipPlane2 = false;
  41223. var useClipPlane3 = false;
  41224. var useClipPlane4 = false;
  41225. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  41226. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  41227. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  41228. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  41229. if (defines["CLIPPLANE"] !== useClipPlane1) {
  41230. defines["CLIPPLANE"] = useClipPlane1;
  41231. changed = true;
  41232. }
  41233. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  41234. defines["CLIPPLANE2"] = useClipPlane2;
  41235. changed = true;
  41236. }
  41237. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  41238. defines["CLIPPLANE3"] = useClipPlane3;
  41239. changed = true;
  41240. }
  41241. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  41242. defines["CLIPPLANE4"] = useClipPlane4;
  41243. changed = true;
  41244. }
  41245. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41246. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41247. changed = true;
  41248. }
  41249. if (defines["INSTANCES"] !== useInstances) {
  41250. defines["INSTANCES"] = useInstances;
  41251. changed = true;
  41252. }
  41253. if (changed) {
  41254. defines.markAsUnprocessed();
  41255. }
  41256. };
  41257. /**
  41258. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41259. * @param mesh The mesh containing the geometry data we will draw
  41260. * @param defines The defines to update
  41261. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41262. * @param useBones Precise whether bones should be used or not (override mesh info)
  41263. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41264. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41265. * @returns false if defines are considered not dirty and have not been checked
  41266. */
  41267. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41268. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41269. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41270. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41271. return false;
  41272. }
  41273. defines._normals = defines._needNormals;
  41274. defines._uvs = defines._needUVs;
  41275. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41276. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41277. defines["TANGENT"] = true;
  41278. }
  41279. if (defines._needUVs) {
  41280. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41281. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41282. }
  41283. else {
  41284. defines["UV1"] = false;
  41285. defines["UV2"] = false;
  41286. }
  41287. if (useVertexColor) {
  41288. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41289. defines["VERTEXCOLOR"] = hasVertexColors;
  41290. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41291. }
  41292. if (useBones) {
  41293. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41294. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41295. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41296. }
  41297. else {
  41298. defines["NUM_BONE_INFLUENCERS"] = 0;
  41299. defines["BonesPerMesh"] = 0;
  41300. }
  41301. }
  41302. if (useMorphTargets) {
  41303. var manager = mesh.morphTargetManager;
  41304. if (manager) {
  41305. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41306. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41307. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41308. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41309. }
  41310. else {
  41311. defines["MORPHTARGETS_TANGENT"] = false;
  41312. defines["MORPHTARGETS_NORMAL"] = false;
  41313. defines["MORPHTARGETS"] = false;
  41314. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41315. }
  41316. }
  41317. return true;
  41318. };
  41319. /**
  41320. * Prepares the defines related to the light information passed in parameter
  41321. * @param scene The scene we are intending to draw
  41322. * @param mesh The mesh the effect is compiling for
  41323. * @param defines The defines to update
  41324. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41325. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41326. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41327. * @returns true if normals will be required for the rest of the effect
  41328. */
  41329. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41330. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41331. if (disableLighting === void 0) { disableLighting = false; }
  41332. if (!defines._areLightsDirty) {
  41333. return defines._needNormals;
  41334. }
  41335. var lightIndex = 0;
  41336. var needNormals = false;
  41337. var needRebuild = false;
  41338. var lightmapMode = false;
  41339. var shadowEnabled = false;
  41340. var specularEnabled = false;
  41341. if (scene.lightsEnabled && !disableLighting) {
  41342. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41343. var light = _a[_i];
  41344. needNormals = true;
  41345. if (defines["LIGHT" + lightIndex] === undefined) {
  41346. needRebuild = true;
  41347. }
  41348. defines["LIGHT" + lightIndex] = true;
  41349. defines["SPOTLIGHT" + lightIndex] = false;
  41350. defines["HEMILIGHT" + lightIndex] = false;
  41351. defines["POINTLIGHT" + lightIndex] = false;
  41352. defines["DIRLIGHT" + lightIndex] = false;
  41353. light.prepareLightSpecificDefines(defines, lightIndex);
  41354. // FallOff.
  41355. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  41356. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  41357. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  41358. switch (light.falloffType) {
  41359. case BABYLON.Light.FALLOFF_GLTF:
  41360. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  41361. break;
  41362. case BABYLON.Light.FALLOFF_PHYSICAL:
  41363. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  41364. break;
  41365. case BABYLON.Light.FALLOFF_STANDARD:
  41366. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  41367. break;
  41368. }
  41369. // Specular
  41370. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41371. specularEnabled = true;
  41372. }
  41373. // Shadows
  41374. defines["SHADOW" + lightIndex] = false;
  41375. defines["SHADOWPCF" + lightIndex] = false;
  41376. defines["SHADOWPCSS" + lightIndex] = false;
  41377. defines["SHADOWPOISSON" + lightIndex] = false;
  41378. defines["SHADOWESM" + lightIndex] = false;
  41379. defines["SHADOWCUBE" + lightIndex] = false;
  41380. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41381. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41382. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41383. var shadowGenerator = light.getShadowGenerator();
  41384. if (shadowGenerator) {
  41385. var shadowMap = shadowGenerator.getShadowMap();
  41386. if (shadowMap) {
  41387. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  41388. shadowEnabled = true;
  41389. shadowGenerator.prepareDefines(defines, lightIndex);
  41390. }
  41391. }
  41392. }
  41393. }
  41394. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41395. lightmapMode = true;
  41396. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41397. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41398. }
  41399. else {
  41400. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41401. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41402. }
  41403. lightIndex++;
  41404. if (lightIndex === maxSimultaneousLights)
  41405. break;
  41406. }
  41407. }
  41408. defines["SPECULARTERM"] = specularEnabled;
  41409. defines["SHADOWS"] = shadowEnabled;
  41410. // Resetting all other lights if any
  41411. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41412. if (defines["LIGHT" + index] !== undefined) {
  41413. defines["LIGHT" + index] = false;
  41414. defines["HEMILIGHT" + lightIndex] = false;
  41415. defines["POINTLIGHT" + lightIndex] = false;
  41416. defines["DIRLIGHT" + lightIndex] = false;
  41417. defines["SPOTLIGHT" + lightIndex] = false;
  41418. defines["SHADOW" + lightIndex] = false;
  41419. }
  41420. }
  41421. var caps = scene.getEngine().getCaps();
  41422. if (defines["SHADOWFLOAT"] === undefined) {
  41423. needRebuild = true;
  41424. }
  41425. defines["SHADOWFLOAT"] = shadowEnabled &&
  41426. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41427. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41428. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41429. if (needRebuild) {
  41430. defines.rebuild();
  41431. }
  41432. return needNormals;
  41433. };
  41434. /**
  41435. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41436. * that won t be acctive due to defines being turned off.
  41437. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41438. * @param samplersList The samplers list
  41439. * @param defines The defines helping in the list generation
  41440. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41441. */
  41442. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41443. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41444. var uniformsList;
  41445. var uniformBuffersList = null;
  41446. if (uniformsListOrOptions.uniformsNames) {
  41447. var options = uniformsListOrOptions;
  41448. uniformsList = options.uniformsNames;
  41449. uniformBuffersList = options.uniformBuffersNames;
  41450. samplersList = options.samplers;
  41451. defines = options.defines;
  41452. maxSimultaneousLights = options.maxSimultaneousLights;
  41453. }
  41454. else {
  41455. uniformsList = uniformsListOrOptions;
  41456. if (!samplersList) {
  41457. samplersList = [];
  41458. }
  41459. }
  41460. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41461. if (!defines["LIGHT" + lightIndex]) {
  41462. break;
  41463. }
  41464. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41465. if (uniformBuffersList) {
  41466. uniformBuffersList.push("Light" + lightIndex);
  41467. }
  41468. samplersList.push("shadowSampler" + lightIndex);
  41469. samplersList.push("depthSampler" + lightIndex);
  41470. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41471. samplersList.push("projectionLightSampler" + lightIndex);
  41472. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41473. }
  41474. }
  41475. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41476. uniformsList.push("morphTargetInfluences");
  41477. }
  41478. };
  41479. /**
  41480. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41481. * @param defines The defines to update while falling back
  41482. * @param fallbacks The authorized effect fallbacks
  41483. * @param maxSimultaneousLights The maximum number of lights allowed
  41484. * @param rank the current rank of the Effect
  41485. * @returns The newly affected rank
  41486. */
  41487. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41488. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41489. if (rank === void 0) { rank = 0; }
  41490. var lightFallbackRank = 0;
  41491. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41492. if (!defines["LIGHT" + lightIndex]) {
  41493. break;
  41494. }
  41495. if (lightIndex > 0) {
  41496. lightFallbackRank = rank + lightIndex;
  41497. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41498. }
  41499. if (!defines["SHADOWS"]) {
  41500. if (defines["SHADOW" + lightIndex]) {
  41501. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41502. }
  41503. if (defines["SHADOWPCF" + lightIndex]) {
  41504. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41505. }
  41506. if (defines["SHADOWPCSS" + lightIndex]) {
  41507. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41508. }
  41509. if (defines["SHADOWPOISSON" + lightIndex]) {
  41510. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41511. }
  41512. if (defines["SHADOWESM" + lightIndex]) {
  41513. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41514. }
  41515. }
  41516. }
  41517. return lightFallbackRank++;
  41518. };
  41519. /**
  41520. * Prepares the list of attributes required for morph targets according to the effect defines.
  41521. * @param attribs The current list of supported attribs
  41522. * @param mesh The mesh to prepare the morph targets attributes for
  41523. * @param defines The current Defines of the effect
  41524. */
  41525. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41526. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41527. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41528. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41529. var manager = mesh.morphTargetManager;
  41530. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41531. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41532. for (var index = 0; index < influencers; index++) {
  41533. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41534. if (normal) {
  41535. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41536. }
  41537. if (tangent) {
  41538. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41539. }
  41540. if (attribs.length > maxAttributesCount) {
  41541. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41542. }
  41543. }
  41544. }
  41545. };
  41546. /**
  41547. * Prepares the list of attributes required for bones according to the effect defines.
  41548. * @param attribs The current list of supported attribs
  41549. * @param mesh The mesh to prepare the bones attributes for
  41550. * @param defines The current Defines of the effect
  41551. * @param fallbacks The current efffect fallback strategy
  41552. */
  41553. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41554. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41555. fallbacks.addCPUSkinningFallback(0, mesh);
  41556. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41557. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41558. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41559. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41560. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41561. }
  41562. }
  41563. };
  41564. /**
  41565. * Prepares the list of attributes required for instances according to the effect defines.
  41566. * @param attribs The current list of supported attribs
  41567. * @param defines The current Defines of the effect
  41568. */
  41569. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41570. if (defines["INSTANCES"]) {
  41571. attribs.push("world0");
  41572. attribs.push("world1");
  41573. attribs.push("world2");
  41574. attribs.push("world3");
  41575. }
  41576. };
  41577. /**
  41578. * Binds the light shadow information to the effect for the given mesh.
  41579. * @param light The light containing the generator
  41580. * @param scene The scene the lights belongs to
  41581. * @param mesh The mesh we are binding the information to render
  41582. * @param lightIndex The light index in the effect used to render the mesh
  41583. * @param effect The effect we are binding the data to
  41584. */
  41585. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41586. if (light.shadowEnabled && mesh.receiveShadows) {
  41587. var shadowGenerator = light.getShadowGenerator();
  41588. if (shadowGenerator) {
  41589. shadowGenerator.bindShadowLight(lightIndex, effect);
  41590. }
  41591. }
  41592. };
  41593. /**
  41594. * Binds the light information to the effect.
  41595. * @param light The light containing the generator
  41596. * @param effect The effect we are binding the data to
  41597. * @param lightIndex The light index in the effect used to render
  41598. */
  41599. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41600. light.transferToEffect(effect, lightIndex + "");
  41601. };
  41602. /**
  41603. * Binds the lights information from the scene to the effect for the given mesh.
  41604. * @param scene The scene the lights belongs to
  41605. * @param mesh The mesh we are binding the information to render
  41606. * @param effect The effect we are binding the data to
  41607. * @param defines The generated defines for the effect
  41608. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41609. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41610. */
  41611. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41612. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41613. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41614. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41615. for (var i = 0; i < len; i++) {
  41616. var light = mesh._lightSources[i];
  41617. var iAsString = i.toString();
  41618. var scaledIntensity = light.getScaledIntensity();
  41619. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41620. MaterialHelper.BindLightProperties(light, effect, i);
  41621. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41622. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41623. if (defines["SPECULARTERM"]) {
  41624. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41625. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41626. }
  41627. // Shadows
  41628. if (scene.shadowsEnabled) {
  41629. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41630. }
  41631. light._uniformBuffer.update();
  41632. }
  41633. };
  41634. /**
  41635. * Binds the fog information from the scene to the effect for the given mesh.
  41636. * @param scene The scene the lights belongs to
  41637. * @param mesh The mesh we are binding the information to render
  41638. * @param effect The effect we are binding the data to
  41639. */
  41640. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41641. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41642. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41643. effect.setColor3("vFogColor", scene.fogColor);
  41644. }
  41645. };
  41646. /**
  41647. * Binds the bones information from the mesh to the effect.
  41648. * @param mesh The mesh we are binding the information to render
  41649. * @param effect The effect we are binding the data to
  41650. */
  41651. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41652. if (!effect || !mesh) {
  41653. return;
  41654. }
  41655. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41656. mesh.computeBonesUsingShaders = false;
  41657. }
  41658. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41659. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41660. if (matrices) {
  41661. effect.setMatrices("mBones", matrices);
  41662. }
  41663. }
  41664. };
  41665. /**
  41666. * Binds the morph targets information from the mesh to the effect.
  41667. * @param abstractMesh The mesh we are binding the information to render
  41668. * @param effect The effect we are binding the data to
  41669. */
  41670. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41671. var manager = abstractMesh.morphTargetManager;
  41672. if (!abstractMesh || !manager) {
  41673. return;
  41674. }
  41675. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41676. };
  41677. /**
  41678. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41679. * @param defines The generated defines used in the effect
  41680. * @param effect The effect we are binding the data to
  41681. * @param scene The scene we are willing to render with logarithmic scale for
  41682. */
  41683. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41684. if (defines["LOGARITHMICDEPTH"]) {
  41685. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41686. }
  41687. };
  41688. /**
  41689. * Binds the clip plane information from the scene to the effect.
  41690. * @param scene The scene the clip plane information are extracted from
  41691. * @param effect The effect we are binding the data to
  41692. */
  41693. MaterialHelper.BindClipPlane = function (effect, scene) {
  41694. if (scene.clipPlane) {
  41695. var clipPlane = scene.clipPlane;
  41696. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41697. }
  41698. if (scene.clipPlane2) {
  41699. var clipPlane = scene.clipPlane2;
  41700. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41701. }
  41702. if (scene.clipPlane3) {
  41703. var clipPlane = scene.clipPlane3;
  41704. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41705. }
  41706. if (scene.clipPlane4) {
  41707. var clipPlane = scene.clipPlane4;
  41708. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41709. }
  41710. };
  41711. return MaterialHelper;
  41712. }());
  41713. BABYLON.MaterialHelper = MaterialHelper;
  41714. })(BABYLON || (BABYLON = {}));
  41715. //# sourceMappingURL=babylon.materialHelper.js.map
  41716. var BABYLON;
  41717. (function (BABYLON) {
  41718. var PushMaterial = /** @class */ (function (_super) {
  41719. __extends(PushMaterial, _super);
  41720. function PushMaterial(name, scene) {
  41721. var _this = _super.call(this, name, scene) || this;
  41722. _this._normalMatrix = new BABYLON.Matrix();
  41723. _this.storeEffectOnSubMeshes = true;
  41724. return _this;
  41725. }
  41726. PushMaterial.prototype.getEffect = function () {
  41727. return this._activeEffect;
  41728. };
  41729. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41730. if (!mesh) {
  41731. return false;
  41732. }
  41733. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41734. return true;
  41735. }
  41736. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41737. };
  41738. /**
  41739. * Binds the given world matrix to the active effect
  41740. *
  41741. * @param world the matrix to bind
  41742. */
  41743. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41744. this._activeEffect.setMatrix("world", world);
  41745. };
  41746. /**
  41747. * Binds the given normal matrix to the active effect
  41748. *
  41749. * @param normalMatrix the matrix to bind
  41750. */
  41751. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41752. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41753. };
  41754. PushMaterial.prototype.bind = function (world, mesh) {
  41755. if (!mesh) {
  41756. return;
  41757. }
  41758. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41759. };
  41760. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41761. if (effect === void 0) { effect = null; }
  41762. _super.prototype._afterBind.call(this, mesh);
  41763. this.getScene()._cachedEffect = effect;
  41764. };
  41765. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41766. if (visibility === void 0) { visibility = 1; }
  41767. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41768. };
  41769. return PushMaterial;
  41770. }(BABYLON.Material));
  41771. BABYLON.PushMaterial = PushMaterial;
  41772. })(BABYLON || (BABYLON = {}));
  41773. //# sourceMappingURL=babylon.pushMaterial.js.map
  41774. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;\nvarying float fClipDistance4;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n#ifdef CLIPPLANE2\nfClipDistance2=dot(worldPos,vClipPlane2);\n#endif\n#ifdef CLIPPLANE3\nfClipDistance3=dot(worldPos,vClipPlane3);\n#endif\n#ifdef CLIPPLANE4\nfClipDistance4=dot(worldPos,vClipPlane4);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}\n\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=max(0.0000001,max(color.r,max(color.g,color.b)));\nfloat D=max(rgbdMaxRange/maxRGB,1.);\nD=clamp(floor(D)/255.0,0.,1.);\n\nvec3 rgb=color.rgb*D;\n\nrgb=toGammaSpace(rgb);\nreturn vec4(rgb,D); \n}\nvec3 fromRGBD(vec4 rgbd) {\n\nrgbd.rgb=toLinearSpace(rgbd.rgb);\n\nreturn rgbd.rgb/rgbd.a;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\nuniform vec4 vLightFalloff{X};\n#elif defined(POINTLIGHT{X})\nuniform vec4 vLightFalloff{X};\n#elif defined(HEMILIGHT{X})\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\nvec4 vLightFalloff;\n#elif defined(POINTLIGHT{X})\nvec4 vLightFalloff;\n#elif defined(HEMILIGHT{X})\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat lon=atan(direction.z,direction.x);\nfloat lat=acos(direction.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=normalize(reflect(cameraToVertex,worldNormal));\nfloat lon=atan(r.z,r.x);\nfloat lat=acos(r.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\n#ifdef TONEMAPPING_ACES\n\n\n\n\n\nconst mat3 ACESInputMat=mat3(\nvec3(0.59719,0.07600,0.02840),\nvec3(0.35458,0.90834,0.13383),\nvec3(0.04823,0.01566,0.83777)\n);\n\nconst mat3 ACESOutputMat=mat3(\nvec3( 1.60475,-0.10208,-0.00327),\nvec3(-0.53108,1.10813,-0.07276),\nvec3(-0.07367,-0.00605,1.07602)\n);\nvec3 RRTAndODTFit(vec3 v)\n{\nvec3 a=v*(v+0.0245786)-0.000090537;\nvec3 b=v*(0.983729*v+0.4329510)+0.238081;\nreturn a/b;\n}\nvec3 ACESFitted(vec3 color)\n{\ncolor=ACESInputMat*color;\n\ncolor=RRTAndODTFit(color);\ncolor=ACESOutputMat*color;\n\ncolor=clamp(color,0.0,1.0);\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\n#ifdef TONEMAPPING_ACES\nresult.rgb=ACESFitted(result.rgb);\n#else\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nvarying float fClipDistance4;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE2\nif (fClipDistance2>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE3\nif (fClipDistance3>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE4\nif (fClipDistance4>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\nspotInfo=computeSpotLightingInfo(light{X}.vLightData);\n#ifdef LIGHT_FALLOFF_GLTF{X}\nspotInfo.attenuation=computeDistanceLightFalloff_GLTF(spotInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\nspotInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\nspotInfo.attenuation=computeDistanceLightFalloff_Physical(spotInfo.lightDistanceSquared);\nspotInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\nspotInfo.attenuation=computeDistanceLightFalloff_Standard(spotInfo.lightOffset,light{X}.vLightFalloff.x);\nspotInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w,light{X}.vLightData.w);\n#else\nspotInfo.attenuation=computeDistanceLightFalloff(spotInfo.lightOffset,spotInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\nspotInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#endif\ninfo=computeSpotLighting(spotInfo,viewDirectionW,normalW,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(POINTLIGHT{X})\npointInfo=computePointLightingInfo(light{X}.vLightData);\n#ifdef LIGHT_FALLOFF_GLTF{X}\npointInfo.attenuation=computeDistanceLightFalloff_GLTF(pointInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npointInfo.attenuation=computeDistanceLightFalloff_Physical(pointInfo.lightDistanceSquared);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npointInfo.attenuation=computeDistanceLightFalloff_Standard(pointInfo.lightOffset,light{X}.vLightFalloff.x);\n#else\npointInfo.attenuation=computeDistanceLightFalloff(pointInfo.lightOffset,pointInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\n#endif\ninfo=computePointLighting(pointInfo,viewDirectionW,normalW,light{X}.vLightDiffuse.rgb,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(DIRLIGHT{X})\ninfo=computeDirectionalLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF)\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nstruct pointLightingInfo\n{\nvec3 lightOffset;\nfloat lightDistanceSquared;\nfloat attenuation;\n};\nstruct spotLightingInfo\n{\nvec3 lightOffset;\nfloat lightDistanceSquared;\nvec3 directionToLightCenterW;\nfloat attenuation;\n};\nfloat computeDistanceLightFalloff_Standard(vec3 lightOffset,float range)\n{\nreturn max(0.,1.0-length(lightOffset)/range);\n}\nfloat computeDistanceLightFalloff_Physical(float lightDistanceSquared)\n{\nreturn 1.0/((lightDistanceSquared+0.001));\n}\nfloat computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange)\n{\nconst float minDistanceSquared=0.01*0.01;\nfloat lightDistanceFalloff=1.0/(max(lightDistanceSquared,minDistanceSquared));\nfloat factor=lightDistanceSquared*inverseSquaredRange;\nfloat attenuation=clamp(1.0-factor*factor,0.,1.);\nattenuation*=attenuation;\n\nlightDistanceFalloff*=attenuation;\nreturn lightDistanceFalloff;\n}\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDistanceLightFalloff_Physical(lightDistanceSquared);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange);\n#else\nreturn computeDistanceLightFalloff_Standard(lightOffset,range);\n#endif\n}\nfloat computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle)\n{\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfloat falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset)\n{\n\n\n\nfloat cd=dot(-lightDirection,directionToLightCenterW);\nfloat falloff=clamp(cd*lightAngleScale+lightAngleOffset,0.,1.);\n\nfalloff*=falloff;\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset);\n#else\nreturn computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent);\n#endif\n}\npointLightingInfo computePointLightingInfo(vec4 lightData) {\npointLightingInfo result;\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\nreturn result;\n}\nspotLightingInfo computeSpotLightingInfo(vec4 lightData) {\nspotLightingInfo result;\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.directionToLightCenterW=normalize(result.lightOffset);\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\nreturn result;\n}\nlightingInfo computePointLighting(pointLightingInfo info,vec3 viewDirectionW,vec3 vNormal,vec3 diffuseColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nfloat lightDistance=sqrt(info.lightDistanceSquared);\nvec3 lightDirection=normalize(info.lightOffset);\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*info.attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*info.attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(spotLightingInfo info,vec3 viewDirectionW,vec3 vNormal,vec4 lightDirection,vec3 diffuseColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\nfloat lightDistance=sqrt(info.lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+info.directionToLightCenterW);\nNdotL=clamp(dot(vNormal,info.directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*info.attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*info.attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeDirectionalLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nfloat lightDistance=length(-lightData.xyz);\nvec3 lightDirection=normalize(-lightData.xyz);\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","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};"};
  41775. var BABYLON;
  41776. (function (BABYLON) {
  41777. /** @hidden */
  41778. var StandardMaterialDefines = /** @class */ (function (_super) {
  41779. __extends(StandardMaterialDefines, _super);
  41780. function StandardMaterialDefines() {
  41781. var _this = _super.call(this) || this;
  41782. _this.MAINUV1 = false;
  41783. _this.MAINUV2 = false;
  41784. _this.DIFFUSE = false;
  41785. _this.DIFFUSEDIRECTUV = 0;
  41786. _this.AMBIENT = false;
  41787. _this.AMBIENTDIRECTUV = 0;
  41788. _this.OPACITY = false;
  41789. _this.OPACITYDIRECTUV = 0;
  41790. _this.OPACITYRGB = false;
  41791. _this.REFLECTION = false;
  41792. _this.EMISSIVE = false;
  41793. _this.EMISSIVEDIRECTUV = 0;
  41794. _this.SPECULAR = false;
  41795. _this.SPECULARDIRECTUV = 0;
  41796. _this.BUMP = false;
  41797. _this.BUMPDIRECTUV = 0;
  41798. _this.PARALLAX = false;
  41799. _this.PARALLAXOCCLUSION = false;
  41800. _this.SPECULAROVERALPHA = false;
  41801. _this.CLIPPLANE = false;
  41802. _this.CLIPPLANE2 = false;
  41803. _this.CLIPPLANE3 = false;
  41804. _this.CLIPPLANE4 = false;
  41805. _this.ALPHATEST = false;
  41806. _this.DEPTHPREPASS = false;
  41807. _this.ALPHAFROMDIFFUSE = false;
  41808. _this.POINTSIZE = false;
  41809. _this.FOG = false;
  41810. _this.SPECULARTERM = false;
  41811. _this.DIFFUSEFRESNEL = false;
  41812. _this.OPACITYFRESNEL = false;
  41813. _this.REFLECTIONFRESNEL = false;
  41814. _this.REFRACTIONFRESNEL = false;
  41815. _this.EMISSIVEFRESNEL = false;
  41816. _this.FRESNEL = false;
  41817. _this.NORMAL = false;
  41818. _this.UV1 = false;
  41819. _this.UV2 = false;
  41820. _this.VERTEXCOLOR = false;
  41821. _this.VERTEXALPHA = false;
  41822. _this.NUM_BONE_INFLUENCERS = 0;
  41823. _this.BonesPerMesh = 0;
  41824. _this.INSTANCES = false;
  41825. _this.GLOSSINESS = false;
  41826. _this.ROUGHNESS = false;
  41827. _this.EMISSIVEASILLUMINATION = false;
  41828. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41829. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41830. _this.LIGHTMAP = false;
  41831. _this.LIGHTMAPDIRECTUV = 0;
  41832. _this.OBJECTSPACE_NORMALMAP = false;
  41833. _this.USELIGHTMAPASSHADOWMAP = false;
  41834. _this.REFLECTIONMAP_3D = false;
  41835. _this.REFLECTIONMAP_SPHERICAL = false;
  41836. _this.REFLECTIONMAP_PLANAR = false;
  41837. _this.REFLECTIONMAP_CUBIC = false;
  41838. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41839. _this.REFLECTIONMAP_PROJECTION = false;
  41840. _this.REFLECTIONMAP_SKYBOX = false;
  41841. _this.REFLECTIONMAP_EXPLICIT = false;
  41842. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41843. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41844. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41845. _this.INVERTCUBICMAP = false;
  41846. _this.LOGARITHMICDEPTH = false;
  41847. _this.REFRACTION = false;
  41848. _this.REFRACTIONMAP_3D = false;
  41849. _this.REFLECTIONOVERALPHA = false;
  41850. _this.TWOSIDEDLIGHTING = false;
  41851. _this.SHADOWFLOAT = false;
  41852. _this.MORPHTARGETS = false;
  41853. _this.MORPHTARGETS_NORMAL = false;
  41854. _this.MORPHTARGETS_TANGENT = false;
  41855. _this.NUM_MORPH_INFLUENCERS = 0;
  41856. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41857. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41858. _this.IMAGEPROCESSING = false;
  41859. _this.VIGNETTE = false;
  41860. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41861. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41862. _this.TONEMAPPING = false;
  41863. _this.TONEMAPPING_ACES = false;
  41864. _this.CONTRAST = false;
  41865. _this.COLORCURVES = false;
  41866. _this.COLORGRADING = false;
  41867. _this.COLORGRADING3D = false;
  41868. _this.SAMPLER3DGREENDEPTH = false;
  41869. _this.SAMPLER3DBGRMAP = false;
  41870. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41871. /**
  41872. * If the reflection texture on this material is in linear color space
  41873. * @hidden
  41874. */
  41875. _this.IS_REFLECTION_LINEAR = false;
  41876. /**
  41877. * If the refraction texture on this material is in linear color space
  41878. * @hidden
  41879. */
  41880. _this.IS_REFRACTION_LINEAR = false;
  41881. _this.EXPOSURE = false;
  41882. _this.rebuild();
  41883. return _this;
  41884. }
  41885. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41886. var modes = [
  41887. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41888. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41889. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41890. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41891. ];
  41892. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41893. var mode = modes_1[_i];
  41894. this[mode] = (mode === modeToEnable);
  41895. }
  41896. };
  41897. return StandardMaterialDefines;
  41898. }(BABYLON.MaterialDefines));
  41899. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41900. var StandardMaterial = /** @class */ (function (_super) {
  41901. __extends(StandardMaterial, _super);
  41902. function StandardMaterial(name, scene) {
  41903. var _this = _super.call(this, name, scene) || this;
  41904. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41905. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41906. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41907. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41908. _this.specularPower = 64;
  41909. _this._useAlphaFromDiffuseTexture = false;
  41910. _this._useEmissiveAsIllumination = false;
  41911. _this._linkEmissiveWithDiffuse = false;
  41912. _this._useSpecularOverAlpha = false;
  41913. _this._useReflectionOverAlpha = false;
  41914. _this._disableLighting = false;
  41915. _this._useObjectSpaceNormalMap = false;
  41916. _this._useParallax = false;
  41917. _this._useParallaxOcclusion = false;
  41918. _this.parallaxScaleBias = 0.05;
  41919. _this._roughness = 0;
  41920. _this.indexOfRefraction = 0.98;
  41921. _this.invertRefractionY = true;
  41922. /**
  41923. * Defines the alpha limits in alpha test mode
  41924. */
  41925. _this.alphaCutOff = 0.4;
  41926. _this._useLightmapAsShadowmap = false;
  41927. _this._useReflectionFresnelFromSpecular = false;
  41928. _this._useGlossinessFromSpecularMapAlpha = false;
  41929. _this._maxSimultaneousLights = 4;
  41930. /**
  41931. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41932. */
  41933. _this._invertNormalMapX = false;
  41934. /**
  41935. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41936. */
  41937. _this._invertNormalMapY = false;
  41938. /**
  41939. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41940. */
  41941. _this._twoSidedLighting = false;
  41942. _this._renderTargets = new BABYLON.SmartArray(16);
  41943. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41944. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41945. // Setup the default processing configuration to the scene.
  41946. _this._attachImageProcessingConfiguration(null);
  41947. _this.getRenderTargetTextures = function () {
  41948. _this._renderTargets.reset();
  41949. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41950. _this._renderTargets.push(_this._reflectionTexture);
  41951. }
  41952. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41953. _this._renderTargets.push(_this._refractionTexture);
  41954. }
  41955. return _this._renderTargets;
  41956. };
  41957. return _this;
  41958. }
  41959. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41960. /**
  41961. * Gets the image processing configuration used either in this material.
  41962. */
  41963. get: function () {
  41964. return this._imageProcessingConfiguration;
  41965. },
  41966. /**
  41967. * Sets the Default image processing configuration used either in the this material.
  41968. *
  41969. * If sets to null, the scene one is in use.
  41970. */
  41971. set: function (value) {
  41972. this._attachImageProcessingConfiguration(value);
  41973. // Ensure the effect will be rebuilt.
  41974. this._markAllSubMeshesAsTexturesDirty();
  41975. },
  41976. enumerable: true,
  41977. configurable: true
  41978. });
  41979. /**
  41980. * Attaches a new image processing configuration to the Standard Material.
  41981. * @param configuration
  41982. */
  41983. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41984. var _this = this;
  41985. if (configuration === this._imageProcessingConfiguration) {
  41986. return;
  41987. }
  41988. // Detaches observer.
  41989. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41990. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41991. }
  41992. // Pick the scene configuration if needed.
  41993. if (!configuration) {
  41994. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41995. }
  41996. else {
  41997. this._imageProcessingConfiguration = configuration;
  41998. }
  41999. // Attaches observer.
  42000. if (this._imageProcessingConfiguration) {
  42001. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42002. _this._markAllSubMeshesAsImageProcessingDirty();
  42003. });
  42004. }
  42005. };
  42006. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42007. /**
  42008. * Gets wether the color curves effect is enabled.
  42009. */
  42010. get: function () {
  42011. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42012. },
  42013. /**
  42014. * Sets wether the color curves effect is enabled.
  42015. */
  42016. set: function (value) {
  42017. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42018. },
  42019. enumerable: true,
  42020. configurable: true
  42021. });
  42022. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42023. /**
  42024. * Gets wether the color grading effect is enabled.
  42025. */
  42026. get: function () {
  42027. return this.imageProcessingConfiguration.colorGradingEnabled;
  42028. },
  42029. /**
  42030. * Gets wether the color grading effect is enabled.
  42031. */
  42032. set: function (value) {
  42033. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42034. },
  42035. enumerable: true,
  42036. configurable: true
  42037. });
  42038. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42039. /**
  42040. * Gets wether tonemapping is enabled or not.
  42041. */
  42042. get: function () {
  42043. return this._imageProcessingConfiguration.toneMappingEnabled;
  42044. },
  42045. /**
  42046. * Sets wether tonemapping is enabled or not
  42047. */
  42048. set: function (value) {
  42049. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42050. },
  42051. enumerable: true,
  42052. configurable: true
  42053. });
  42054. ;
  42055. ;
  42056. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42057. /**
  42058. * The camera exposure used on this material.
  42059. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42060. * This corresponds to a photographic exposure.
  42061. */
  42062. get: function () {
  42063. return this._imageProcessingConfiguration.exposure;
  42064. },
  42065. /**
  42066. * The camera exposure used on this material.
  42067. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42068. * This corresponds to a photographic exposure.
  42069. */
  42070. set: function (value) {
  42071. this._imageProcessingConfiguration.exposure = value;
  42072. },
  42073. enumerable: true,
  42074. configurable: true
  42075. });
  42076. ;
  42077. ;
  42078. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42079. /**
  42080. * Gets The camera contrast used on this material.
  42081. */
  42082. get: function () {
  42083. return this._imageProcessingConfiguration.contrast;
  42084. },
  42085. /**
  42086. * Sets The camera contrast used on this material.
  42087. */
  42088. set: function (value) {
  42089. this._imageProcessingConfiguration.contrast = value;
  42090. },
  42091. enumerable: true,
  42092. configurable: true
  42093. });
  42094. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42095. /**
  42096. * Gets the Color Grading 2D Lookup Texture.
  42097. */
  42098. get: function () {
  42099. return this._imageProcessingConfiguration.colorGradingTexture;
  42100. },
  42101. /**
  42102. * Sets the Color Grading 2D Lookup Texture.
  42103. */
  42104. set: function (value) {
  42105. this._imageProcessingConfiguration.colorGradingTexture = value;
  42106. },
  42107. enumerable: true,
  42108. configurable: true
  42109. });
  42110. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42111. /**
  42112. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42113. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42114. * 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;
  42115. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42116. */
  42117. get: function () {
  42118. return this._imageProcessingConfiguration.colorCurves;
  42119. },
  42120. /**
  42121. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42122. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42123. * 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;
  42124. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42125. */
  42126. set: function (value) {
  42127. this._imageProcessingConfiguration.colorCurves = value;
  42128. },
  42129. enumerable: true,
  42130. configurable: true
  42131. });
  42132. StandardMaterial.prototype.getClassName = function () {
  42133. return "StandardMaterial";
  42134. };
  42135. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42136. get: function () {
  42137. return this._useLogarithmicDepth;
  42138. },
  42139. set: function (value) {
  42140. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42141. this._markAllSubMeshesAsMiscDirty();
  42142. },
  42143. enumerable: true,
  42144. configurable: true
  42145. });
  42146. StandardMaterial.prototype.needAlphaBlending = function () {
  42147. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42148. };
  42149. StandardMaterial.prototype.needAlphaTesting = function () {
  42150. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42151. };
  42152. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42153. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42154. };
  42155. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42156. return this._diffuseTexture;
  42157. };
  42158. /**
  42159. * Child classes can use it to update shaders
  42160. */
  42161. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42162. if (useInstances === void 0) { useInstances = false; }
  42163. if (subMesh.effect && this.isFrozen) {
  42164. if (this._wasPreviouslyReady) {
  42165. return true;
  42166. }
  42167. }
  42168. if (!subMesh._materialDefines) {
  42169. subMesh._materialDefines = new StandardMaterialDefines();
  42170. }
  42171. var scene = this.getScene();
  42172. var defines = subMesh._materialDefines;
  42173. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42174. if (defines._renderId === scene.getRenderId()) {
  42175. return true;
  42176. }
  42177. }
  42178. var engine = scene.getEngine();
  42179. // Lights
  42180. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42181. // Textures
  42182. if (defines._areTexturesDirty) {
  42183. defines._needUVs = false;
  42184. defines.MAINUV1 = false;
  42185. defines.MAINUV2 = false;
  42186. if (scene.texturesEnabled) {
  42187. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42188. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42189. return false;
  42190. }
  42191. else {
  42192. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42193. }
  42194. }
  42195. else {
  42196. defines.DIFFUSE = false;
  42197. }
  42198. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42199. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42200. return false;
  42201. }
  42202. else {
  42203. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42204. }
  42205. }
  42206. else {
  42207. defines.AMBIENT = false;
  42208. }
  42209. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42210. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42211. return false;
  42212. }
  42213. else {
  42214. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42215. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42216. }
  42217. }
  42218. else {
  42219. defines.OPACITY = false;
  42220. }
  42221. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42222. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42223. return false;
  42224. }
  42225. else {
  42226. defines._needNormals = true;
  42227. defines.REFLECTION = true;
  42228. defines.ROUGHNESS = (this._roughness > 0);
  42229. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42230. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42231. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42232. switch (this._reflectionTexture.coordinatesMode) {
  42233. case BABYLON.Texture.EXPLICIT_MODE:
  42234. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42235. break;
  42236. case BABYLON.Texture.PLANAR_MODE:
  42237. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42238. break;
  42239. case BABYLON.Texture.PROJECTION_MODE:
  42240. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42241. break;
  42242. case BABYLON.Texture.SKYBOX_MODE:
  42243. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42244. break;
  42245. case BABYLON.Texture.SPHERICAL_MODE:
  42246. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42247. break;
  42248. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42249. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42250. break;
  42251. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42252. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42253. break;
  42254. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42255. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42256. break;
  42257. case BABYLON.Texture.CUBIC_MODE:
  42258. case BABYLON.Texture.INVCUBIC_MODE:
  42259. default:
  42260. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42261. break;
  42262. }
  42263. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42264. }
  42265. }
  42266. else {
  42267. defines.REFLECTION = false;
  42268. }
  42269. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42270. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42271. return false;
  42272. }
  42273. else {
  42274. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42275. }
  42276. }
  42277. else {
  42278. defines.EMISSIVE = false;
  42279. }
  42280. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42281. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42282. return false;
  42283. }
  42284. else {
  42285. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42286. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42287. }
  42288. }
  42289. else {
  42290. defines.LIGHTMAP = false;
  42291. }
  42292. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42293. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42294. return false;
  42295. }
  42296. else {
  42297. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42298. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42299. }
  42300. }
  42301. else {
  42302. defines.SPECULAR = false;
  42303. }
  42304. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42305. // Bump texure can not be not blocking.
  42306. if (!this._bumpTexture.isReady()) {
  42307. return false;
  42308. }
  42309. else {
  42310. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42311. defines.PARALLAX = this._useParallax;
  42312. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42313. }
  42314. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42315. }
  42316. else {
  42317. defines.BUMP = false;
  42318. }
  42319. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42320. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42321. return false;
  42322. }
  42323. else {
  42324. defines._needUVs = true;
  42325. defines.REFRACTION = true;
  42326. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42327. }
  42328. }
  42329. else {
  42330. defines.REFRACTION = false;
  42331. }
  42332. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42333. }
  42334. else {
  42335. defines.DIFFUSE = false;
  42336. defines.AMBIENT = false;
  42337. defines.OPACITY = false;
  42338. defines.REFLECTION = false;
  42339. defines.EMISSIVE = false;
  42340. defines.LIGHTMAP = false;
  42341. defines.BUMP = false;
  42342. defines.REFRACTION = false;
  42343. }
  42344. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42345. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42346. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42347. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42348. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42349. }
  42350. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  42351. if (!this._imageProcessingConfiguration.isReady()) {
  42352. return false;
  42353. }
  42354. this._imageProcessingConfiguration.prepareDefines(defines);
  42355. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42356. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42357. }
  42358. if (defines._areFresnelDirty) {
  42359. if (StandardMaterial.FresnelEnabled) {
  42360. // Fresnel
  42361. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42362. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42363. this._reflectionFresnelParameters) {
  42364. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42365. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42366. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42367. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42368. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42369. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42370. defines._needNormals = true;
  42371. defines.FRESNEL = true;
  42372. }
  42373. }
  42374. else {
  42375. defines.FRESNEL = false;
  42376. }
  42377. }
  42378. // Misc.
  42379. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42380. // Attribs
  42381. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42382. // Values that need to be evaluated on every frame
  42383. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42384. // Get correct effect
  42385. if (defines.isDirty) {
  42386. defines.markAsProcessed();
  42387. scene.resetCachedMaterial();
  42388. // Fallbacks
  42389. var fallbacks = new BABYLON.EffectFallbacks();
  42390. if (defines.REFLECTION) {
  42391. fallbacks.addFallback(0, "REFLECTION");
  42392. }
  42393. if (defines.SPECULAR) {
  42394. fallbacks.addFallback(0, "SPECULAR");
  42395. }
  42396. if (defines.BUMP) {
  42397. fallbacks.addFallback(0, "BUMP");
  42398. }
  42399. if (defines.PARALLAX) {
  42400. fallbacks.addFallback(1, "PARALLAX");
  42401. }
  42402. if (defines.PARALLAXOCCLUSION) {
  42403. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42404. }
  42405. if (defines.SPECULAROVERALPHA) {
  42406. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42407. }
  42408. if (defines.FOG) {
  42409. fallbacks.addFallback(1, "FOG");
  42410. }
  42411. if (defines.POINTSIZE) {
  42412. fallbacks.addFallback(0, "POINTSIZE");
  42413. }
  42414. if (defines.LOGARITHMICDEPTH) {
  42415. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42416. }
  42417. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42418. if (defines.SPECULARTERM) {
  42419. fallbacks.addFallback(0, "SPECULARTERM");
  42420. }
  42421. if (defines.DIFFUSEFRESNEL) {
  42422. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42423. }
  42424. if (defines.OPACITYFRESNEL) {
  42425. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42426. }
  42427. if (defines.REFLECTIONFRESNEL) {
  42428. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42429. }
  42430. if (defines.EMISSIVEFRESNEL) {
  42431. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42432. }
  42433. if (defines.FRESNEL) {
  42434. fallbacks.addFallback(4, "FRESNEL");
  42435. }
  42436. //Attributes
  42437. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42438. if (defines.NORMAL) {
  42439. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42440. }
  42441. if (defines.UV1) {
  42442. attribs.push(BABYLON.VertexBuffer.UVKind);
  42443. }
  42444. if (defines.UV2) {
  42445. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42446. }
  42447. if (defines.VERTEXCOLOR) {
  42448. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42449. }
  42450. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42451. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42452. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42453. var shaderName = "default";
  42454. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42455. "vFogInfos", "vFogColor", "pointSize",
  42456. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42457. "mBones",
  42458. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42459. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42460. "vReflectionPosition", "vReflectionSize",
  42461. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42462. ];
  42463. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42464. var uniformBuffers = ["Material", "Scene"];
  42465. if (BABYLON.ImageProcessingConfiguration) {
  42466. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42467. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42468. }
  42469. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42470. uniformsNames: uniforms,
  42471. uniformBuffersNames: uniformBuffers,
  42472. samplers: samplers,
  42473. defines: defines,
  42474. maxSimultaneousLights: this._maxSimultaneousLights
  42475. });
  42476. if (this.customShaderNameResolve) {
  42477. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42478. }
  42479. var join = defines.toString();
  42480. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42481. attributes: attribs,
  42482. uniformsNames: uniforms,
  42483. uniformBuffersNames: uniformBuffers,
  42484. samplers: samplers,
  42485. defines: join,
  42486. fallbacks: fallbacks,
  42487. onCompiled: this.onCompiled,
  42488. onError: this.onError,
  42489. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42490. }, engine), defines);
  42491. this.buildUniformLayout();
  42492. }
  42493. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42494. return false;
  42495. }
  42496. defines._renderId = scene.getRenderId();
  42497. this._wasPreviouslyReady = true;
  42498. return true;
  42499. };
  42500. StandardMaterial.prototype.buildUniformLayout = function () {
  42501. // Order is important !
  42502. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42503. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42504. this._uniformBuffer.addUniform("opacityParts", 4);
  42505. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42506. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42507. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42508. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42509. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42510. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42511. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42512. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42513. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42514. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42515. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42516. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42517. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42518. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42519. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42520. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42521. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42522. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42523. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42524. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42525. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42526. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42527. this._uniformBuffer.addUniform("specularMatrix", 16);
  42528. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42529. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42530. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42531. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42532. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42533. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42534. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42535. this._uniformBuffer.addUniform("pointSize", 1);
  42536. this._uniformBuffer.create();
  42537. };
  42538. StandardMaterial.prototype.unbind = function () {
  42539. if (this._activeEffect) {
  42540. var needFlag = false;
  42541. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42542. this._activeEffect.setTexture("reflection2DSampler", null);
  42543. needFlag = true;
  42544. }
  42545. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42546. this._activeEffect.setTexture("refraction2DSampler", null);
  42547. needFlag = true;
  42548. }
  42549. if (needFlag) {
  42550. this._markAllSubMeshesAsTexturesDirty();
  42551. }
  42552. }
  42553. _super.prototype.unbind.call(this);
  42554. };
  42555. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42556. var scene = this.getScene();
  42557. var defines = subMesh._materialDefines;
  42558. if (!defines) {
  42559. return;
  42560. }
  42561. var effect = subMesh.effect;
  42562. if (!effect) {
  42563. return;
  42564. }
  42565. this._activeEffect = effect;
  42566. // Matrices
  42567. this.bindOnlyWorldMatrix(world);
  42568. // Normal Matrix
  42569. if (defines.OBJECTSPACE_NORMALMAP) {
  42570. world.toNormalMatrix(this._normalMatrix);
  42571. this.bindOnlyNormalMatrix(this._normalMatrix);
  42572. }
  42573. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42574. // Bones
  42575. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42576. if (mustRebind) {
  42577. this._uniformBuffer.bindToEffect(effect, "Material");
  42578. this.bindViewProjection(effect);
  42579. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42580. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42581. // Fresnel
  42582. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42583. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42584. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42585. }
  42586. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42587. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42588. }
  42589. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42590. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42591. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42592. }
  42593. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42594. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42595. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42596. }
  42597. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42598. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42599. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42600. }
  42601. }
  42602. // Textures
  42603. if (scene.texturesEnabled) {
  42604. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42605. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42606. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42607. if (this._diffuseTexture.hasAlpha) {
  42608. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42609. }
  42610. }
  42611. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42612. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42613. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42614. }
  42615. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42616. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42617. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42618. }
  42619. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42620. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42621. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42622. if (this._reflectionTexture.boundingBoxSize) {
  42623. var cubeTexture = this._reflectionTexture;
  42624. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42625. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42626. }
  42627. }
  42628. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42629. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42630. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42631. }
  42632. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42633. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42634. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42635. }
  42636. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42637. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42638. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42639. }
  42640. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42641. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42642. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42643. if (scene._mirroredCameraPosition) {
  42644. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42645. }
  42646. else {
  42647. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42648. }
  42649. }
  42650. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42651. var depth = 1.0;
  42652. if (!this._refractionTexture.isCube) {
  42653. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42654. if (this._refractionTexture.depth) {
  42655. depth = this._refractionTexture.depth;
  42656. }
  42657. }
  42658. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42659. }
  42660. }
  42661. // Point size
  42662. if (this.pointsCloud) {
  42663. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42664. }
  42665. if (defines.SPECULARTERM) {
  42666. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42667. }
  42668. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42669. // Diffuse
  42670. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42671. }
  42672. // Textures
  42673. if (scene.texturesEnabled) {
  42674. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42675. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42676. }
  42677. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42678. effect.setTexture("ambientSampler", this._ambientTexture);
  42679. }
  42680. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42681. effect.setTexture("opacitySampler", this._opacityTexture);
  42682. }
  42683. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42684. if (this._reflectionTexture.isCube) {
  42685. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42686. }
  42687. else {
  42688. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42689. }
  42690. }
  42691. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42692. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42693. }
  42694. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42695. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42696. }
  42697. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42698. effect.setTexture("specularSampler", this._specularTexture);
  42699. }
  42700. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42701. effect.setTexture("bumpSampler", this._bumpTexture);
  42702. }
  42703. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42704. var depth = 1.0;
  42705. if (this._refractionTexture.isCube) {
  42706. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42707. }
  42708. else {
  42709. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42710. }
  42711. }
  42712. }
  42713. // Clip plane
  42714. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42715. // Colors
  42716. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42717. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42718. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42719. }
  42720. if (mustRebind || !this.isFrozen) {
  42721. // Lights
  42722. if (scene.lightsEnabled && !this._disableLighting) {
  42723. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42724. }
  42725. // View
  42726. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42727. this.bindView(effect);
  42728. }
  42729. // Fog
  42730. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42731. // Morph targets
  42732. if (defines.NUM_MORPH_INFLUENCERS) {
  42733. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42734. }
  42735. // Log. depth
  42736. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42737. // image processing
  42738. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42739. this._imageProcessingConfiguration.bind(this._activeEffect);
  42740. }
  42741. }
  42742. this._uniformBuffer.update();
  42743. this._afterBind(mesh, this._activeEffect);
  42744. };
  42745. StandardMaterial.prototype.getAnimatables = function () {
  42746. var results = [];
  42747. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42748. results.push(this._diffuseTexture);
  42749. }
  42750. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42751. results.push(this._ambientTexture);
  42752. }
  42753. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42754. results.push(this._opacityTexture);
  42755. }
  42756. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42757. results.push(this._reflectionTexture);
  42758. }
  42759. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42760. results.push(this._emissiveTexture);
  42761. }
  42762. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42763. results.push(this._specularTexture);
  42764. }
  42765. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42766. results.push(this._bumpTexture);
  42767. }
  42768. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42769. results.push(this._lightmapTexture);
  42770. }
  42771. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42772. results.push(this._refractionTexture);
  42773. }
  42774. return results;
  42775. };
  42776. StandardMaterial.prototype.getActiveTextures = function () {
  42777. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42778. if (this._diffuseTexture) {
  42779. activeTextures.push(this._diffuseTexture);
  42780. }
  42781. if (this._ambientTexture) {
  42782. activeTextures.push(this._ambientTexture);
  42783. }
  42784. if (this._opacityTexture) {
  42785. activeTextures.push(this._opacityTexture);
  42786. }
  42787. if (this._reflectionTexture) {
  42788. activeTextures.push(this._reflectionTexture);
  42789. }
  42790. if (this._emissiveTexture) {
  42791. activeTextures.push(this._emissiveTexture);
  42792. }
  42793. if (this._specularTexture) {
  42794. activeTextures.push(this._specularTexture);
  42795. }
  42796. if (this._bumpTexture) {
  42797. activeTextures.push(this._bumpTexture);
  42798. }
  42799. if (this._lightmapTexture) {
  42800. activeTextures.push(this._lightmapTexture);
  42801. }
  42802. if (this._refractionTexture) {
  42803. activeTextures.push(this._refractionTexture);
  42804. }
  42805. return activeTextures;
  42806. };
  42807. StandardMaterial.prototype.hasTexture = function (texture) {
  42808. if (_super.prototype.hasTexture.call(this, texture)) {
  42809. return true;
  42810. }
  42811. if (this._diffuseTexture === texture) {
  42812. return true;
  42813. }
  42814. if (this._ambientTexture === texture) {
  42815. return true;
  42816. }
  42817. if (this._opacityTexture === texture) {
  42818. return true;
  42819. }
  42820. if (this._reflectionTexture === texture) {
  42821. return true;
  42822. }
  42823. if (this._emissiveTexture === texture) {
  42824. return true;
  42825. }
  42826. if (this._specularTexture === texture) {
  42827. return true;
  42828. }
  42829. if (this._bumpTexture === texture) {
  42830. return true;
  42831. }
  42832. if (this._lightmapTexture === texture) {
  42833. return true;
  42834. }
  42835. if (this._refractionTexture === texture) {
  42836. return true;
  42837. }
  42838. return false;
  42839. };
  42840. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42841. if (forceDisposeTextures) {
  42842. if (this._diffuseTexture) {
  42843. this._diffuseTexture.dispose();
  42844. }
  42845. if (this._ambientTexture) {
  42846. this._ambientTexture.dispose();
  42847. }
  42848. if (this._opacityTexture) {
  42849. this._opacityTexture.dispose();
  42850. }
  42851. if (this._reflectionTexture) {
  42852. this._reflectionTexture.dispose();
  42853. }
  42854. if (this._emissiveTexture) {
  42855. this._emissiveTexture.dispose();
  42856. }
  42857. if (this._specularTexture) {
  42858. this._specularTexture.dispose();
  42859. }
  42860. if (this._bumpTexture) {
  42861. this._bumpTexture.dispose();
  42862. }
  42863. if (this._lightmapTexture) {
  42864. this._lightmapTexture.dispose();
  42865. }
  42866. if (this._refractionTexture) {
  42867. this._refractionTexture.dispose();
  42868. }
  42869. }
  42870. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42871. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42872. }
  42873. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42874. };
  42875. StandardMaterial.prototype.clone = function (name) {
  42876. var _this = this;
  42877. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42878. result.name = name;
  42879. result.id = name;
  42880. return result;
  42881. };
  42882. StandardMaterial.prototype.serialize = function () {
  42883. return BABYLON.SerializationHelper.Serialize(this);
  42884. };
  42885. // Statics
  42886. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42887. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42888. };
  42889. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42890. get: function () {
  42891. return StandardMaterial._DiffuseTextureEnabled;
  42892. },
  42893. set: function (value) {
  42894. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42895. return;
  42896. }
  42897. StandardMaterial._DiffuseTextureEnabled = value;
  42898. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42899. },
  42900. enumerable: true,
  42901. configurable: true
  42902. });
  42903. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42904. get: function () {
  42905. return StandardMaterial._AmbientTextureEnabled;
  42906. },
  42907. set: function (value) {
  42908. if (StandardMaterial._AmbientTextureEnabled === value) {
  42909. return;
  42910. }
  42911. StandardMaterial._AmbientTextureEnabled = value;
  42912. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42913. },
  42914. enumerable: true,
  42915. configurable: true
  42916. });
  42917. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42918. get: function () {
  42919. return StandardMaterial._OpacityTextureEnabled;
  42920. },
  42921. set: function (value) {
  42922. if (StandardMaterial._OpacityTextureEnabled === value) {
  42923. return;
  42924. }
  42925. StandardMaterial._OpacityTextureEnabled = value;
  42926. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42927. },
  42928. enumerable: true,
  42929. configurable: true
  42930. });
  42931. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42932. get: function () {
  42933. return StandardMaterial._ReflectionTextureEnabled;
  42934. },
  42935. set: function (value) {
  42936. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42937. return;
  42938. }
  42939. StandardMaterial._ReflectionTextureEnabled = value;
  42940. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42941. },
  42942. enumerable: true,
  42943. configurable: true
  42944. });
  42945. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42946. get: function () {
  42947. return StandardMaterial._EmissiveTextureEnabled;
  42948. },
  42949. set: function (value) {
  42950. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42951. return;
  42952. }
  42953. StandardMaterial._EmissiveTextureEnabled = value;
  42954. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42955. },
  42956. enumerable: true,
  42957. configurable: true
  42958. });
  42959. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42960. get: function () {
  42961. return StandardMaterial._SpecularTextureEnabled;
  42962. },
  42963. set: function (value) {
  42964. if (StandardMaterial._SpecularTextureEnabled === value) {
  42965. return;
  42966. }
  42967. StandardMaterial._SpecularTextureEnabled = value;
  42968. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42969. },
  42970. enumerable: true,
  42971. configurable: true
  42972. });
  42973. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42974. get: function () {
  42975. return StandardMaterial._BumpTextureEnabled;
  42976. },
  42977. set: function (value) {
  42978. if (StandardMaterial._BumpTextureEnabled === value) {
  42979. return;
  42980. }
  42981. StandardMaterial._BumpTextureEnabled = value;
  42982. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42983. },
  42984. enumerable: true,
  42985. configurable: true
  42986. });
  42987. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42988. get: function () {
  42989. return StandardMaterial._LightmapTextureEnabled;
  42990. },
  42991. set: function (value) {
  42992. if (StandardMaterial._LightmapTextureEnabled === value) {
  42993. return;
  42994. }
  42995. StandardMaterial._LightmapTextureEnabled = value;
  42996. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42997. },
  42998. enumerable: true,
  42999. configurable: true
  43000. });
  43001. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43002. get: function () {
  43003. return StandardMaterial._RefractionTextureEnabled;
  43004. },
  43005. set: function (value) {
  43006. if (StandardMaterial._RefractionTextureEnabled === value) {
  43007. return;
  43008. }
  43009. StandardMaterial._RefractionTextureEnabled = value;
  43010. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43011. },
  43012. enumerable: true,
  43013. configurable: true
  43014. });
  43015. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43016. get: function () {
  43017. return StandardMaterial._ColorGradingTextureEnabled;
  43018. },
  43019. set: function (value) {
  43020. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43021. return;
  43022. }
  43023. StandardMaterial._ColorGradingTextureEnabled = value;
  43024. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43025. },
  43026. enumerable: true,
  43027. configurable: true
  43028. });
  43029. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43030. get: function () {
  43031. return StandardMaterial._FresnelEnabled;
  43032. },
  43033. set: function (value) {
  43034. if (StandardMaterial._FresnelEnabled === value) {
  43035. return;
  43036. }
  43037. StandardMaterial._FresnelEnabled = value;
  43038. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43039. },
  43040. enumerable: true,
  43041. configurable: true
  43042. });
  43043. // Flags used to enable or disable a type of texture for all Standard Materials
  43044. StandardMaterial._DiffuseTextureEnabled = true;
  43045. StandardMaterial._AmbientTextureEnabled = true;
  43046. StandardMaterial._OpacityTextureEnabled = true;
  43047. StandardMaterial._ReflectionTextureEnabled = true;
  43048. StandardMaterial._EmissiveTextureEnabled = true;
  43049. StandardMaterial._SpecularTextureEnabled = true;
  43050. StandardMaterial._BumpTextureEnabled = true;
  43051. StandardMaterial._LightmapTextureEnabled = true;
  43052. StandardMaterial._RefractionTextureEnabled = true;
  43053. StandardMaterial._ColorGradingTextureEnabled = true;
  43054. StandardMaterial._FresnelEnabled = true;
  43055. __decorate([
  43056. BABYLON.serializeAsTexture("diffuseTexture")
  43057. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43058. __decorate([
  43059. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43060. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43061. __decorate([
  43062. BABYLON.serializeAsTexture("ambientTexture")
  43063. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43064. __decorate([
  43065. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43066. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43067. __decorate([
  43068. BABYLON.serializeAsTexture("opacityTexture")
  43069. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43070. __decorate([
  43071. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43072. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43073. __decorate([
  43074. BABYLON.serializeAsTexture("reflectionTexture")
  43075. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43076. __decorate([
  43077. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43078. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43079. __decorate([
  43080. BABYLON.serializeAsTexture("emissiveTexture")
  43081. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43082. __decorate([
  43083. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43084. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43085. __decorate([
  43086. BABYLON.serializeAsTexture("specularTexture")
  43087. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43088. __decorate([
  43089. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43090. ], StandardMaterial.prototype, "specularTexture", void 0);
  43091. __decorate([
  43092. BABYLON.serializeAsTexture("bumpTexture")
  43093. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43094. __decorate([
  43095. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43096. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43097. __decorate([
  43098. BABYLON.serializeAsTexture("lightmapTexture")
  43099. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43100. __decorate([
  43101. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43102. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43103. __decorate([
  43104. BABYLON.serializeAsTexture("refractionTexture")
  43105. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43106. __decorate([
  43107. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43108. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43109. __decorate([
  43110. BABYLON.serializeAsColor3("ambient")
  43111. ], StandardMaterial.prototype, "ambientColor", void 0);
  43112. __decorate([
  43113. BABYLON.serializeAsColor3("diffuse")
  43114. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43115. __decorate([
  43116. BABYLON.serializeAsColor3("specular")
  43117. ], StandardMaterial.prototype, "specularColor", void 0);
  43118. __decorate([
  43119. BABYLON.serializeAsColor3("emissive")
  43120. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43121. __decorate([
  43122. BABYLON.serialize()
  43123. ], StandardMaterial.prototype, "specularPower", void 0);
  43124. __decorate([
  43125. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43126. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43127. __decorate([
  43128. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43129. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43130. __decorate([
  43131. BABYLON.serialize("useEmissiveAsIllumination")
  43132. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43133. __decorate([
  43134. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43135. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43136. __decorate([
  43137. BABYLON.serialize("linkEmissiveWithDiffuse")
  43138. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43139. __decorate([
  43140. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43141. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43142. __decorate([
  43143. BABYLON.serialize("useSpecularOverAlpha")
  43144. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43145. __decorate([
  43146. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43147. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43148. __decorate([
  43149. BABYLON.serialize("useReflectionOverAlpha")
  43150. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43151. __decorate([
  43152. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43153. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43154. __decorate([
  43155. BABYLON.serialize("disableLighting")
  43156. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43157. __decorate([
  43158. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43159. ], StandardMaterial.prototype, "disableLighting", void 0);
  43160. __decorate([
  43161. BABYLON.serialize("useObjectSpaceNormalMap")
  43162. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43163. __decorate([
  43164. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43165. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43166. __decorate([
  43167. BABYLON.serialize("useParallax")
  43168. ], StandardMaterial.prototype, "_useParallax", void 0);
  43169. __decorate([
  43170. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43171. ], StandardMaterial.prototype, "useParallax", void 0);
  43172. __decorate([
  43173. BABYLON.serialize("useParallaxOcclusion")
  43174. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43175. __decorate([
  43176. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43177. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43178. __decorate([
  43179. BABYLON.serialize()
  43180. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43181. __decorate([
  43182. BABYLON.serialize("roughness")
  43183. ], StandardMaterial.prototype, "_roughness", void 0);
  43184. __decorate([
  43185. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43186. ], StandardMaterial.prototype, "roughness", void 0);
  43187. __decorate([
  43188. BABYLON.serialize()
  43189. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43190. __decorate([
  43191. BABYLON.serialize()
  43192. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43193. __decorate([
  43194. BABYLON.serialize()
  43195. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43196. __decorate([
  43197. BABYLON.serialize("useLightmapAsShadowmap")
  43198. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43199. __decorate([
  43200. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43201. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43202. __decorate([
  43203. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43204. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43205. __decorate([
  43206. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43207. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43208. __decorate([
  43209. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43210. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43211. __decorate([
  43212. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43213. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43214. __decorate([
  43215. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43216. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43217. __decorate([
  43218. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43219. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43220. __decorate([
  43221. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43222. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43223. __decorate([
  43224. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43225. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43226. __decorate([
  43227. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43228. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43229. __decorate([
  43230. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43231. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43232. __decorate([
  43233. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43234. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43235. __decorate([
  43236. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43237. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43238. __decorate([
  43239. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43240. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43241. __decorate([
  43242. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43243. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43244. __decorate([
  43245. BABYLON.serialize("maxSimultaneousLights")
  43246. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43247. __decorate([
  43248. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43249. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43250. __decorate([
  43251. BABYLON.serialize("invertNormalMapX")
  43252. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43253. __decorate([
  43254. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43255. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43256. __decorate([
  43257. BABYLON.serialize("invertNormalMapY")
  43258. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43259. __decorate([
  43260. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43261. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43262. __decorate([
  43263. BABYLON.serialize("twoSidedLighting")
  43264. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43265. __decorate([
  43266. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43267. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43268. __decorate([
  43269. BABYLON.serialize()
  43270. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43271. return StandardMaterial;
  43272. }(BABYLON.PushMaterial));
  43273. BABYLON.StandardMaterial = StandardMaterial;
  43274. })(BABYLON || (BABYLON = {}));
  43275. //# sourceMappingURL=babylon.standardMaterial.js.map
  43276. var BABYLON;
  43277. (function (BABYLON) {
  43278. /**
  43279. * Class representing spherical polynomial coefficients to the 3rd degree
  43280. */
  43281. var SphericalPolynomial = /** @class */ (function () {
  43282. function SphericalPolynomial() {
  43283. /**
  43284. * The x coefficients of the spherical polynomial
  43285. */
  43286. this.x = BABYLON.Vector3.Zero();
  43287. /**
  43288. * The y coefficients of the spherical polynomial
  43289. */
  43290. this.y = BABYLON.Vector3.Zero();
  43291. /**
  43292. * The z coefficients of the spherical polynomial
  43293. */
  43294. this.z = BABYLON.Vector3.Zero();
  43295. /**
  43296. * The xx coefficients of the spherical polynomial
  43297. */
  43298. this.xx = BABYLON.Vector3.Zero();
  43299. /**
  43300. * The yy coefficients of the spherical polynomial
  43301. */
  43302. this.yy = BABYLON.Vector3.Zero();
  43303. /**
  43304. * The zz coefficients of the spherical polynomial
  43305. */
  43306. this.zz = BABYLON.Vector3.Zero();
  43307. /**
  43308. * The xy coefficients of the spherical polynomial
  43309. */
  43310. this.xy = BABYLON.Vector3.Zero();
  43311. /**
  43312. * The yz coefficients of the spherical polynomial
  43313. */
  43314. this.yz = BABYLON.Vector3.Zero();
  43315. /**
  43316. * The zx coefficients of the spherical polynomial
  43317. */
  43318. this.zx = BABYLON.Vector3.Zero();
  43319. }
  43320. /**
  43321. * Adds an ambient color to the spherical polynomial
  43322. * @param color the color to add
  43323. */
  43324. SphericalPolynomial.prototype.addAmbient = function (color) {
  43325. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43326. this.xx = this.xx.add(colorVector);
  43327. this.yy = this.yy.add(colorVector);
  43328. this.zz = this.zz.add(colorVector);
  43329. };
  43330. /**
  43331. * Scales the spherical polynomial by the given amount
  43332. * @param scale the amount to scale
  43333. */
  43334. SphericalPolynomial.prototype.scale = function (scale) {
  43335. this.x = this.x.scale(scale);
  43336. this.y = this.y.scale(scale);
  43337. this.z = this.z.scale(scale);
  43338. this.xx = this.xx.scale(scale);
  43339. this.yy = this.yy.scale(scale);
  43340. this.zz = this.zz.scale(scale);
  43341. this.yz = this.yz.scale(scale);
  43342. this.zx = this.zx.scale(scale);
  43343. this.xy = this.xy.scale(scale);
  43344. };
  43345. /**
  43346. * Gets the spherical polynomial from harmonics
  43347. * @param harmonics the spherical harmonics
  43348. * @returns the spherical polynomial
  43349. */
  43350. SphericalPolynomial.FromHarmonics = function (harmonics) {
  43351. var result = new SphericalPolynomial();
  43352. result.x = harmonics.l11.scale(1.02333);
  43353. result.y = harmonics.l1_1.scale(1.02333);
  43354. result.z = harmonics.l10.scale(1.02333);
  43355. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  43356. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  43357. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  43358. result.yz = harmonics.l2_1.scale(0.858086);
  43359. result.zx = harmonics.l21.scale(0.858086);
  43360. result.xy = harmonics.l2_2.scale(0.858086);
  43361. result.scale(1.0 / Math.PI);
  43362. return result;
  43363. };
  43364. /**
  43365. * Constructs a spherical polynomial from an array.
  43366. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  43367. * @returns the spherical polynomial
  43368. */
  43369. SphericalPolynomial.FromArray = function (data) {
  43370. var sp = new SphericalPolynomial();
  43371. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  43372. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  43373. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  43374. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  43375. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  43376. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  43377. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  43378. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  43379. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  43380. return sp;
  43381. };
  43382. return SphericalPolynomial;
  43383. }());
  43384. BABYLON.SphericalPolynomial = SphericalPolynomial;
  43385. /**
  43386. * Class representing spherical harmonics coefficients to the 3rd degree
  43387. */
  43388. var SphericalHarmonics = /** @class */ (function () {
  43389. function SphericalHarmonics() {
  43390. /**
  43391. * The l0,0 coefficients of the spherical harmonics
  43392. */
  43393. this.l00 = BABYLON.Vector3.Zero();
  43394. /**
  43395. * The l1,-1 coefficients of the spherical harmonics
  43396. */
  43397. this.l1_1 = BABYLON.Vector3.Zero();
  43398. /**
  43399. * The l1,0 coefficients of the spherical harmonics
  43400. */
  43401. this.l10 = BABYLON.Vector3.Zero();
  43402. /**
  43403. * The l1,1 coefficients of the spherical harmonics
  43404. */
  43405. this.l11 = BABYLON.Vector3.Zero();
  43406. /**
  43407. * The l2,-2 coefficients of the spherical harmonics
  43408. */
  43409. this.l2_2 = BABYLON.Vector3.Zero();
  43410. /**
  43411. * The l2,-1 coefficients of the spherical harmonics
  43412. */
  43413. this.l2_1 = BABYLON.Vector3.Zero();
  43414. /**
  43415. * The l2,0 coefficients of the spherical harmonics
  43416. */
  43417. this.l20 = BABYLON.Vector3.Zero();
  43418. /**
  43419. * The l2,1 coefficients of the spherical harmonics
  43420. */
  43421. this.l21 = BABYLON.Vector3.Zero();
  43422. /**
  43423. * The l2,2 coefficients of the spherical harmonics
  43424. */
  43425. this.lL22 = BABYLON.Vector3.Zero();
  43426. }
  43427. /**
  43428. * Adds a light to the spherical harmonics
  43429. * @param direction the direction of the light
  43430. * @param color the color of the light
  43431. * @param deltaSolidAngle the delta solid angle of the light
  43432. */
  43433. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  43434. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  43435. var c = colorVector.scale(deltaSolidAngle);
  43436. this.l00 = this.l00.add(c.scale(0.282095));
  43437. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  43438. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  43439. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  43440. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  43441. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  43442. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  43443. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  43444. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  43445. };
  43446. /**
  43447. * Scales the spherical harmonics by the given amount
  43448. * @param scale the amount to scale
  43449. */
  43450. SphericalHarmonics.prototype.scale = function (scale) {
  43451. this.l00 = this.l00.scale(scale);
  43452. this.l1_1 = this.l1_1.scale(scale);
  43453. this.l10 = this.l10.scale(scale);
  43454. this.l11 = this.l11.scale(scale);
  43455. this.l2_2 = this.l2_2.scale(scale);
  43456. this.l2_1 = this.l2_1.scale(scale);
  43457. this.l20 = this.l20.scale(scale);
  43458. this.l21 = this.l21.scale(scale);
  43459. this.lL22 = this.lL22.scale(scale);
  43460. };
  43461. /**
  43462. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  43463. *
  43464. * ```
  43465. * E_lm = A_l * L_lm
  43466. * ```
  43467. *
  43468. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  43469. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  43470. * the scaling factors are given in equation 9.
  43471. */
  43472. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  43473. // Constant (Band 0)
  43474. this.l00 = this.l00.scale(3.141593);
  43475. // Linear (Band 1)
  43476. this.l1_1 = this.l1_1.scale(2.094395);
  43477. this.l10 = this.l10.scale(2.094395);
  43478. this.l11 = this.l11.scale(2.094395);
  43479. // Quadratic (Band 2)
  43480. this.l2_2 = this.l2_2.scale(0.785398);
  43481. this.l2_1 = this.l2_1.scale(0.785398);
  43482. this.l20 = this.l20.scale(0.785398);
  43483. this.l21 = this.l21.scale(0.785398);
  43484. this.lL22 = this.lL22.scale(0.785398);
  43485. };
  43486. /**
  43487. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  43488. *
  43489. * ```
  43490. * L = (1/pi) * E * rho
  43491. * ```
  43492. *
  43493. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  43494. */
  43495. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  43496. this.scale(1.0 / Math.PI);
  43497. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  43498. // (The pixel shader must apply albedo after texture fetches, etc).
  43499. };
  43500. /**
  43501. * Gets the spherical harmonics from polynomial
  43502. * @param polynomial the spherical polynomial
  43503. * @returns the spherical harmonics
  43504. */
  43505. SphericalHarmonics.FromPolynomial = function (polynomial) {
  43506. var result = new SphericalHarmonics();
  43507. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  43508. result.l1_1 = polynomial.y.scale(0.977204);
  43509. result.l10 = polynomial.z.scale(0.977204);
  43510. result.l11 = polynomial.x.scale(0.977204);
  43511. result.l2_2 = polynomial.xy.scale(1.16538);
  43512. result.l2_1 = polynomial.yz.scale(1.16538);
  43513. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  43514. result.l21 = polynomial.zx.scale(1.16538);
  43515. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  43516. result.scale(Math.PI);
  43517. return result;
  43518. };
  43519. /**
  43520. * Constructs a spherical harmonics from an array.
  43521. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  43522. * @returns the spherical harmonics
  43523. */
  43524. SphericalHarmonics.FromArray = function (data) {
  43525. var sh = new SphericalHarmonics();
  43526. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  43527. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  43528. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  43529. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  43530. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  43531. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  43532. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  43533. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  43534. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  43535. return sh;
  43536. };
  43537. return SphericalHarmonics;
  43538. }());
  43539. BABYLON.SphericalHarmonics = SphericalHarmonics;
  43540. })(BABYLON || (BABYLON = {}));
  43541. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  43542. var BABYLON;
  43543. (function (BABYLON) {
  43544. var FileFaceOrientation = /** @class */ (function () {
  43545. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  43546. this.name = name;
  43547. this.worldAxisForNormal = worldAxisForNormal;
  43548. this.worldAxisForFileX = worldAxisForFileX;
  43549. this.worldAxisForFileY = worldAxisForFileY;
  43550. }
  43551. return FileFaceOrientation;
  43552. }());
  43553. ;
  43554. /**
  43555. * Helper class dealing with the extraction of spherical polynomial dataArray
  43556. * from a cube map.
  43557. */
  43558. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  43559. function CubeMapToSphericalPolynomialTools() {
  43560. }
  43561. /**
  43562. * Converts a texture to the according Spherical Polynomial data.
  43563. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43564. *
  43565. * @param texture The texture to extract the information from.
  43566. * @return The Spherical Polynomial data.
  43567. */
  43568. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  43569. if (!texture.isCube) {
  43570. // Only supports cube Textures currently.
  43571. return null;
  43572. }
  43573. var size = texture.getSize().width;
  43574. var right = texture.readPixels(0);
  43575. var left = texture.readPixels(1);
  43576. var up;
  43577. var down;
  43578. if (texture.isRenderTarget) {
  43579. up = texture.readPixels(3);
  43580. down = texture.readPixels(2);
  43581. }
  43582. else {
  43583. up = texture.readPixels(2);
  43584. down = texture.readPixels(3);
  43585. }
  43586. var front = texture.readPixels(4);
  43587. var back = texture.readPixels(5);
  43588. var gammaSpace = texture.gammaSpace;
  43589. // Always read as RGBA.
  43590. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  43591. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  43592. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43593. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  43594. }
  43595. var cubeInfo = {
  43596. size: size,
  43597. right: right,
  43598. left: left,
  43599. up: up,
  43600. down: down,
  43601. front: front,
  43602. back: back,
  43603. format: format,
  43604. type: type,
  43605. gammaSpace: gammaSpace,
  43606. };
  43607. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  43608. };
  43609. /**
  43610. * Converts a cubemap to the according Spherical Polynomial data.
  43611. * This extracts the first 3 orders only as they are the only one used in the lighting.
  43612. *
  43613. * @param cubeInfo The Cube map to extract the information from.
  43614. * @return The Spherical Polynomial data.
  43615. */
  43616. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  43617. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  43618. var totalSolidAngle = 0.0;
  43619. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  43620. var du = 2.0 / cubeInfo.size;
  43621. var dv = du;
  43622. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  43623. var minUV = du * 0.5 - 1.0;
  43624. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  43625. var fileFace = this.FileFaces[faceIndex];
  43626. var dataArray = cubeInfo[fileFace.name];
  43627. var v = minUV;
  43628. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  43629. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  43630. // Because SP is still linear, so summation is fine in that basis.
  43631. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  43632. for (var y = 0; y < cubeInfo.size; y++) {
  43633. var u = minUV;
  43634. for (var x = 0; x < cubeInfo.size; x++) {
  43635. // World direction (not normalised)
  43636. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  43637. worldDirection.normalize();
  43638. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  43639. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  43640. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  43641. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  43642. // Handle Integer types.
  43643. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  43644. r /= 255;
  43645. g /= 255;
  43646. b /= 255;
  43647. }
  43648. // Handle Gamma space textures.
  43649. if (cubeInfo.gammaSpace) {
  43650. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  43651. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  43652. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  43653. }
  43654. var color = new BABYLON.Color3(r, g, b);
  43655. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  43656. totalSolidAngle += deltaSolidAngle;
  43657. u += du;
  43658. }
  43659. v += dv;
  43660. }
  43661. }
  43662. // Solid angle for entire sphere is 4*pi
  43663. var sphereSolidAngle = 4.0 * Math.PI;
  43664. // Adjust the solid angle to allow for how many faces we processed.
  43665. var facesProcessed = 6.0;
  43666. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  43667. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  43668. // This is needed because the numerical integration over the cube uses a
  43669. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  43670. // and also to compensate for accumulative error due to float precision in the summation.
  43671. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  43672. sphericalHarmonics.scale(correctionFactor);
  43673. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  43674. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  43675. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  43676. };
  43677. CubeMapToSphericalPolynomialTools.FileFaces = [
  43678. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  43679. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  43680. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  43681. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  43682. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  43683. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  43684. ];
  43685. return CubeMapToSphericalPolynomialTools;
  43686. }());
  43687. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  43688. })(BABYLON || (BABYLON = {}));
  43689. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  43690. var BABYLON;
  43691. (function (BABYLON) {
  43692. /**
  43693. * Manages the defines for the PBR Material.
  43694. * @hiddenChildren
  43695. */
  43696. var PBRMaterialDefines = /** @class */ (function (_super) {
  43697. __extends(PBRMaterialDefines, _super);
  43698. /**
  43699. * Initializes the PBR Material defines.
  43700. */
  43701. function PBRMaterialDefines() {
  43702. var _this = _super.call(this) || this;
  43703. _this.PBR = true;
  43704. _this.MAINUV1 = false;
  43705. _this.MAINUV2 = false;
  43706. _this.UV1 = false;
  43707. _this.UV2 = false;
  43708. _this.ALBEDO = false;
  43709. _this.ALBEDODIRECTUV = 0;
  43710. _this.VERTEXCOLOR = false;
  43711. _this.AMBIENT = false;
  43712. _this.AMBIENTDIRECTUV = 0;
  43713. _this.AMBIENTINGRAYSCALE = false;
  43714. _this.OPACITY = false;
  43715. _this.VERTEXALPHA = false;
  43716. _this.OPACITYDIRECTUV = 0;
  43717. _this.OPACITYRGB = false;
  43718. _this.ALPHATEST = false;
  43719. _this.DEPTHPREPASS = false;
  43720. _this.ALPHABLEND = false;
  43721. _this.ALPHAFROMALBEDO = false;
  43722. _this.ALPHATESTVALUE = "0.5";
  43723. _this.SPECULAROVERALPHA = false;
  43724. _this.RADIANCEOVERALPHA = false;
  43725. _this.ALPHAFRESNEL = false;
  43726. _this.LINEARALPHAFRESNEL = false;
  43727. _this.PREMULTIPLYALPHA = false;
  43728. _this.EMISSIVE = false;
  43729. _this.EMISSIVEDIRECTUV = 0;
  43730. _this.REFLECTIVITY = false;
  43731. _this.REFLECTIVITYDIRECTUV = 0;
  43732. _this.SPECULARTERM = false;
  43733. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43734. _this.MICROSURFACEAUTOMATIC = false;
  43735. _this.LODBASEDMICROSFURACE = false;
  43736. _this.MICROSURFACEMAP = false;
  43737. _this.MICROSURFACEMAPDIRECTUV = 0;
  43738. _this.METALLICWORKFLOW = false;
  43739. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43740. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43741. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43742. _this.AOSTOREINMETALMAPRED = false;
  43743. _this.ENVIRONMENTBRDF = false;
  43744. _this.NORMAL = false;
  43745. _this.TANGENT = false;
  43746. _this.BUMP = false;
  43747. _this.BUMPDIRECTUV = 0;
  43748. _this.OBJECTSPACE_NORMALMAP = false;
  43749. _this.PARALLAX = false;
  43750. _this.PARALLAXOCCLUSION = false;
  43751. _this.NORMALXYSCALE = true;
  43752. _this.LIGHTMAP = false;
  43753. _this.LIGHTMAPDIRECTUV = 0;
  43754. _this.USELIGHTMAPASSHADOWMAP = false;
  43755. _this.GAMMALIGHTMAP = false;
  43756. _this.REFLECTION = false;
  43757. _this.REFLECTIONMAP_3D = false;
  43758. _this.REFLECTIONMAP_SPHERICAL = false;
  43759. _this.REFLECTIONMAP_PLANAR = false;
  43760. _this.REFLECTIONMAP_CUBIC = false;
  43761. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43762. _this.REFLECTIONMAP_PROJECTION = false;
  43763. _this.REFLECTIONMAP_SKYBOX = false;
  43764. _this.REFLECTIONMAP_EXPLICIT = false;
  43765. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43766. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43767. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43768. _this.INVERTCUBICMAP = false;
  43769. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43770. _this.USESPHERICALINVERTEX = false;
  43771. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43772. _this.LODINREFLECTIONALPHA = false;
  43773. _this.GAMMAREFLECTION = false;
  43774. _this.RGBDREFLECTION = false;
  43775. _this.RADIANCEOCCLUSION = false;
  43776. _this.HORIZONOCCLUSION = false;
  43777. _this.REFRACTION = false;
  43778. _this.REFRACTIONMAP_3D = false;
  43779. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43780. _this.LODINREFRACTIONALPHA = false;
  43781. _this.GAMMAREFRACTION = false;
  43782. _this.RGBDREFRACTION = false;
  43783. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43784. _this.INSTANCES = false;
  43785. _this.NUM_BONE_INFLUENCERS = 0;
  43786. _this.BonesPerMesh = 0;
  43787. _this.NONUNIFORMSCALING = false;
  43788. _this.MORPHTARGETS = false;
  43789. _this.MORPHTARGETS_NORMAL = false;
  43790. _this.MORPHTARGETS_TANGENT = false;
  43791. _this.NUM_MORPH_INFLUENCERS = 0;
  43792. _this.IMAGEPROCESSING = false;
  43793. _this.VIGNETTE = false;
  43794. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43795. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43796. _this.TONEMAPPING = false;
  43797. _this.TONEMAPPING_ACES = false;
  43798. _this.CONTRAST = false;
  43799. _this.COLORCURVES = false;
  43800. _this.COLORGRADING = false;
  43801. _this.COLORGRADING3D = false;
  43802. _this.SAMPLER3DGREENDEPTH = false;
  43803. _this.SAMPLER3DBGRMAP = false;
  43804. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43805. _this.EXPOSURE = false;
  43806. _this.USEPHYSICALLIGHTFALLOFF = false;
  43807. _this.USEGLTFLIGHTFALLOFF = false;
  43808. _this.TWOSIDEDLIGHTING = false;
  43809. _this.SHADOWFLOAT = false;
  43810. _this.CLIPPLANE = false;
  43811. _this.CLIPPLANE2 = false;
  43812. _this.CLIPPLANE3 = false;
  43813. _this.CLIPPLANE4 = false;
  43814. _this.POINTSIZE = false;
  43815. _this.FOG = false;
  43816. _this.LOGARITHMICDEPTH = false;
  43817. _this.FORCENORMALFORWARD = false;
  43818. _this.SPECULARAA = false;
  43819. _this.UNLIT = false;
  43820. _this.rebuild();
  43821. return _this;
  43822. }
  43823. /**
  43824. * Resets the PBR Material defines.
  43825. */
  43826. PBRMaterialDefines.prototype.reset = function () {
  43827. _super.prototype.reset.call(this);
  43828. this.ALPHATESTVALUE = "0.5";
  43829. this.PBR = true;
  43830. };
  43831. return PBRMaterialDefines;
  43832. }(BABYLON.MaterialDefines));
  43833. /**
  43834. * The Physically based material base class of BJS.
  43835. *
  43836. * This offers the main features of a standard PBR material.
  43837. * For more information, please refer to the documentation :
  43838. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43839. */
  43840. var PBRBaseMaterial = /** @class */ (function (_super) {
  43841. __extends(PBRBaseMaterial, _super);
  43842. /**
  43843. * Instantiates a new PBRMaterial instance.
  43844. *
  43845. * @param name The material name
  43846. * @param scene The scene the material will be use in.
  43847. */
  43848. function PBRBaseMaterial(name, scene) {
  43849. var _this = _super.call(this, name, scene) || this;
  43850. /**
  43851. * Intensity of the direct lights e.g. the four lights available in your scene.
  43852. * This impacts both the direct diffuse and specular highlights.
  43853. */
  43854. _this._directIntensity = 1.0;
  43855. /**
  43856. * Intensity of the emissive part of the material.
  43857. * This helps controlling the emissive effect without modifying the emissive color.
  43858. */
  43859. _this._emissiveIntensity = 1.0;
  43860. /**
  43861. * Intensity of the environment e.g. how much the environment will light the object
  43862. * either through harmonics for rough material or through the refelction for shiny ones.
  43863. */
  43864. _this._environmentIntensity = 1.0;
  43865. /**
  43866. * This is a special control allowing the reduction of the specular highlights coming from the
  43867. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43868. */
  43869. _this._specularIntensity = 1.0;
  43870. /**
  43871. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43872. */
  43873. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43874. /**
  43875. * Debug Control allowing disabling the bump map on this material.
  43876. */
  43877. _this._disableBumpMap = false;
  43878. /**
  43879. * AKA Occlusion Texture Intensity in other nomenclature.
  43880. */
  43881. _this._ambientTextureStrength = 1.0;
  43882. /**
  43883. * The color of a material in ambient lighting.
  43884. */
  43885. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43886. /**
  43887. * AKA Diffuse Color in other nomenclature.
  43888. */
  43889. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43890. /**
  43891. * AKA Specular Color in other nomenclature.
  43892. */
  43893. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43894. /**
  43895. * The color applied when light is reflected from a material.
  43896. */
  43897. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43898. /**
  43899. * The color applied when light is emitted from a material.
  43900. */
  43901. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43902. /**
  43903. * AKA Glossiness in other nomenclature.
  43904. */
  43905. _this._microSurface = 0.9;
  43906. /**
  43907. * source material index of refraction (IOR)' / 'destination material IOR.
  43908. */
  43909. _this._indexOfRefraction = 0.66;
  43910. /**
  43911. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43912. */
  43913. _this._invertRefractionY = false;
  43914. /**
  43915. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43916. * Materials half opaque for instance using refraction could benefit from this control.
  43917. */
  43918. _this._linkRefractionWithTransparency = false;
  43919. /**
  43920. * Specifies that the material will use the light map as a show map.
  43921. */
  43922. _this._useLightmapAsShadowmap = false;
  43923. /**
  43924. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43925. * makes the reflect vector face the model (under horizon).
  43926. */
  43927. _this._useHorizonOcclusion = true;
  43928. /**
  43929. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43930. * too much the area relying on ambient texture to define their ambient occlusion.
  43931. */
  43932. _this._useRadianceOcclusion = true;
  43933. /**
  43934. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43935. */
  43936. _this._useAlphaFromAlbedoTexture = false;
  43937. /**
  43938. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43939. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43940. */
  43941. _this._useSpecularOverAlpha = true;
  43942. /**
  43943. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43944. */
  43945. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43946. /**
  43947. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43948. */
  43949. _this._useRoughnessFromMetallicTextureAlpha = true;
  43950. /**
  43951. * Specifies if the metallic texture contains the roughness information in its green channel.
  43952. */
  43953. _this._useRoughnessFromMetallicTextureGreen = false;
  43954. /**
  43955. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43956. */
  43957. _this._useMetallnessFromMetallicTextureBlue = false;
  43958. /**
  43959. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43960. */
  43961. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43962. /**
  43963. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43964. */
  43965. _this._useAmbientInGrayScale = false;
  43966. /**
  43967. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43968. * The material will try to infer what glossiness each pixel should be.
  43969. */
  43970. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43971. /**
  43972. * Defines the falloff type used in this material.
  43973. * It by default is Physical.
  43974. */
  43975. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  43976. /**
  43977. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43978. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43979. */
  43980. _this._useRadianceOverAlpha = true;
  43981. /**
  43982. * Allows using an object space normal map (instead of tangent space).
  43983. */
  43984. _this._useObjectSpaceNormalMap = false;
  43985. /**
  43986. * Allows using the bump map in parallax mode.
  43987. */
  43988. _this._useParallax = false;
  43989. /**
  43990. * Allows using the bump map in parallax occlusion mode.
  43991. */
  43992. _this._useParallaxOcclusion = false;
  43993. /**
  43994. * Controls the scale bias of the parallax mode.
  43995. */
  43996. _this._parallaxScaleBias = 0.05;
  43997. /**
  43998. * If sets to true, disables all the lights affecting the material.
  43999. */
  44000. _this._disableLighting = false;
  44001. /**
  44002. * Number of Simultaneous lights allowed on the material.
  44003. */
  44004. _this._maxSimultaneousLights = 4;
  44005. /**
  44006. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44007. */
  44008. _this._invertNormalMapX = false;
  44009. /**
  44010. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44011. */
  44012. _this._invertNormalMapY = false;
  44013. /**
  44014. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44015. */
  44016. _this._twoSidedLighting = false;
  44017. /**
  44018. * Defines the alpha limits in alpha test mode.
  44019. */
  44020. _this._alphaCutOff = 0.4;
  44021. /**
  44022. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44023. */
  44024. _this._forceAlphaTest = false;
  44025. /**
  44026. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44027. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44028. */
  44029. _this._useAlphaFresnel = false;
  44030. /**
  44031. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44032. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44033. */
  44034. _this._useLinearAlphaFresnel = false;
  44035. /**
  44036. * The transparency mode of the material.
  44037. */
  44038. _this._transparencyMode = null;
  44039. /**
  44040. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44041. * from cos thetav and roughness:
  44042. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44043. */
  44044. _this._environmentBRDFTexture = null;
  44045. /**
  44046. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44047. */
  44048. _this._forceIrradianceInFragment = false;
  44049. /**
  44050. * Force normal to face away from face.
  44051. */
  44052. _this._forceNormalForward = false;
  44053. /**
  44054. * Enables specular anti aliasing in the PBR shader.
  44055. * It will both interacts on the Geometry for analytical and IBL lighting.
  44056. * It also prefilter the roughness map based on the bump values.
  44057. */
  44058. _this._enableSpecularAntiAliasing = false;
  44059. /**
  44060. * Stores the available render targets.
  44061. */
  44062. _this._renderTargets = new BABYLON.SmartArray(16);
  44063. /**
  44064. * Sets the global ambient color for the material used in lighting calculations.
  44065. */
  44066. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44067. /**
  44068. * If set to true, no lighting calculations will be applied.
  44069. */
  44070. _this._unlit = false;
  44071. // Setup the default processing configuration to the scene.
  44072. _this._attachImageProcessingConfiguration(null);
  44073. _this.getRenderTargetTextures = function () {
  44074. _this._renderTargets.reset();
  44075. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44076. _this._renderTargets.push(_this._reflectionTexture);
  44077. }
  44078. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44079. _this._renderTargets.push(_this._refractionTexture);
  44080. }
  44081. return _this._renderTargets;
  44082. };
  44083. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44084. return _this;
  44085. }
  44086. /**
  44087. * Attaches a new image processing configuration to the PBR Material.
  44088. * @param configuration
  44089. */
  44090. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44091. var _this = this;
  44092. if (configuration === this._imageProcessingConfiguration) {
  44093. return;
  44094. }
  44095. // Detaches observer.
  44096. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44097. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44098. }
  44099. // Pick the scene configuration if needed.
  44100. if (!configuration) {
  44101. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44102. }
  44103. else {
  44104. this._imageProcessingConfiguration = configuration;
  44105. }
  44106. // Attaches observer.
  44107. if (this._imageProcessingConfiguration) {
  44108. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44109. _this._markAllSubMeshesAsImageProcessingDirty();
  44110. });
  44111. }
  44112. };
  44113. /**
  44114. * Gets the name of the material class.
  44115. */
  44116. PBRBaseMaterial.prototype.getClassName = function () {
  44117. return "PBRBaseMaterial";
  44118. };
  44119. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44120. /**
  44121. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44122. */
  44123. get: function () {
  44124. return this._useLogarithmicDepth;
  44125. },
  44126. /**
  44127. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44128. */
  44129. set: function (value) {
  44130. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44131. },
  44132. enumerable: true,
  44133. configurable: true
  44134. });
  44135. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44136. /**
  44137. * Gets the current transparency mode.
  44138. */
  44139. get: function () {
  44140. return this._transparencyMode;
  44141. },
  44142. /**
  44143. * Sets the transparency mode of the material.
  44144. *
  44145. * | Value | Type | Description |
  44146. * | ----- | ----------------------------------- | ----------- |
  44147. * | 0 | OPAQUE | |
  44148. * | 1 | ALPHATEST | |
  44149. * | 2 | ALPHABLEND | |
  44150. * | 3 | ALPHATESTANDBLEND | |
  44151. *
  44152. */
  44153. set: function (value) {
  44154. if (this._transparencyMode === value) {
  44155. return;
  44156. }
  44157. this._transparencyMode = value;
  44158. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44159. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44160. },
  44161. enumerable: true,
  44162. configurable: true
  44163. });
  44164. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44165. /**
  44166. * Returns true if alpha blending should be disabled.
  44167. */
  44168. get: function () {
  44169. return (this._linkRefractionWithTransparency ||
  44170. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44171. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44172. },
  44173. enumerable: true,
  44174. configurable: true
  44175. });
  44176. /**
  44177. * Specifies whether or not this material should be rendered in alpha blend mode.
  44178. */
  44179. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44180. if (this._disableAlphaBlending) {
  44181. return false;
  44182. }
  44183. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44184. };
  44185. /**
  44186. * Specifies if the mesh will require alpha blending.
  44187. * @param mesh - BJS mesh.
  44188. */
  44189. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44190. if (this._disableAlphaBlending) {
  44191. return false;
  44192. }
  44193. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44194. };
  44195. /**
  44196. * Specifies whether or not this material should be rendered in alpha test mode.
  44197. */
  44198. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44199. if (this._forceAlphaTest) {
  44200. return true;
  44201. }
  44202. if (this._linkRefractionWithTransparency) {
  44203. return false;
  44204. }
  44205. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44206. };
  44207. /**
  44208. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44209. */
  44210. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44211. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44212. };
  44213. /**
  44214. * Gets the texture used for the alpha test.
  44215. */
  44216. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44217. return this._albedoTexture;
  44218. };
  44219. /**
  44220. * Specifies that the submesh is ready to be used.
  44221. * @param mesh - BJS mesh.
  44222. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44223. * @param useInstances - Specifies that instances should be used.
  44224. * @returns - boolean indicating that the submesh is ready or not.
  44225. */
  44226. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44227. if (subMesh.effect && this.isFrozen) {
  44228. if (this._wasPreviouslyReady) {
  44229. return true;
  44230. }
  44231. }
  44232. if (!subMesh._materialDefines) {
  44233. subMesh._materialDefines = new PBRMaterialDefines();
  44234. }
  44235. var defines = subMesh._materialDefines;
  44236. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44237. if (defines._renderId === this.getScene().getRenderId()) {
  44238. return true;
  44239. }
  44240. }
  44241. var scene = this.getScene();
  44242. var engine = scene.getEngine();
  44243. if (defines._areTexturesDirty) {
  44244. if (scene.texturesEnabled) {
  44245. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44246. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44247. return false;
  44248. }
  44249. }
  44250. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44251. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44252. return false;
  44253. }
  44254. }
  44255. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44256. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44257. return false;
  44258. }
  44259. }
  44260. var reflectionTexture = this._getReflectionTexture();
  44261. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44262. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44263. return false;
  44264. }
  44265. }
  44266. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44267. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44268. return false;
  44269. }
  44270. }
  44271. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44272. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44273. return false;
  44274. }
  44275. }
  44276. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44277. if (this._metallicTexture) {
  44278. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44279. return false;
  44280. }
  44281. }
  44282. else if (this._reflectivityTexture) {
  44283. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44284. return false;
  44285. }
  44286. }
  44287. if (this._microSurfaceTexture) {
  44288. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44289. return false;
  44290. }
  44291. }
  44292. }
  44293. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44294. // Bump texture cannot be not blocking.
  44295. if (!this._bumpTexture.isReady()) {
  44296. return false;
  44297. }
  44298. }
  44299. var refractionTexture = this._getRefractionTexture();
  44300. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44301. if (!refractionTexture.isReadyOrNotBlocking()) {
  44302. return false;
  44303. }
  44304. }
  44305. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44306. // This is blocking.
  44307. if (!this._environmentBRDFTexture.isReady()) {
  44308. return false;
  44309. }
  44310. }
  44311. }
  44312. }
  44313. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44314. if (!this._imageProcessingConfiguration.isReady()) {
  44315. return false;
  44316. }
  44317. }
  44318. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44319. mesh.createNormals(true);
  44320. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44321. }
  44322. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44323. if (effect) {
  44324. scene.resetCachedMaterial();
  44325. subMesh.setEffect(effect, defines);
  44326. this.buildUniformLayout();
  44327. }
  44328. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44329. return false;
  44330. }
  44331. defines._renderId = scene.getRenderId();
  44332. this._wasPreviouslyReady = true;
  44333. return true;
  44334. };
  44335. /**
  44336. * Specifies if the material uses metallic roughness workflow.
  44337. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44338. */
  44339. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44340. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44341. return true;
  44342. }
  44343. return false;
  44344. };
  44345. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44346. if (onCompiled === void 0) { onCompiled = null; }
  44347. if (onError === void 0) { onError = null; }
  44348. if (useInstances === void 0) { useInstances = null; }
  44349. if (useClipPlane === void 0) { useClipPlane = null; }
  44350. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44351. if (!defines.isDirty) {
  44352. return null;
  44353. }
  44354. defines.markAsProcessed();
  44355. var scene = this.getScene();
  44356. var engine = scene.getEngine();
  44357. // Fallbacks
  44358. var fallbacks = new BABYLON.EffectFallbacks();
  44359. var fallbackRank = 0;
  44360. if (defines.USESPHERICALINVERTEX) {
  44361. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44362. }
  44363. if (defines.FOG) {
  44364. fallbacks.addFallback(fallbackRank, "FOG");
  44365. }
  44366. if (defines.SPECULARAA) {
  44367. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  44368. }
  44369. if (defines.POINTSIZE) {
  44370. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44371. }
  44372. if (defines.LOGARITHMICDEPTH) {
  44373. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44374. }
  44375. if (defines.PARALLAX) {
  44376. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44377. }
  44378. if (defines.PARALLAXOCCLUSION) {
  44379. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44380. }
  44381. if (defines.ENVIRONMENTBRDF) {
  44382. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44383. }
  44384. if (defines.TANGENT) {
  44385. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44386. }
  44387. if (defines.BUMP) {
  44388. fallbacks.addFallback(fallbackRank++, "BUMP");
  44389. }
  44390. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44391. if (defines.SPECULARTERM) {
  44392. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44393. }
  44394. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44395. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44396. }
  44397. if (defines.LIGHTMAP) {
  44398. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44399. }
  44400. if (defines.NORMAL) {
  44401. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44402. }
  44403. if (defines.AMBIENT) {
  44404. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44405. }
  44406. if (defines.EMISSIVE) {
  44407. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44408. }
  44409. if (defines.VERTEXCOLOR) {
  44410. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44411. }
  44412. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44413. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44414. }
  44415. if (defines.MORPHTARGETS) {
  44416. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44417. }
  44418. //Attributes
  44419. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44420. if (defines.NORMAL) {
  44421. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44422. }
  44423. if (defines.TANGENT) {
  44424. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44425. }
  44426. if (defines.UV1) {
  44427. attribs.push(BABYLON.VertexBuffer.UVKind);
  44428. }
  44429. if (defines.UV2) {
  44430. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44431. }
  44432. if (defines.VERTEXCOLOR) {
  44433. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44434. }
  44435. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44436. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44437. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44438. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44439. "vFogInfos", "vFogColor", "pointSize",
  44440. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44441. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44442. "mBones",
  44443. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44444. "vLightingIntensity",
  44445. "logarithmicDepthConstant",
  44446. "vSphericalX", "vSphericalY", "vSphericalZ",
  44447. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44448. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44449. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44450. "vTangentSpaceParams"
  44451. ];
  44452. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44453. "bumpSampler", "lightmapSampler", "opacitySampler",
  44454. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44455. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44456. "microSurfaceSampler", "environmentBrdfSampler"];
  44457. var uniformBuffers = ["Material", "Scene"];
  44458. if (BABYLON.ImageProcessingConfiguration) {
  44459. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44460. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44461. }
  44462. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44463. uniformsNames: uniforms,
  44464. uniformBuffersNames: uniformBuffers,
  44465. samplers: samplers,
  44466. defines: defines,
  44467. maxSimultaneousLights: this._maxSimultaneousLights
  44468. });
  44469. var join = defines.toString();
  44470. return engine.createEffect("pbr", {
  44471. attributes: attribs,
  44472. uniformsNames: uniforms,
  44473. uniformBuffersNames: uniformBuffers,
  44474. samplers: samplers,
  44475. defines: join,
  44476. fallbacks: fallbacks,
  44477. onCompiled: onCompiled,
  44478. onError: onError,
  44479. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44480. }, engine);
  44481. };
  44482. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44483. if (useInstances === void 0) { useInstances = null; }
  44484. if (useClipPlane === void 0) { useClipPlane = null; }
  44485. var scene = this.getScene();
  44486. var engine = scene.getEngine();
  44487. // Lights
  44488. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44489. defines._needNormals = true;
  44490. // Textures
  44491. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44492. if (defines._areTexturesDirty) {
  44493. defines._needUVs = false;
  44494. if (scene.texturesEnabled) {
  44495. if (scene.getEngine().getCaps().textureLOD) {
  44496. defines.LODBASEDMICROSFURACE = true;
  44497. }
  44498. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44499. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44500. }
  44501. else {
  44502. defines.ALBEDO = false;
  44503. }
  44504. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44505. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44506. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44507. }
  44508. else {
  44509. defines.AMBIENT = false;
  44510. }
  44511. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44512. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44513. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44514. }
  44515. else {
  44516. defines.OPACITY = false;
  44517. }
  44518. var reflectionTexture = this._getReflectionTexture();
  44519. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44520. defines.REFLECTION = true;
  44521. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44522. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44523. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44524. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44525. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44526. defines.INVERTCUBICMAP = true;
  44527. }
  44528. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44529. switch (reflectionTexture.coordinatesMode) {
  44530. case BABYLON.Texture.EXPLICIT_MODE:
  44531. defines.REFLECTIONMAP_EXPLICIT = true;
  44532. break;
  44533. case BABYLON.Texture.PLANAR_MODE:
  44534. defines.REFLECTIONMAP_PLANAR = true;
  44535. break;
  44536. case BABYLON.Texture.PROJECTION_MODE:
  44537. defines.REFLECTIONMAP_PROJECTION = true;
  44538. break;
  44539. case BABYLON.Texture.SKYBOX_MODE:
  44540. defines.REFLECTIONMAP_SKYBOX = true;
  44541. break;
  44542. case BABYLON.Texture.SPHERICAL_MODE:
  44543. defines.REFLECTIONMAP_SPHERICAL = true;
  44544. break;
  44545. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44546. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44547. break;
  44548. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44549. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44550. break;
  44551. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44552. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44553. break;
  44554. case BABYLON.Texture.CUBIC_MODE:
  44555. case BABYLON.Texture.INVCUBIC_MODE:
  44556. default:
  44557. defines.REFLECTIONMAP_CUBIC = true;
  44558. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44559. break;
  44560. }
  44561. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44562. if (reflectionTexture.sphericalPolynomial) {
  44563. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44564. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44565. defines.USESPHERICALINVERTEX = false;
  44566. }
  44567. else {
  44568. defines.USESPHERICALINVERTEX = true;
  44569. }
  44570. }
  44571. }
  44572. }
  44573. else {
  44574. defines.REFLECTION = false;
  44575. defines.REFLECTIONMAP_3D = false;
  44576. defines.REFLECTIONMAP_SPHERICAL = false;
  44577. defines.REFLECTIONMAP_PLANAR = false;
  44578. defines.REFLECTIONMAP_CUBIC = false;
  44579. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44580. defines.REFLECTIONMAP_PROJECTION = false;
  44581. defines.REFLECTIONMAP_SKYBOX = false;
  44582. defines.REFLECTIONMAP_EXPLICIT = false;
  44583. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44584. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44585. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44586. defines.INVERTCUBICMAP = false;
  44587. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44588. defines.USESPHERICALINVERTEX = false;
  44589. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44590. defines.LODINREFLECTIONALPHA = false;
  44591. defines.GAMMAREFLECTION = false;
  44592. defines.RGBDREFLECTION = false;
  44593. }
  44594. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44595. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44596. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44597. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44598. }
  44599. else {
  44600. defines.LIGHTMAP = false;
  44601. }
  44602. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44603. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44604. }
  44605. else {
  44606. defines.EMISSIVE = false;
  44607. }
  44608. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44609. if (this._metallicTexture) {
  44610. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44611. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44612. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44613. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44614. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44615. }
  44616. else if (this._reflectivityTexture) {
  44617. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44618. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44619. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44620. }
  44621. else {
  44622. defines.REFLECTIVITY = false;
  44623. }
  44624. if (this._microSurfaceTexture) {
  44625. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44626. }
  44627. else {
  44628. defines.MICROSURFACEMAP = false;
  44629. }
  44630. }
  44631. else {
  44632. defines.REFLECTIVITY = false;
  44633. defines.MICROSURFACEMAP = false;
  44634. }
  44635. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44636. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44637. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44638. defines.PARALLAX = true;
  44639. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44640. }
  44641. else {
  44642. defines.PARALLAX = false;
  44643. }
  44644. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44645. }
  44646. else {
  44647. defines.BUMP = false;
  44648. }
  44649. var refractionTexture = this._getRefractionTexture();
  44650. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44651. defines.REFRACTION = true;
  44652. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44653. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44654. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44655. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44656. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44657. if (this._linkRefractionWithTransparency) {
  44658. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44659. }
  44660. }
  44661. else {
  44662. defines.REFRACTION = false;
  44663. }
  44664. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44665. defines.ENVIRONMENTBRDF = true;
  44666. }
  44667. else {
  44668. defines.ENVIRONMENTBRDF = false;
  44669. }
  44670. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44671. defines.ALPHAFROMALBEDO = true;
  44672. }
  44673. else {
  44674. defines.ALPHAFROMALBEDO = false;
  44675. }
  44676. }
  44677. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44678. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  44679. defines.USEPHYSICALLIGHTFALLOFF = false;
  44680. defines.USEGLTFLIGHTFALLOFF = false;
  44681. }
  44682. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  44683. defines.USEPHYSICALLIGHTFALLOFF = false;
  44684. defines.USEGLTFLIGHTFALLOFF = true;
  44685. }
  44686. else {
  44687. defines.USEPHYSICALLIGHTFALLOFF = true;
  44688. defines.USEGLTFLIGHTFALLOFF = false;
  44689. }
  44690. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44691. if (!this.backFaceCulling && this._twoSidedLighting) {
  44692. defines.TWOSIDEDLIGHTING = true;
  44693. }
  44694. else {
  44695. defines.TWOSIDEDLIGHTING = false;
  44696. }
  44697. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44698. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44699. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44700. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44701. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44702. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44703. }
  44704. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44705. this._imageProcessingConfiguration.prepareDefines(defines);
  44706. }
  44707. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44708. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44709. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44710. // Misc.
  44711. if (defines._areMiscDirty) {
  44712. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44713. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44714. }
  44715. // Values that need to be evaluated on every frame
  44716. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44717. // Attribs
  44718. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44719. };
  44720. /**
  44721. * Force shader compilation
  44722. */
  44723. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44724. var _this = this;
  44725. var localOptions = __assign({ clipPlane: false }, options);
  44726. var defines = new PBRMaterialDefines();
  44727. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44728. if (effect.isReady()) {
  44729. if (onCompiled) {
  44730. onCompiled(this);
  44731. }
  44732. }
  44733. else {
  44734. effect.onCompileObservable.add(function () {
  44735. if (onCompiled) {
  44736. onCompiled(_this);
  44737. }
  44738. });
  44739. }
  44740. };
  44741. /**
  44742. * Initializes the uniform buffer layout for the shader.
  44743. */
  44744. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44745. // Order is important !
  44746. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44747. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44748. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44749. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44750. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44751. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44752. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44753. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44754. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44755. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44756. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44757. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44758. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44759. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44760. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44761. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44762. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44763. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44764. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44765. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44766. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44767. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44768. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44769. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44770. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44771. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44772. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44773. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44774. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44775. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44776. this._uniformBuffer.addUniform("pointSize", 1);
  44777. this._uniformBuffer.create();
  44778. };
  44779. /**
  44780. * Unbinds the textures.
  44781. */
  44782. PBRBaseMaterial.prototype.unbind = function () {
  44783. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44784. this._uniformBuffer.setTexture("reflectionSampler", null);
  44785. }
  44786. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44787. this._uniformBuffer.setTexture("refractionSampler", null);
  44788. }
  44789. _super.prototype.unbind.call(this);
  44790. };
  44791. /**
  44792. * Binds the submesh data.
  44793. * @param world - The world matrix.
  44794. * @param mesh - The BJS mesh.
  44795. * @param subMesh - A submesh of the BJS mesh.
  44796. */
  44797. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44798. var scene = this.getScene();
  44799. var defines = subMesh._materialDefines;
  44800. if (!defines) {
  44801. return;
  44802. }
  44803. var effect = subMesh.effect;
  44804. if (!effect) {
  44805. return;
  44806. }
  44807. this._activeEffect = effect;
  44808. // Matrices
  44809. this.bindOnlyWorldMatrix(world);
  44810. // Normal Matrix
  44811. if (defines.OBJECTSPACE_NORMALMAP) {
  44812. world.toNormalMatrix(this._normalMatrix);
  44813. this.bindOnlyNormalMatrix(this._normalMatrix);
  44814. }
  44815. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44816. // Bones
  44817. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44818. var reflectionTexture = null;
  44819. if (mustRebind) {
  44820. this._uniformBuffer.bindToEffect(effect, "Material");
  44821. this.bindViewProjection(effect);
  44822. reflectionTexture = this._getReflectionTexture();
  44823. var refractionTexture = this._getRefractionTexture();
  44824. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44825. // Texture uniforms
  44826. if (scene.texturesEnabled) {
  44827. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44828. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44829. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44830. }
  44831. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44832. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44833. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44834. }
  44835. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44836. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44837. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44838. }
  44839. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44840. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44841. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44842. if (reflectionTexture.boundingBoxSize) {
  44843. var cubeTexture = reflectionTexture;
  44844. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44845. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44846. }
  44847. var polynomials = reflectionTexture.sphericalPolynomial;
  44848. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44849. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44850. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44851. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44852. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44853. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44854. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44855. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44856. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44857. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44858. }
  44859. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44860. }
  44861. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44862. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44863. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44864. }
  44865. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44866. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44867. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44868. }
  44869. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44870. if (this._metallicTexture) {
  44871. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44872. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44873. }
  44874. else if (this._reflectivityTexture) {
  44875. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44876. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44877. }
  44878. if (this._microSurfaceTexture) {
  44879. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44880. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44881. }
  44882. }
  44883. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44884. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44885. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44886. if (scene._mirroredCameraPosition) {
  44887. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44888. }
  44889. else {
  44890. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44891. }
  44892. }
  44893. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44894. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44895. var depth = 1.0;
  44896. if (!refractionTexture.isCube) {
  44897. if (refractionTexture.depth) {
  44898. depth = refractionTexture.depth;
  44899. }
  44900. }
  44901. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44902. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44903. }
  44904. }
  44905. // Point size
  44906. if (this.pointsCloud) {
  44907. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44908. }
  44909. // Colors
  44910. if (defines.METALLICWORKFLOW) {
  44911. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44912. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44913. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44914. }
  44915. else {
  44916. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44917. }
  44918. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44919. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44920. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44921. // Misc
  44922. this._lightingInfos.x = this._directIntensity;
  44923. this._lightingInfos.y = this._emissiveIntensity;
  44924. this._lightingInfos.z = this._environmentIntensity;
  44925. this._lightingInfos.w = this._specularIntensity;
  44926. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44927. }
  44928. // Textures
  44929. if (scene.texturesEnabled) {
  44930. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44931. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44932. }
  44933. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44934. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44935. }
  44936. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44937. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44938. }
  44939. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44940. if (defines.LODBASEDMICROSFURACE) {
  44941. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44942. }
  44943. else {
  44944. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44945. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44946. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44947. }
  44948. }
  44949. if (defines.ENVIRONMENTBRDF) {
  44950. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44951. }
  44952. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44953. if (defines.LODBASEDMICROSFURACE) {
  44954. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44955. }
  44956. else {
  44957. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44958. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44959. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44960. }
  44961. }
  44962. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44963. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44964. }
  44965. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44966. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44967. }
  44968. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44969. if (this._metallicTexture) {
  44970. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44971. }
  44972. else if (this._reflectivityTexture) {
  44973. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44974. }
  44975. if (this._microSurfaceTexture) {
  44976. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44977. }
  44978. }
  44979. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44980. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44981. }
  44982. }
  44983. // Clip plane
  44984. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44985. // Colors
  44986. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44987. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44988. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44989. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44990. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44991. }
  44992. if (mustRebind || !this.isFrozen) {
  44993. // Lights
  44994. if (scene.lightsEnabled && !this._disableLighting) {
  44995. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  44996. }
  44997. // View
  44998. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44999. this.bindView(effect);
  45000. }
  45001. // Fog
  45002. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  45003. // Morph targets
  45004. if (defines.NUM_MORPH_INFLUENCERS) {
  45005. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45006. }
  45007. // image processing
  45008. this._imageProcessingConfiguration.bind(this._activeEffect);
  45009. // Log. depth
  45010. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45011. }
  45012. this._uniformBuffer.update();
  45013. this._afterBind(mesh, this._activeEffect);
  45014. };
  45015. /**
  45016. * Returns the animatable textures.
  45017. * @returns - Array of animatable textures.
  45018. */
  45019. PBRBaseMaterial.prototype.getAnimatables = function () {
  45020. var results = [];
  45021. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45022. results.push(this._albedoTexture);
  45023. }
  45024. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45025. results.push(this._ambientTexture);
  45026. }
  45027. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45028. results.push(this._opacityTexture);
  45029. }
  45030. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45031. results.push(this._reflectionTexture);
  45032. }
  45033. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45034. results.push(this._emissiveTexture);
  45035. }
  45036. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45037. results.push(this._metallicTexture);
  45038. }
  45039. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45040. results.push(this._reflectivityTexture);
  45041. }
  45042. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45043. results.push(this._bumpTexture);
  45044. }
  45045. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45046. results.push(this._lightmapTexture);
  45047. }
  45048. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45049. results.push(this._refractionTexture);
  45050. }
  45051. return results;
  45052. };
  45053. /**
  45054. * Returns the texture used for reflections.
  45055. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45056. */
  45057. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45058. if (this._reflectionTexture) {
  45059. return this._reflectionTexture;
  45060. }
  45061. return this.getScene().environmentTexture;
  45062. };
  45063. /**
  45064. * Returns the texture used for refraction or null if none is used.
  45065. * @returns - Refection texture if present. If no refraction texture and refraction
  45066. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45067. */
  45068. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45069. if (this._refractionTexture) {
  45070. return this._refractionTexture;
  45071. }
  45072. if (this._linkRefractionWithTransparency) {
  45073. return this.getScene().environmentTexture;
  45074. }
  45075. return null;
  45076. };
  45077. /**
  45078. * Disposes the resources of the material.
  45079. * @param forceDisposeEffect - Forces the disposal of effects.
  45080. * @param forceDisposeTextures - Forces the disposal of all textures.
  45081. */
  45082. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45083. if (forceDisposeTextures) {
  45084. if (this._albedoTexture) {
  45085. this._albedoTexture.dispose();
  45086. }
  45087. if (this._ambientTexture) {
  45088. this._ambientTexture.dispose();
  45089. }
  45090. if (this._opacityTexture) {
  45091. this._opacityTexture.dispose();
  45092. }
  45093. if (this._reflectionTexture) {
  45094. this._reflectionTexture.dispose();
  45095. }
  45096. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45097. this._environmentBRDFTexture.dispose();
  45098. }
  45099. if (this._emissiveTexture) {
  45100. this._emissiveTexture.dispose();
  45101. }
  45102. if (this._metallicTexture) {
  45103. this._metallicTexture.dispose();
  45104. }
  45105. if (this._reflectivityTexture) {
  45106. this._reflectivityTexture.dispose();
  45107. }
  45108. if (this._bumpTexture) {
  45109. this._bumpTexture.dispose();
  45110. }
  45111. if (this._lightmapTexture) {
  45112. this._lightmapTexture.dispose();
  45113. }
  45114. if (this._refractionTexture) {
  45115. this._refractionTexture.dispose();
  45116. }
  45117. }
  45118. this._renderTargets.dispose();
  45119. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45120. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45121. }
  45122. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45123. };
  45124. /**
  45125. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  45126. */
  45127. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  45128. /**
  45129. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  45130. * to enhance interoperability with other engines.
  45131. */
  45132. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  45133. /**
  45134. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  45135. * to enhance interoperability with other materials.
  45136. */
  45137. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  45138. /**
  45139. * Stores the reflectivity values based on metallic roughness workflow.
  45140. */
  45141. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45142. __decorate([
  45143. BABYLON.serializeAsImageProcessingConfiguration()
  45144. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45145. __decorate([
  45146. BABYLON.serialize()
  45147. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45148. __decorate([
  45149. BABYLON.serialize()
  45150. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45151. return PBRBaseMaterial;
  45152. }(BABYLON.PushMaterial));
  45153. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45154. })(BABYLON || (BABYLON = {}));
  45155. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45156. var BABYLON;
  45157. (function (BABYLON) {
  45158. /**
  45159. * The Physically based simple base material of BJS.
  45160. *
  45161. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45162. * It is used as the base class for both the specGloss and metalRough conventions.
  45163. */
  45164. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45165. __extends(PBRBaseSimpleMaterial, _super);
  45166. /**
  45167. * Instantiates a new PBRMaterial instance.
  45168. *
  45169. * @param name The material name
  45170. * @param scene The scene the material will be use in.
  45171. */
  45172. function PBRBaseSimpleMaterial(name, scene) {
  45173. var _this = _super.call(this, name, scene) || this;
  45174. /**
  45175. * Number of Simultaneous lights allowed on the material.
  45176. */
  45177. _this.maxSimultaneousLights = 4;
  45178. /**
  45179. * If sets to true, disables all the lights affecting the material.
  45180. */
  45181. _this.disableLighting = false;
  45182. /**
  45183. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45184. */
  45185. _this.invertNormalMapX = false;
  45186. /**
  45187. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45188. */
  45189. _this.invertNormalMapY = false;
  45190. /**
  45191. * Emissivie color used to self-illuminate the model.
  45192. */
  45193. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45194. /**
  45195. * Occlusion Channel Strenght.
  45196. */
  45197. _this.occlusionStrength = 1.0;
  45198. _this.useLightmapAsShadowmap = false;
  45199. _this._useAlphaFromAlbedoTexture = true;
  45200. _this._useAmbientInGrayScale = true;
  45201. return _this;
  45202. }
  45203. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45204. /**
  45205. * Gets the current double sided mode.
  45206. */
  45207. get: function () {
  45208. return this._twoSidedLighting;
  45209. },
  45210. /**
  45211. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45212. */
  45213. set: function (value) {
  45214. if (this._twoSidedLighting === value) {
  45215. return;
  45216. }
  45217. this._twoSidedLighting = value;
  45218. this.backFaceCulling = !value;
  45219. this._markAllSubMeshesAsTexturesDirty();
  45220. },
  45221. enumerable: true,
  45222. configurable: true
  45223. });
  45224. /**
  45225. * Return the active textures of the material.
  45226. */
  45227. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45228. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45229. if (this.environmentTexture) {
  45230. activeTextures.push(this.environmentTexture);
  45231. }
  45232. if (this.normalTexture) {
  45233. activeTextures.push(this.normalTexture);
  45234. }
  45235. if (this.emissiveTexture) {
  45236. activeTextures.push(this.emissiveTexture);
  45237. }
  45238. if (this.occlusionTexture) {
  45239. activeTextures.push(this.occlusionTexture);
  45240. }
  45241. if (this.lightmapTexture) {
  45242. activeTextures.push(this.lightmapTexture);
  45243. }
  45244. return activeTextures;
  45245. };
  45246. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45247. if (_super.prototype.hasTexture.call(this, texture)) {
  45248. return true;
  45249. }
  45250. if (this.lightmapTexture === texture) {
  45251. return true;
  45252. }
  45253. return false;
  45254. };
  45255. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45256. return "PBRBaseSimpleMaterial";
  45257. };
  45258. __decorate([
  45259. BABYLON.serialize(),
  45260. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45261. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45262. __decorate([
  45263. BABYLON.serialize(),
  45264. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45265. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45266. __decorate([
  45267. BABYLON.serializeAsTexture(),
  45268. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45269. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45270. __decorate([
  45271. BABYLON.serialize(),
  45272. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45273. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45274. __decorate([
  45275. BABYLON.serialize(),
  45276. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45277. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45278. __decorate([
  45279. BABYLON.serializeAsTexture(),
  45280. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45281. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45282. __decorate([
  45283. BABYLON.serializeAsColor3("emissive"),
  45284. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45285. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45286. __decorate([
  45287. BABYLON.serializeAsTexture(),
  45288. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45289. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45290. __decorate([
  45291. BABYLON.serialize(),
  45292. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45293. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45294. __decorate([
  45295. BABYLON.serializeAsTexture(),
  45296. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45297. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45298. __decorate([
  45299. BABYLON.serialize(),
  45300. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45301. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45302. __decorate([
  45303. BABYLON.serialize()
  45304. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45305. __decorate([
  45306. BABYLON.serializeAsTexture(),
  45307. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45308. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45309. __decorate([
  45310. BABYLON.serialize(),
  45311. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45312. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45313. return PBRBaseSimpleMaterial;
  45314. }(BABYLON.PBRBaseMaterial));
  45315. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45316. })(BABYLON || (BABYLON = {}));
  45317. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45318. var BABYLON;
  45319. (function (BABYLON) {
  45320. /**
  45321. * The Physically based material of BJS.
  45322. *
  45323. * This offers the main features of a standard PBR material.
  45324. * For more information, please refer to the documentation :
  45325. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45326. */
  45327. var PBRMaterial = /** @class */ (function (_super) {
  45328. __extends(PBRMaterial, _super);
  45329. /**
  45330. * Instantiates a new PBRMaterial instance.
  45331. *
  45332. * @param name The material name
  45333. * @param scene The scene the material will be use in.
  45334. */
  45335. function PBRMaterial(name, scene) {
  45336. var _this = _super.call(this, name, scene) || this;
  45337. /**
  45338. * Intensity of the direct lights e.g. the four lights available in your scene.
  45339. * This impacts both the direct diffuse and specular highlights.
  45340. */
  45341. _this.directIntensity = 1.0;
  45342. /**
  45343. * Intensity of the emissive part of the material.
  45344. * This helps controlling the emissive effect without modifying the emissive color.
  45345. */
  45346. _this.emissiveIntensity = 1.0;
  45347. /**
  45348. * Intensity of the environment e.g. how much the environment will light the object
  45349. * either through harmonics for rough material or through the refelction for shiny ones.
  45350. */
  45351. _this.environmentIntensity = 1.0;
  45352. /**
  45353. * This is a special control allowing the reduction of the specular highlights coming from the
  45354. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45355. */
  45356. _this.specularIntensity = 1.0;
  45357. /**
  45358. * Debug Control allowing disabling the bump map on this material.
  45359. */
  45360. _this.disableBumpMap = false;
  45361. /**
  45362. * AKA Occlusion Texture Intensity in other nomenclature.
  45363. */
  45364. _this.ambientTextureStrength = 1.0;
  45365. /**
  45366. * The color of a material in ambient lighting.
  45367. */
  45368. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45369. /**
  45370. * AKA Diffuse Color in other nomenclature.
  45371. */
  45372. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45373. /**
  45374. * AKA Specular Color in other nomenclature.
  45375. */
  45376. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45377. /**
  45378. * The color reflected from the material.
  45379. */
  45380. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45381. /**
  45382. * The color emitted from the material.
  45383. */
  45384. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45385. /**
  45386. * AKA Glossiness in other nomenclature.
  45387. */
  45388. _this.microSurface = 1.0;
  45389. /**
  45390. * source material index of refraction (IOR)' / 'destination material IOR.
  45391. */
  45392. _this.indexOfRefraction = 0.66;
  45393. /**
  45394. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45395. */
  45396. _this.invertRefractionY = false;
  45397. /**
  45398. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45399. * Materials half opaque for instance using refraction could benefit from this control.
  45400. */
  45401. _this.linkRefractionWithTransparency = false;
  45402. _this.useLightmapAsShadowmap = false;
  45403. /**
  45404. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45405. */
  45406. _this.useAlphaFromAlbedoTexture = false;
  45407. /**
  45408. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45409. */
  45410. _this.forceAlphaTest = false;
  45411. /**
  45412. * Defines the alpha limits in alpha test mode.
  45413. */
  45414. _this.alphaCutOff = 0.4;
  45415. /**
  45416. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45417. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45418. */
  45419. _this.useSpecularOverAlpha = true;
  45420. /**
  45421. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45422. */
  45423. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45424. /**
  45425. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45426. */
  45427. _this.useRoughnessFromMetallicTextureAlpha = true;
  45428. /**
  45429. * Specifies if the metallic texture contains the roughness information in its green channel.
  45430. */
  45431. _this.useRoughnessFromMetallicTextureGreen = false;
  45432. /**
  45433. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45434. */
  45435. _this.useMetallnessFromMetallicTextureBlue = false;
  45436. /**
  45437. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45438. */
  45439. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45440. /**
  45441. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45442. */
  45443. _this.useAmbientInGrayScale = false;
  45444. /**
  45445. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45446. * The material will try to infer what glossiness each pixel should be.
  45447. */
  45448. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45449. /**
  45450. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45451. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45452. */
  45453. _this.useRadianceOverAlpha = true;
  45454. /**
  45455. * Allows using an object space normal map (instead of tangent space).
  45456. */
  45457. _this.useObjectSpaceNormalMap = false;
  45458. /**
  45459. * Allows using the bump map in parallax mode.
  45460. */
  45461. _this.useParallax = false;
  45462. /**
  45463. * Allows using the bump map in parallax occlusion mode.
  45464. */
  45465. _this.useParallaxOcclusion = false;
  45466. /**
  45467. * Controls the scale bias of the parallax mode.
  45468. */
  45469. _this.parallaxScaleBias = 0.05;
  45470. /**
  45471. * If sets to true, disables all the lights affecting the material.
  45472. */
  45473. _this.disableLighting = false;
  45474. /**
  45475. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45476. */
  45477. _this.forceIrradianceInFragment = false;
  45478. /**
  45479. * Number of Simultaneous lights allowed on the material.
  45480. */
  45481. _this.maxSimultaneousLights = 4;
  45482. /**
  45483. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45484. */
  45485. _this.invertNormalMapX = false;
  45486. /**
  45487. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45488. */
  45489. _this.invertNormalMapY = false;
  45490. /**
  45491. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45492. */
  45493. _this.twoSidedLighting = false;
  45494. /**
  45495. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45496. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45497. */
  45498. _this.useAlphaFresnel = false;
  45499. /**
  45500. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45501. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45502. */
  45503. _this.useLinearAlphaFresnel = false;
  45504. /**
  45505. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45506. * And/Or occlude the blended part.
  45507. */
  45508. _this.environmentBRDFTexture = null;
  45509. /**
  45510. * Force normal to face away from face.
  45511. */
  45512. _this.forceNormalForward = false;
  45513. /**
  45514. * Enables specular anti aliasing in the PBR shader.
  45515. * It will both interacts on the Geometry for analytical and IBL lighting.
  45516. * It also prefilter the roughness map based on the bump values.
  45517. */
  45518. _this.enableSpecularAntiAliasing = false;
  45519. /**
  45520. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45521. * makes the reflect vector face the model (under horizon).
  45522. */
  45523. _this.useHorizonOcclusion = true;
  45524. /**
  45525. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45526. * too much the area relying on ambient texture to define their ambient occlusion.
  45527. */
  45528. _this.useRadianceOcclusion = true;
  45529. /**
  45530. * If set to true, no lighting calculations will be applied.
  45531. */
  45532. _this.unlit = false;
  45533. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45534. return _this;
  45535. }
  45536. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  45537. /**
  45538. * BJS is using an harcoded light falloff based on a manually sets up range.
  45539. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45540. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45541. */
  45542. get: function () {
  45543. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45544. },
  45545. /**
  45546. * BJS is using an harcoded light falloff based on a manually sets up range.
  45547. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45548. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45549. */
  45550. set: function (value) {
  45551. if (value !== this.usePhysicalLightFalloff) {
  45552. // Ensure the effect will be rebuilt.
  45553. this._markAllSubMeshesAsTexturesDirty();
  45554. if (value) {
  45555. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45556. }
  45557. else {
  45558. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45559. }
  45560. }
  45561. },
  45562. enumerable: true,
  45563. configurable: true
  45564. });
  45565. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  45566. /**
  45567. * In order to support the falloff compatibility with gltf, a special mode has been added
  45568. * to reproduce the gltf light falloff.
  45569. */
  45570. get: function () {
  45571. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45572. },
  45573. /**
  45574. * In order to support the falloff compatibility with gltf, a special mode has been added
  45575. * to reproduce the gltf light falloff.
  45576. */
  45577. set: function (value) {
  45578. if (value !== this.useGLTFLightFalloff) {
  45579. // Ensure the effect will be rebuilt.
  45580. this._markAllSubMeshesAsTexturesDirty();
  45581. if (value) {
  45582. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  45583. }
  45584. else {
  45585. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  45586. }
  45587. }
  45588. },
  45589. enumerable: true,
  45590. configurable: true
  45591. });
  45592. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45593. /**
  45594. * Gets the image processing configuration used either in this material.
  45595. */
  45596. get: function () {
  45597. return this._imageProcessingConfiguration;
  45598. },
  45599. /**
  45600. * Sets the Default image processing configuration used either in the this material.
  45601. *
  45602. * If sets to null, the scene one is in use.
  45603. */
  45604. set: function (value) {
  45605. this._attachImageProcessingConfiguration(value);
  45606. // Ensure the effect will be rebuilt.
  45607. this._markAllSubMeshesAsTexturesDirty();
  45608. },
  45609. enumerable: true,
  45610. configurable: true
  45611. });
  45612. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45613. /**
  45614. * Gets wether the color curves effect is enabled.
  45615. */
  45616. get: function () {
  45617. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45618. },
  45619. /**
  45620. * Sets wether the color curves effect is enabled.
  45621. */
  45622. set: function (value) {
  45623. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45624. },
  45625. enumerable: true,
  45626. configurable: true
  45627. });
  45628. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45629. /**
  45630. * Gets wether the color grading effect is enabled.
  45631. */
  45632. get: function () {
  45633. return this.imageProcessingConfiguration.colorGradingEnabled;
  45634. },
  45635. /**
  45636. * Gets wether the color grading effect is enabled.
  45637. */
  45638. set: function (value) {
  45639. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45640. },
  45641. enumerable: true,
  45642. configurable: true
  45643. });
  45644. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45645. /**
  45646. * Gets wether tonemapping is enabled or not.
  45647. */
  45648. get: function () {
  45649. return this._imageProcessingConfiguration.toneMappingEnabled;
  45650. },
  45651. /**
  45652. * Sets wether tonemapping is enabled or not
  45653. */
  45654. set: function (value) {
  45655. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45656. },
  45657. enumerable: true,
  45658. configurable: true
  45659. });
  45660. ;
  45661. ;
  45662. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45663. /**
  45664. * The camera exposure used on this material.
  45665. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45666. * This corresponds to a photographic exposure.
  45667. */
  45668. get: function () {
  45669. return this._imageProcessingConfiguration.exposure;
  45670. },
  45671. /**
  45672. * The camera exposure used on this material.
  45673. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45674. * This corresponds to a photographic exposure.
  45675. */
  45676. set: function (value) {
  45677. this._imageProcessingConfiguration.exposure = value;
  45678. },
  45679. enumerable: true,
  45680. configurable: true
  45681. });
  45682. ;
  45683. ;
  45684. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45685. /**
  45686. * Gets The camera contrast used on this material.
  45687. */
  45688. get: function () {
  45689. return this._imageProcessingConfiguration.contrast;
  45690. },
  45691. /**
  45692. * Sets The camera contrast used on this material.
  45693. */
  45694. set: function (value) {
  45695. this._imageProcessingConfiguration.contrast = value;
  45696. },
  45697. enumerable: true,
  45698. configurable: true
  45699. });
  45700. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45701. /**
  45702. * Gets the Color Grading 2D Lookup Texture.
  45703. */
  45704. get: function () {
  45705. return this._imageProcessingConfiguration.colorGradingTexture;
  45706. },
  45707. /**
  45708. * Sets the Color Grading 2D Lookup Texture.
  45709. */
  45710. set: function (value) {
  45711. this._imageProcessingConfiguration.colorGradingTexture = value;
  45712. },
  45713. enumerable: true,
  45714. configurable: true
  45715. });
  45716. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45717. /**
  45718. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45719. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45720. * 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;
  45721. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45722. */
  45723. get: function () {
  45724. return this._imageProcessingConfiguration.colorCurves;
  45725. },
  45726. /**
  45727. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45728. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45729. * 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;
  45730. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45731. */
  45732. set: function (value) {
  45733. this._imageProcessingConfiguration.colorCurves = value;
  45734. },
  45735. enumerable: true,
  45736. configurable: true
  45737. });
  45738. /**
  45739. * Returns the name of this material class.
  45740. */
  45741. PBRMaterial.prototype.getClassName = function () {
  45742. return "PBRMaterial";
  45743. };
  45744. /**
  45745. * Returns an array of the actively used textures.
  45746. * @returns - Array of BaseTextures
  45747. */
  45748. PBRMaterial.prototype.getActiveTextures = function () {
  45749. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45750. if (this._albedoTexture) {
  45751. activeTextures.push(this._albedoTexture);
  45752. }
  45753. if (this._ambientTexture) {
  45754. activeTextures.push(this._ambientTexture);
  45755. }
  45756. if (this._opacityTexture) {
  45757. activeTextures.push(this._opacityTexture);
  45758. }
  45759. if (this._reflectionTexture) {
  45760. activeTextures.push(this._reflectionTexture);
  45761. }
  45762. if (this._emissiveTexture) {
  45763. activeTextures.push(this._emissiveTexture);
  45764. }
  45765. if (this._reflectivityTexture) {
  45766. activeTextures.push(this._reflectivityTexture);
  45767. }
  45768. if (this._metallicTexture) {
  45769. activeTextures.push(this._metallicTexture);
  45770. }
  45771. if (this._microSurfaceTexture) {
  45772. activeTextures.push(this._microSurfaceTexture);
  45773. }
  45774. if (this._bumpTexture) {
  45775. activeTextures.push(this._bumpTexture);
  45776. }
  45777. if (this._lightmapTexture) {
  45778. activeTextures.push(this._lightmapTexture);
  45779. }
  45780. if (this._refractionTexture) {
  45781. activeTextures.push(this._refractionTexture);
  45782. }
  45783. return activeTextures;
  45784. };
  45785. /**
  45786. * Checks to see if a texture is used in the material.
  45787. * @param texture - Base texture to use.
  45788. * @returns - Boolean specifying if a texture is used in the material.
  45789. */
  45790. PBRMaterial.prototype.hasTexture = function (texture) {
  45791. if (_super.prototype.hasTexture.call(this, texture)) {
  45792. return true;
  45793. }
  45794. if (this._albedoTexture === texture) {
  45795. return true;
  45796. }
  45797. if (this._ambientTexture === texture) {
  45798. return true;
  45799. }
  45800. if (this._opacityTexture === texture) {
  45801. return true;
  45802. }
  45803. if (this._reflectionTexture === texture) {
  45804. return true;
  45805. }
  45806. if (this._reflectivityTexture === texture) {
  45807. return true;
  45808. }
  45809. if (this._metallicTexture === texture) {
  45810. return true;
  45811. }
  45812. if (this._microSurfaceTexture === texture) {
  45813. return true;
  45814. }
  45815. if (this._bumpTexture === texture) {
  45816. return true;
  45817. }
  45818. if (this._lightmapTexture === texture) {
  45819. return true;
  45820. }
  45821. if (this._refractionTexture === texture) {
  45822. return true;
  45823. }
  45824. return false;
  45825. };
  45826. /**
  45827. * Makes a duplicate of the current material.
  45828. * @param name - name to use for the new material.
  45829. */
  45830. PBRMaterial.prototype.clone = function (name) {
  45831. var _this = this;
  45832. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45833. clone.id = name;
  45834. clone.name = name;
  45835. return clone;
  45836. };
  45837. /**
  45838. * Serializes this PBR Material.
  45839. * @returns - An object with the serialized material.
  45840. */
  45841. PBRMaterial.prototype.serialize = function () {
  45842. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45843. serializationObject.customType = "BABYLON.PBRMaterial";
  45844. return serializationObject;
  45845. };
  45846. // Statics
  45847. /**
  45848. * Parses a PBR Material from a serialized object.
  45849. * @param source - Serialized object.
  45850. * @param scene - BJS scene instance.
  45851. * @param rootUrl - url for the scene object
  45852. * @returns - PBRMaterial
  45853. */
  45854. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45855. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45856. };
  45857. /**
  45858. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45859. */
  45860. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  45861. /**
  45862. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45863. */
  45864. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  45865. /**
  45866. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45867. */
  45868. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  45869. /**
  45870. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45871. * They are also discarded below the alpha cutoff threshold to improve performances.
  45872. */
  45873. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45874. __decorate([
  45875. BABYLON.serialize(),
  45876. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45877. ], PBRMaterial.prototype, "directIntensity", void 0);
  45878. __decorate([
  45879. BABYLON.serialize(),
  45880. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45881. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45882. __decorate([
  45883. BABYLON.serialize(),
  45884. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45885. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45886. __decorate([
  45887. BABYLON.serialize(),
  45888. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45889. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45890. __decorate([
  45891. BABYLON.serialize(),
  45892. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45893. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45894. __decorate([
  45895. BABYLON.serializeAsTexture(),
  45896. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45897. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45898. __decorate([
  45899. BABYLON.serializeAsTexture(),
  45900. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45901. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45902. __decorate([
  45903. BABYLON.serialize(),
  45904. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45905. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45906. __decorate([
  45907. BABYLON.serializeAsTexture(),
  45908. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45909. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45910. __decorate([
  45911. BABYLON.serializeAsTexture(),
  45912. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45913. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45914. __decorate([
  45915. BABYLON.serializeAsTexture(),
  45916. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45917. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45918. __decorate([
  45919. BABYLON.serializeAsTexture(),
  45920. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45921. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45922. __decorate([
  45923. BABYLON.serializeAsTexture(),
  45924. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45925. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45926. __decorate([
  45927. BABYLON.serialize(),
  45928. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45929. ], PBRMaterial.prototype, "metallic", void 0);
  45930. __decorate([
  45931. BABYLON.serialize(),
  45932. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45933. ], PBRMaterial.prototype, "roughness", void 0);
  45934. __decorate([
  45935. BABYLON.serializeAsTexture(),
  45936. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45937. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45938. __decorate([
  45939. BABYLON.serializeAsTexture(),
  45940. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45941. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45942. __decorate([
  45943. BABYLON.serializeAsTexture(),
  45944. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45945. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45946. __decorate([
  45947. BABYLON.serializeAsTexture(),
  45948. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45949. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45950. __decorate([
  45951. BABYLON.serializeAsColor3("ambient"),
  45952. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45953. ], PBRMaterial.prototype, "ambientColor", void 0);
  45954. __decorate([
  45955. BABYLON.serializeAsColor3("albedo"),
  45956. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45957. ], PBRMaterial.prototype, "albedoColor", void 0);
  45958. __decorate([
  45959. BABYLON.serializeAsColor3("reflectivity"),
  45960. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45961. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45962. __decorate([
  45963. BABYLON.serializeAsColor3("reflection"),
  45964. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45965. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45966. __decorate([
  45967. BABYLON.serializeAsColor3("emissive"),
  45968. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45969. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45970. __decorate([
  45971. BABYLON.serialize(),
  45972. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45973. ], PBRMaterial.prototype, "microSurface", void 0);
  45974. __decorate([
  45975. BABYLON.serialize(),
  45976. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45977. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45978. __decorate([
  45979. BABYLON.serialize(),
  45980. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45981. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45982. __decorate([
  45983. BABYLON.serialize(),
  45984. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45985. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45986. __decorate([
  45987. BABYLON.serialize(),
  45988. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45989. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45990. __decorate([
  45991. BABYLON.serialize(),
  45992. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45993. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45994. __decorate([
  45995. BABYLON.serialize(),
  45996. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45997. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45998. __decorate([
  45999. BABYLON.serialize(),
  46000. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46001. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46002. __decorate([
  46003. BABYLON.serialize(),
  46004. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46005. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46006. __decorate([
  46007. BABYLON.serialize(),
  46008. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46009. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46010. __decorate([
  46011. BABYLON.serialize(),
  46012. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46013. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46014. __decorate([
  46015. BABYLON.serialize(),
  46016. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46017. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46018. __decorate([
  46019. BABYLON.serialize(),
  46020. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46021. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46022. __decorate([
  46023. BABYLON.serialize(),
  46024. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46025. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46026. __decorate([
  46027. BABYLON.serialize(),
  46028. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46029. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46030. __decorate([
  46031. BABYLON.serialize(),
  46032. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46033. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46034. __decorate([
  46035. BABYLON.serialize()
  46036. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  46037. __decorate([
  46038. BABYLON.serialize()
  46039. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  46040. __decorate([
  46041. BABYLON.serialize(),
  46042. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46043. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46044. __decorate([
  46045. BABYLON.serialize(),
  46046. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46047. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46048. __decorate([
  46049. BABYLON.serialize(),
  46050. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46051. ], PBRMaterial.prototype, "useParallax", void 0);
  46052. __decorate([
  46053. BABYLON.serialize(),
  46054. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46055. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46056. __decorate([
  46057. BABYLON.serialize(),
  46058. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46059. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46060. __decorate([
  46061. BABYLON.serialize(),
  46062. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46063. ], PBRMaterial.prototype, "disableLighting", void 0);
  46064. __decorate([
  46065. BABYLON.serialize(),
  46066. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46067. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46068. __decorate([
  46069. BABYLON.serialize(),
  46070. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46071. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46072. __decorate([
  46073. BABYLON.serialize(),
  46074. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46075. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46076. __decorate([
  46077. BABYLON.serialize(),
  46078. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46079. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46080. __decorate([
  46081. BABYLON.serialize(),
  46082. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46083. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46084. __decorate([
  46085. BABYLON.serialize(),
  46086. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46087. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46088. __decorate([
  46089. BABYLON.serialize(),
  46090. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46091. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46092. __decorate([
  46093. BABYLON.serializeAsTexture(),
  46094. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46095. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46096. __decorate([
  46097. BABYLON.serialize(),
  46098. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46099. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46100. __decorate([
  46101. BABYLON.serialize(),
  46102. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46103. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46104. __decorate([
  46105. BABYLON.serialize(),
  46106. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46107. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46108. __decorate([
  46109. BABYLON.serialize(),
  46110. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46111. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46112. __decorate([
  46113. BABYLON.serialize(),
  46114. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  46115. ], PBRMaterial.prototype, "unlit", void 0);
  46116. return PBRMaterial;
  46117. }(BABYLON.PBRBaseMaterial));
  46118. BABYLON.PBRMaterial = PBRMaterial;
  46119. })(BABYLON || (BABYLON = {}));
  46120. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46121. var BABYLON;
  46122. (function (BABYLON) {
  46123. /**
  46124. * The PBR material of BJS following the metal roughness convention.
  46125. *
  46126. * This fits to the PBR convention in the GLTF definition:
  46127. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46128. */
  46129. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46130. __extends(PBRMetallicRoughnessMaterial, _super);
  46131. /**
  46132. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46133. *
  46134. * @param name The material name
  46135. * @param scene The scene the material will be use in.
  46136. */
  46137. function PBRMetallicRoughnessMaterial(name, scene) {
  46138. var _this = _super.call(this, name, scene) || this;
  46139. _this._useRoughnessFromMetallicTextureAlpha = false;
  46140. _this._useRoughnessFromMetallicTextureGreen = true;
  46141. _this._useMetallnessFromMetallicTextureBlue = true;
  46142. _this.metallic = 1.0;
  46143. _this.roughness = 1.0;
  46144. return _this;
  46145. }
  46146. /**
  46147. * Return the currrent class name of the material.
  46148. */
  46149. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46150. return "PBRMetallicRoughnessMaterial";
  46151. };
  46152. /**
  46153. * Return the active textures of the material.
  46154. */
  46155. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46156. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46157. if (this.baseTexture) {
  46158. activeTextures.push(this.baseTexture);
  46159. }
  46160. if (this.metallicRoughnessTexture) {
  46161. activeTextures.push(this.metallicRoughnessTexture);
  46162. }
  46163. return activeTextures;
  46164. };
  46165. /**
  46166. * Checks to see if a texture is used in the material.
  46167. * @param texture - Base texture to use.
  46168. * @returns - Boolean specifying if a texture is used in the material.
  46169. */
  46170. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46171. if (_super.prototype.hasTexture.call(this, texture)) {
  46172. return true;
  46173. }
  46174. if (this.baseTexture === texture) {
  46175. return true;
  46176. }
  46177. if (this.metallicRoughnessTexture === texture) {
  46178. return true;
  46179. }
  46180. return false;
  46181. };
  46182. /**
  46183. * Makes a duplicate of the current material.
  46184. * @param name - name to use for the new material.
  46185. */
  46186. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46187. var _this = this;
  46188. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46189. clone.id = name;
  46190. clone.name = name;
  46191. return clone;
  46192. };
  46193. /**
  46194. * Serialize the material to a parsable JSON object.
  46195. */
  46196. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46197. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46198. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46199. return serializationObject;
  46200. };
  46201. /**
  46202. * Parses a JSON object correponding to the serialize function.
  46203. */
  46204. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46205. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46206. };
  46207. __decorate([
  46208. BABYLON.serializeAsColor3(),
  46209. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46210. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46211. __decorate([
  46212. BABYLON.serializeAsTexture(),
  46213. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46214. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46215. __decorate([
  46216. BABYLON.serialize(),
  46217. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46218. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46219. __decorate([
  46220. BABYLON.serialize(),
  46221. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46222. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46223. __decorate([
  46224. BABYLON.serializeAsTexture(),
  46225. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46226. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46227. return PBRMetallicRoughnessMaterial;
  46228. }(BABYLON.PBRBaseSimpleMaterial));
  46229. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46230. })(BABYLON || (BABYLON = {}));
  46231. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46232. var BABYLON;
  46233. (function (BABYLON) {
  46234. /**
  46235. * The PBR material of BJS following the specular glossiness convention.
  46236. *
  46237. * This fits to the PBR convention in the GLTF definition:
  46238. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46239. */
  46240. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46241. __extends(PBRSpecularGlossinessMaterial, _super);
  46242. /**
  46243. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46244. *
  46245. * @param name The material name
  46246. * @param scene The scene the material will be use in.
  46247. */
  46248. function PBRSpecularGlossinessMaterial(name, scene) {
  46249. var _this = _super.call(this, name, scene) || this;
  46250. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46251. return _this;
  46252. }
  46253. /**
  46254. * Return the currrent class name of the material.
  46255. */
  46256. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46257. return "PBRSpecularGlossinessMaterial";
  46258. };
  46259. /**
  46260. * Return the active textures of the material.
  46261. */
  46262. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46263. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46264. if (this.diffuseTexture) {
  46265. activeTextures.push(this.diffuseTexture);
  46266. }
  46267. if (this.specularGlossinessTexture) {
  46268. activeTextures.push(this.specularGlossinessTexture);
  46269. }
  46270. return activeTextures;
  46271. };
  46272. /**
  46273. * Checks to see if a texture is used in the material.
  46274. * @param texture - Base texture to use.
  46275. * @returns - Boolean specifying if a texture is used in the material.
  46276. */
  46277. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46278. if (_super.prototype.hasTexture.call(this, texture)) {
  46279. return true;
  46280. }
  46281. if (this.diffuseTexture === texture) {
  46282. return true;
  46283. }
  46284. if (this.specularGlossinessTexture === texture) {
  46285. return true;
  46286. }
  46287. return false;
  46288. };
  46289. /**
  46290. * Makes a duplicate of the current material.
  46291. * @param name - name to use for the new material.
  46292. */
  46293. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46294. var _this = this;
  46295. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46296. clone.id = name;
  46297. clone.name = name;
  46298. return clone;
  46299. };
  46300. /**
  46301. * Serialize the material to a parsable JSON object.
  46302. */
  46303. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46304. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46305. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46306. return serializationObject;
  46307. };
  46308. /**
  46309. * Parses a JSON object correponding to the serialize function.
  46310. */
  46311. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46312. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46313. };
  46314. __decorate([
  46315. BABYLON.serializeAsColor3("diffuse"),
  46316. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46317. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46318. __decorate([
  46319. BABYLON.serializeAsTexture(),
  46320. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46321. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46322. __decorate([
  46323. BABYLON.serializeAsColor3("specular"),
  46324. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46325. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46326. __decorate([
  46327. BABYLON.serialize(),
  46328. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46329. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46330. __decorate([
  46331. BABYLON.serializeAsTexture(),
  46332. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46333. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46334. return PBRSpecularGlossinessMaterial;
  46335. }(BABYLON.PBRBaseSimpleMaterial));
  46336. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46337. })(BABYLON || (BABYLON = {}));
  46338. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46339. var BABYLON;
  46340. (function (BABYLON) {
  46341. BABYLON.CameraInputTypes = {};
  46342. var CameraInputsManager = /** @class */ (function () {
  46343. function CameraInputsManager(camera) {
  46344. this.attached = {};
  46345. this.camera = camera;
  46346. this.checkInputs = function () { };
  46347. }
  46348. /**
  46349. * Add an input method to a camera
  46350. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  46351. * @param input camera input method
  46352. */
  46353. CameraInputsManager.prototype.add = function (input) {
  46354. var type = input.getSimpleName();
  46355. if (this.attached[type]) {
  46356. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46357. return;
  46358. }
  46359. this.attached[type] = input;
  46360. input.camera = this.camera;
  46361. //for checkInputs, we are dynamically creating a function
  46362. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46363. if (input.checkInputs) {
  46364. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46365. }
  46366. if (this.attachedElement) {
  46367. input.attachControl(this.attachedElement);
  46368. }
  46369. };
  46370. /**
  46371. * Remove a specific input method from a camera
  46372. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46373. * @param inputToRemove camera input method
  46374. */
  46375. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46376. for (var cam in this.attached) {
  46377. var input = this.attached[cam];
  46378. if (input === inputToRemove) {
  46379. input.detachControl(this.attachedElement);
  46380. input.camera = null;
  46381. delete this.attached[cam];
  46382. this.rebuildInputCheck();
  46383. }
  46384. }
  46385. };
  46386. CameraInputsManager.prototype.removeByType = function (inputType) {
  46387. for (var cam in this.attached) {
  46388. var input = this.attached[cam];
  46389. if (input.getClassName() === inputType) {
  46390. input.detachControl(this.attachedElement);
  46391. input.camera = null;
  46392. delete this.attached[cam];
  46393. this.rebuildInputCheck();
  46394. }
  46395. }
  46396. };
  46397. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46398. var current = this.checkInputs;
  46399. return function () {
  46400. current();
  46401. fn();
  46402. };
  46403. };
  46404. CameraInputsManager.prototype.attachInput = function (input) {
  46405. if (this.attachedElement) {
  46406. input.attachControl(this.attachedElement, this.noPreventDefault);
  46407. }
  46408. };
  46409. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46410. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46411. if (this.attachedElement) {
  46412. return;
  46413. }
  46414. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46415. this.attachedElement = element;
  46416. this.noPreventDefault = noPreventDefault;
  46417. for (var cam in this.attached) {
  46418. this.attached[cam].attachControl(element, noPreventDefault);
  46419. }
  46420. };
  46421. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46422. if (disconnect === void 0) { disconnect = false; }
  46423. if (this.attachedElement !== element) {
  46424. return;
  46425. }
  46426. for (var cam in this.attached) {
  46427. this.attached[cam].detachControl(element);
  46428. if (disconnect) {
  46429. this.attached[cam].camera = null;
  46430. }
  46431. }
  46432. this.attachedElement = null;
  46433. };
  46434. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46435. this.checkInputs = function () { };
  46436. for (var cam in this.attached) {
  46437. var input = this.attached[cam];
  46438. if (input.checkInputs) {
  46439. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46440. }
  46441. }
  46442. };
  46443. /**
  46444. * Remove all attached input methods from a camera
  46445. */
  46446. CameraInputsManager.prototype.clear = function () {
  46447. if (this.attachedElement) {
  46448. this.detachElement(this.attachedElement, true);
  46449. }
  46450. this.attached = {};
  46451. this.attachedElement = null;
  46452. this.checkInputs = function () { };
  46453. };
  46454. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46455. var inputs = {};
  46456. for (var cam in this.attached) {
  46457. var input = this.attached[cam];
  46458. var res = BABYLON.SerializationHelper.Serialize(input);
  46459. inputs[input.getClassName()] = res;
  46460. }
  46461. serializedCamera.inputsmgr = inputs;
  46462. };
  46463. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46464. var parsedInputs = parsedCamera.inputsmgr;
  46465. if (parsedInputs) {
  46466. this.clear();
  46467. for (var n in parsedInputs) {
  46468. var construct = BABYLON.CameraInputTypes[n];
  46469. if (construct) {
  46470. var parsedinput = parsedInputs[n];
  46471. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46472. this.add(input);
  46473. }
  46474. }
  46475. }
  46476. else {
  46477. //2016-03-08 this part is for managing backward compatibility
  46478. for (var n in this.attached) {
  46479. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46480. if (construct) {
  46481. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46482. this.remove(this.attached[n]);
  46483. this.add(input);
  46484. }
  46485. }
  46486. }
  46487. };
  46488. return CameraInputsManager;
  46489. }());
  46490. BABYLON.CameraInputsManager = CameraInputsManager;
  46491. })(BABYLON || (BABYLON = {}));
  46492. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46493. var BABYLON;
  46494. (function (BABYLON) {
  46495. var TargetCamera = /** @class */ (function (_super) {
  46496. __extends(TargetCamera, _super);
  46497. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46498. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46499. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46500. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46501. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46502. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46503. _this.speed = 2.0;
  46504. _this.noRotationConstraint = false;
  46505. _this.lockedTarget = null;
  46506. /** @hidden */
  46507. _this._currentTarget = BABYLON.Vector3.Zero();
  46508. /** @hidden */
  46509. _this._viewMatrix = BABYLON.Matrix.Zero();
  46510. /** @hidden */
  46511. _this._camMatrix = BABYLON.Matrix.Zero();
  46512. /** @hidden */
  46513. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46514. /** @hidden */
  46515. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46516. /** @hidden */
  46517. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46518. /** @hidden */
  46519. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46520. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46521. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46522. return _this;
  46523. }
  46524. TargetCamera.prototype.getFrontPosition = function (distance) {
  46525. this.getWorldMatrix();
  46526. var direction = this.getTarget().subtract(this.position);
  46527. direction.normalize();
  46528. direction.scaleInPlace(distance);
  46529. return this.globalPosition.add(direction);
  46530. };
  46531. /** @hidden */
  46532. TargetCamera.prototype._getLockedTargetPosition = function () {
  46533. if (!this.lockedTarget) {
  46534. return null;
  46535. }
  46536. if (this.lockedTarget.absolutePosition) {
  46537. this.lockedTarget.computeWorldMatrix();
  46538. }
  46539. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46540. };
  46541. TargetCamera.prototype.storeState = function () {
  46542. this._storedPosition = this.position.clone();
  46543. this._storedRotation = this.rotation.clone();
  46544. if (this.rotationQuaternion) {
  46545. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46546. }
  46547. return _super.prototype.storeState.call(this);
  46548. };
  46549. /**
  46550. * Restored camera state. You must call storeState() first
  46551. * @returns whether it was successful or not
  46552. * @hidden
  46553. */
  46554. TargetCamera.prototype._restoreStateValues = function () {
  46555. if (!_super.prototype._restoreStateValues.call(this)) {
  46556. return false;
  46557. }
  46558. this.position = this._storedPosition.clone();
  46559. this.rotation = this._storedRotation.clone();
  46560. if (this.rotationQuaternion) {
  46561. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46562. }
  46563. this.cameraDirection.copyFromFloats(0, 0, 0);
  46564. this.cameraRotation.copyFromFloats(0, 0);
  46565. return true;
  46566. };
  46567. // Cache
  46568. /** @hidden */
  46569. TargetCamera.prototype._initCache = function () {
  46570. _super.prototype._initCache.call(this);
  46571. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46572. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46573. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46574. };
  46575. /** @hidden */
  46576. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46577. if (!ignoreParentClass) {
  46578. _super.prototype._updateCache.call(this);
  46579. }
  46580. var lockedTargetPosition = this._getLockedTargetPosition();
  46581. if (!lockedTargetPosition) {
  46582. this._cache.lockedTarget = null;
  46583. }
  46584. else {
  46585. if (!this._cache.lockedTarget) {
  46586. this._cache.lockedTarget = lockedTargetPosition.clone();
  46587. }
  46588. else {
  46589. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46590. }
  46591. }
  46592. this._cache.rotation.copyFrom(this.rotation);
  46593. if (this.rotationQuaternion)
  46594. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46595. };
  46596. // Synchronized
  46597. /** @hidden */
  46598. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46599. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46600. return false;
  46601. }
  46602. var lockedTargetPosition = this._getLockedTargetPosition();
  46603. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46604. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46605. };
  46606. // Methods
  46607. /** @hidden */
  46608. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46609. var engine = this.getEngine();
  46610. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46611. };
  46612. // Target
  46613. /** @hidden */
  46614. TargetCamera.prototype.setTarget = function (target) {
  46615. this.upVector.normalize();
  46616. if (this.position.z === target.z) {
  46617. this.position.z += BABYLON.Epsilon;
  46618. }
  46619. BABYLON.Matrix.LookAtLHToRef(this.position, target, BABYLON.Vector3.Up(), this._camMatrix);
  46620. this._camMatrix.invert();
  46621. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46622. var vDir = target.subtract(this.position);
  46623. if (vDir.x >= 0.0) {
  46624. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46625. }
  46626. else {
  46627. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46628. }
  46629. this.rotation.z = 0;
  46630. if (isNaN(this.rotation.x)) {
  46631. this.rotation.x = 0;
  46632. }
  46633. if (isNaN(this.rotation.y)) {
  46634. this.rotation.y = 0;
  46635. }
  46636. if (isNaN(this.rotation.z)) {
  46637. this.rotation.z = 0;
  46638. }
  46639. if (this.rotationQuaternion) {
  46640. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46641. }
  46642. };
  46643. /**
  46644. * Return the current target position of the camera. This value is expressed in local space.
  46645. */
  46646. TargetCamera.prototype.getTarget = function () {
  46647. return this._currentTarget;
  46648. };
  46649. /** @hidden */
  46650. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46651. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46652. };
  46653. /** @hidden */
  46654. TargetCamera.prototype._updatePosition = function () {
  46655. if (this.parent) {
  46656. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46657. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46658. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46659. return;
  46660. }
  46661. this.position.addInPlace(this.cameraDirection);
  46662. };
  46663. /** @hidden */
  46664. TargetCamera.prototype._checkInputs = function () {
  46665. var needToMove = this._decideIfNeedsToMove();
  46666. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46667. // Move
  46668. if (needToMove) {
  46669. this._updatePosition();
  46670. }
  46671. // Rotate
  46672. if (needToRotate) {
  46673. this.rotation.x += this.cameraRotation.x;
  46674. this.rotation.y += this.cameraRotation.y;
  46675. //rotate, if quaternion is set and rotation was used
  46676. if (this.rotationQuaternion) {
  46677. var len = this.rotation.lengthSquared();
  46678. if (len) {
  46679. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46680. }
  46681. }
  46682. if (!this.noRotationConstraint) {
  46683. var limit = (Math.PI / 2) * 0.95;
  46684. if (this.rotation.x > limit)
  46685. this.rotation.x = limit;
  46686. if (this.rotation.x < -limit)
  46687. this.rotation.x = -limit;
  46688. }
  46689. }
  46690. // Inertia
  46691. if (needToMove) {
  46692. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46693. this.cameraDirection.x = 0;
  46694. }
  46695. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46696. this.cameraDirection.y = 0;
  46697. }
  46698. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46699. this.cameraDirection.z = 0;
  46700. }
  46701. this.cameraDirection.scaleInPlace(this.inertia);
  46702. }
  46703. if (needToRotate) {
  46704. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46705. this.cameraRotation.x = 0;
  46706. }
  46707. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46708. this.cameraRotation.y = 0;
  46709. }
  46710. this.cameraRotation.scaleInPlace(this.inertia);
  46711. }
  46712. _super.prototype._checkInputs.call(this);
  46713. };
  46714. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46715. if (this.rotationQuaternion) {
  46716. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46717. }
  46718. else {
  46719. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46720. }
  46721. };
  46722. /**
  46723. * Update the up vector to apply the rotation of the camera (So if you changed the camera rotation.z this will let you update the up vector as well)
  46724. * @returns the current camera
  46725. */
  46726. TargetCamera.prototype.rotateUpVectorWithCameraRotationMatrix = function () {
  46727. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this.upVector);
  46728. return this;
  46729. };
  46730. /** @hidden */
  46731. TargetCamera.prototype._getViewMatrix = function () {
  46732. if (this.lockedTarget) {
  46733. this.setTarget(this._getLockedTargetPosition());
  46734. }
  46735. // Compute
  46736. this._updateCameraRotationMatrix();
  46737. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46738. // Computing target and final matrix
  46739. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46740. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  46741. return this._viewMatrix;
  46742. };
  46743. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46744. if (this.parent) {
  46745. var parentWorldMatrix = this.parent.getWorldMatrix();
  46746. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  46747. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46748. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46749. this._markSyncedWithParent();
  46750. }
  46751. else {
  46752. this._globalPosition.copyFrom(position);
  46753. this._globalCurrentTarget.copyFrom(target);
  46754. this._globalCurrentUpVector.copyFrom(up);
  46755. }
  46756. if (this.getScene().useRightHandedSystem) {
  46757. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46758. }
  46759. else {
  46760. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46761. }
  46762. };
  46763. /**
  46764. * @override
  46765. * Override Camera.createRigCamera
  46766. */
  46767. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46768. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46769. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46770. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46771. if (!this.rotationQuaternion) {
  46772. this.rotationQuaternion = new BABYLON.Quaternion();
  46773. }
  46774. rigCamera._cameraRigParams = {};
  46775. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46776. }
  46777. return rigCamera;
  46778. }
  46779. return null;
  46780. };
  46781. /**
  46782. * @hidden
  46783. * @override
  46784. * Override Camera._updateRigCameras
  46785. */
  46786. TargetCamera.prototype._updateRigCameras = function () {
  46787. var camLeft = this._rigCameras[0];
  46788. var camRight = this._rigCameras[1];
  46789. switch (this.cameraRigMode) {
  46790. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46791. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46792. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46793. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46794. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46795. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46796. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46797. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46798. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46799. camLeft.setTarget(this.getTarget());
  46800. camRight.setTarget(this.getTarget());
  46801. break;
  46802. case BABYLON.Camera.RIG_MODE_VR:
  46803. if (camLeft.rotationQuaternion) {
  46804. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46805. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46806. }
  46807. else {
  46808. camLeft.rotation.copyFrom(this.rotation);
  46809. camRight.rotation.copyFrom(this.rotation);
  46810. }
  46811. camLeft.position.copyFrom(this.position);
  46812. camRight.position.copyFrom(this.position);
  46813. break;
  46814. }
  46815. _super.prototype._updateRigCameras.call(this);
  46816. };
  46817. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46818. if (!this._rigCamTransformMatrix) {
  46819. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46820. }
  46821. var target = this.getTarget();
  46822. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46823. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46824. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46825. };
  46826. TargetCamera.prototype.getClassName = function () {
  46827. return "TargetCamera";
  46828. };
  46829. __decorate([
  46830. BABYLON.serializeAsVector3()
  46831. ], TargetCamera.prototype, "rotation", void 0);
  46832. __decorate([
  46833. BABYLON.serialize()
  46834. ], TargetCamera.prototype, "speed", void 0);
  46835. __decorate([
  46836. BABYLON.serializeAsMeshReference("lockedTargetId")
  46837. ], TargetCamera.prototype, "lockedTarget", void 0);
  46838. return TargetCamera;
  46839. }(BABYLON.Camera));
  46840. BABYLON.TargetCamera = TargetCamera;
  46841. })(BABYLON || (BABYLON = {}));
  46842. //# sourceMappingURL=babylon.targetCamera.js.map
  46843. var BABYLON;
  46844. (function (BABYLON) {
  46845. var FreeCameraMouseInput = /** @class */ (function () {
  46846. function FreeCameraMouseInput(touchEnabled) {
  46847. if (touchEnabled === void 0) { touchEnabled = true; }
  46848. this.touchEnabled = touchEnabled;
  46849. this.buttons = [0, 1, 2];
  46850. this.angularSensibility = 2000.0;
  46851. this.previousPosition = null;
  46852. }
  46853. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46854. var _this = this;
  46855. var engine = this.camera.getEngine();
  46856. if (!this._pointerInput) {
  46857. this._pointerInput = function (p, s) {
  46858. var evt = p.event;
  46859. if (engine.isInVRExclusivePointerMode) {
  46860. return;
  46861. }
  46862. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46863. return;
  46864. }
  46865. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46866. return;
  46867. }
  46868. var srcElement = (evt.srcElement || evt.target);
  46869. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46870. try {
  46871. srcElement.setPointerCapture(evt.pointerId);
  46872. }
  46873. catch (e) {
  46874. //Nothing to do with the error. Execution will continue.
  46875. }
  46876. _this.previousPosition = {
  46877. x: evt.clientX,
  46878. y: evt.clientY
  46879. };
  46880. if (!noPreventDefault) {
  46881. evt.preventDefault();
  46882. element.focus();
  46883. }
  46884. }
  46885. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46886. try {
  46887. srcElement.releasePointerCapture(evt.pointerId);
  46888. }
  46889. catch (e) {
  46890. //Nothing to do with the error.
  46891. }
  46892. _this.previousPosition = null;
  46893. if (!noPreventDefault) {
  46894. evt.preventDefault();
  46895. }
  46896. }
  46897. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46898. if (!_this.previousPosition || engine.isPointerLock) {
  46899. return;
  46900. }
  46901. var offsetX = evt.clientX - _this.previousPosition.x;
  46902. if (_this.camera.getScene().useRightHandedSystem)
  46903. offsetX *= -1;
  46904. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46905. offsetX *= -1;
  46906. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46907. var offsetY = evt.clientY - _this.previousPosition.y;
  46908. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46909. _this.previousPosition = {
  46910. x: evt.clientX,
  46911. y: evt.clientY
  46912. };
  46913. if (!noPreventDefault) {
  46914. evt.preventDefault();
  46915. }
  46916. }
  46917. };
  46918. }
  46919. this._onMouseMove = function (evt) {
  46920. if (!engine.isPointerLock) {
  46921. return;
  46922. }
  46923. if (engine.isInVRExclusivePointerMode) {
  46924. return;
  46925. }
  46926. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46927. if (_this.camera.getScene().useRightHandedSystem)
  46928. offsetX *= -1;
  46929. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46930. offsetX *= -1;
  46931. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46932. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46933. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46934. _this.previousPosition = null;
  46935. if (!noPreventDefault) {
  46936. evt.preventDefault();
  46937. }
  46938. };
  46939. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46940. element.addEventListener("mousemove", this._onMouseMove, false);
  46941. };
  46942. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46943. if (this._observer && element) {
  46944. this.camera.getScene().onPointerObservable.remove(this._observer);
  46945. if (this._onMouseMove) {
  46946. element.removeEventListener("mousemove", this._onMouseMove);
  46947. }
  46948. this._observer = null;
  46949. this._onMouseMove = null;
  46950. this.previousPosition = null;
  46951. }
  46952. };
  46953. FreeCameraMouseInput.prototype.getClassName = function () {
  46954. return "FreeCameraMouseInput";
  46955. };
  46956. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46957. return "mouse";
  46958. };
  46959. __decorate([
  46960. BABYLON.serialize()
  46961. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46962. __decorate([
  46963. BABYLON.serialize()
  46964. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46965. return FreeCameraMouseInput;
  46966. }());
  46967. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46968. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46969. })(BABYLON || (BABYLON = {}));
  46970. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46971. var BABYLON;
  46972. (function (BABYLON) {
  46973. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46974. function FreeCameraKeyboardMoveInput() {
  46975. this._keys = new Array();
  46976. this.keysUp = [38];
  46977. this.keysDown = [40];
  46978. this.keysLeft = [37];
  46979. this.keysRight = [39];
  46980. }
  46981. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46982. var _this = this;
  46983. if (this._onCanvasBlurObserver) {
  46984. return;
  46985. }
  46986. this._scene = this.camera.getScene();
  46987. this._engine = this._scene.getEngine();
  46988. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46989. _this._keys = [];
  46990. });
  46991. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46992. var evt = info.event;
  46993. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46994. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46995. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46996. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46997. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46998. var index = _this._keys.indexOf(evt.keyCode);
  46999. if (index === -1) {
  47000. _this._keys.push(evt.keyCode);
  47001. }
  47002. if (!noPreventDefault) {
  47003. evt.preventDefault();
  47004. }
  47005. }
  47006. }
  47007. else {
  47008. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47009. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47010. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47011. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47012. var index = _this._keys.indexOf(evt.keyCode);
  47013. if (index >= 0) {
  47014. _this._keys.splice(index, 1);
  47015. }
  47016. if (!noPreventDefault) {
  47017. evt.preventDefault();
  47018. }
  47019. }
  47020. }
  47021. });
  47022. };
  47023. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47024. if (this._scene) {
  47025. if (this._onKeyboardObserver) {
  47026. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47027. }
  47028. if (this._onCanvasBlurObserver) {
  47029. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47030. }
  47031. this._onKeyboardObserver = null;
  47032. this._onCanvasBlurObserver = null;
  47033. }
  47034. this._keys = [];
  47035. };
  47036. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47037. if (this._onKeyboardObserver) {
  47038. var camera = this.camera;
  47039. // Keyboard
  47040. for (var index = 0; index < this._keys.length; index++) {
  47041. var keyCode = this._keys[index];
  47042. var speed = camera._computeLocalCameraSpeed();
  47043. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47044. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47045. }
  47046. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47047. camera._localDirection.copyFromFloats(0, 0, speed);
  47048. }
  47049. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47050. camera._localDirection.copyFromFloats(speed, 0, 0);
  47051. }
  47052. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47053. camera._localDirection.copyFromFloats(0, 0, -speed);
  47054. }
  47055. if (camera.getScene().useRightHandedSystem) {
  47056. camera._localDirection.z *= -1;
  47057. }
  47058. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47059. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47060. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47061. }
  47062. }
  47063. };
  47064. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47065. return "FreeCameraKeyboardMoveInput";
  47066. };
  47067. /** @hidden */
  47068. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47069. this._keys = [];
  47070. };
  47071. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47072. return "keyboard";
  47073. };
  47074. __decorate([
  47075. BABYLON.serialize()
  47076. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47077. __decorate([
  47078. BABYLON.serialize()
  47079. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47080. __decorate([
  47081. BABYLON.serialize()
  47082. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47083. __decorate([
  47084. BABYLON.serialize()
  47085. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47086. return FreeCameraKeyboardMoveInput;
  47087. }());
  47088. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47089. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47090. })(BABYLON || (BABYLON = {}));
  47091. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47092. var BABYLON;
  47093. (function (BABYLON) {
  47094. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47095. __extends(FreeCameraInputsManager, _super);
  47096. function FreeCameraInputsManager(camera) {
  47097. return _super.call(this, camera) || this;
  47098. }
  47099. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47100. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47101. return this;
  47102. };
  47103. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47104. if (touchEnabled === void 0) { touchEnabled = true; }
  47105. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47106. return this;
  47107. };
  47108. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47109. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47110. return this;
  47111. };
  47112. FreeCameraInputsManager.prototype.addTouch = function () {
  47113. this.add(new BABYLON.FreeCameraTouchInput());
  47114. return this;
  47115. };
  47116. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47117. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47118. return this;
  47119. };
  47120. return FreeCameraInputsManager;
  47121. }(BABYLON.CameraInputsManager));
  47122. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47123. })(BABYLON || (BABYLON = {}));
  47124. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47125. var BABYLON;
  47126. (function (BABYLON) {
  47127. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  47128. // Forcing to use the Universal camera
  47129. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  47130. });
  47131. var FreeCamera = /** @class */ (function (_super) {
  47132. __extends(FreeCamera, _super);
  47133. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47134. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47135. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47136. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47137. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47138. _this.checkCollisions = false;
  47139. _this.applyGravity = false;
  47140. _this._needMoveForGravity = false;
  47141. _this._oldPosition = BABYLON.Vector3.Zero();
  47142. _this._diffPosition = BABYLON.Vector3.Zero();
  47143. _this._newPosition = BABYLON.Vector3.Zero();
  47144. // Collisions
  47145. _this._collisionMask = -1;
  47146. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47147. if (collidedMesh === void 0) { collidedMesh = null; }
  47148. //TODO move this to the collision coordinator!
  47149. if (_this.getScene().workerCollisions)
  47150. newPosition.multiplyInPlace(_this._collider._radius);
  47151. var updatePosition = function (newPos) {
  47152. _this._newPosition.copyFrom(newPos);
  47153. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47154. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47155. _this.position.addInPlace(_this._diffPosition);
  47156. if (_this.onCollide && collidedMesh) {
  47157. _this.onCollide(collidedMesh);
  47158. }
  47159. }
  47160. };
  47161. updatePosition(newPosition);
  47162. };
  47163. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47164. _this.inputs.addKeyboard().addMouse();
  47165. return _this;
  47166. }
  47167. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47168. //-- begin properties for backward compatibility for inputs
  47169. /**
  47170. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47171. * Higher values reduce sensitivity.
  47172. */
  47173. get: function () {
  47174. var mouse = this.inputs.attached["mouse"];
  47175. if (mouse)
  47176. return mouse.angularSensibility;
  47177. return 0;
  47178. },
  47179. /**
  47180. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47181. * Higher values reduce sensitivity.
  47182. */
  47183. set: function (value) {
  47184. var mouse = this.inputs.attached["mouse"];
  47185. if (mouse)
  47186. mouse.angularSensibility = value;
  47187. },
  47188. enumerable: true,
  47189. configurable: true
  47190. });
  47191. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47192. get: function () {
  47193. var keyboard = this.inputs.attached["keyboard"];
  47194. if (keyboard)
  47195. return keyboard.keysUp;
  47196. return [];
  47197. },
  47198. set: function (value) {
  47199. var keyboard = this.inputs.attached["keyboard"];
  47200. if (keyboard)
  47201. keyboard.keysUp = value;
  47202. },
  47203. enumerable: true,
  47204. configurable: true
  47205. });
  47206. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47207. get: function () {
  47208. var keyboard = this.inputs.attached["keyboard"];
  47209. if (keyboard)
  47210. return keyboard.keysDown;
  47211. return [];
  47212. },
  47213. set: function (value) {
  47214. var keyboard = this.inputs.attached["keyboard"];
  47215. if (keyboard)
  47216. keyboard.keysDown = value;
  47217. },
  47218. enumerable: true,
  47219. configurable: true
  47220. });
  47221. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47222. get: function () {
  47223. var keyboard = this.inputs.attached["keyboard"];
  47224. if (keyboard)
  47225. return keyboard.keysLeft;
  47226. return [];
  47227. },
  47228. set: function (value) {
  47229. var keyboard = this.inputs.attached["keyboard"];
  47230. if (keyboard)
  47231. keyboard.keysLeft = value;
  47232. },
  47233. enumerable: true,
  47234. configurable: true
  47235. });
  47236. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47237. get: function () {
  47238. var keyboard = this.inputs.attached["keyboard"];
  47239. if (keyboard)
  47240. return keyboard.keysRight;
  47241. return [];
  47242. },
  47243. set: function (value) {
  47244. var keyboard = this.inputs.attached["keyboard"];
  47245. if (keyboard)
  47246. keyboard.keysRight = value;
  47247. },
  47248. enumerable: true,
  47249. configurable: true
  47250. });
  47251. // Controls
  47252. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47253. this.inputs.attachElement(element, noPreventDefault);
  47254. };
  47255. FreeCamera.prototype.detachControl = function (element) {
  47256. this.inputs.detachElement(element);
  47257. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47258. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47259. };
  47260. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47261. get: function () {
  47262. return this._collisionMask;
  47263. },
  47264. set: function (mask) {
  47265. this._collisionMask = !isNaN(mask) ? mask : -1;
  47266. },
  47267. enumerable: true,
  47268. configurable: true
  47269. });
  47270. /** @hidden */
  47271. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47272. var globalPosition;
  47273. if (this.parent) {
  47274. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47275. }
  47276. else {
  47277. globalPosition = this.position;
  47278. }
  47279. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47280. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47281. if (!this._collider) {
  47282. this._collider = new BABYLON.Collider();
  47283. }
  47284. this._collider._radius = this.ellipsoid;
  47285. this._collider.collisionMask = this._collisionMask;
  47286. //no need for clone, as long as gravity is not on.
  47287. var actualDisplacement = displacement;
  47288. //add gravity to the direction to prevent the dual-collision checking
  47289. if (this.applyGravity) {
  47290. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47291. actualDisplacement = displacement.add(this.getScene().gravity);
  47292. }
  47293. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47294. };
  47295. /** @hidden */
  47296. FreeCamera.prototype._checkInputs = function () {
  47297. if (!this._localDirection) {
  47298. this._localDirection = BABYLON.Vector3.Zero();
  47299. this._transformedDirection = BABYLON.Vector3.Zero();
  47300. }
  47301. this.inputs.checkInputs();
  47302. _super.prototype._checkInputs.call(this);
  47303. };
  47304. /** @hidden */
  47305. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47306. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47307. };
  47308. /** @hidden */
  47309. FreeCamera.prototype._updatePosition = function () {
  47310. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47311. this._collideWithWorld(this.cameraDirection);
  47312. }
  47313. else {
  47314. _super.prototype._updatePosition.call(this);
  47315. }
  47316. };
  47317. FreeCamera.prototype.dispose = function () {
  47318. this.inputs.clear();
  47319. _super.prototype.dispose.call(this);
  47320. };
  47321. FreeCamera.prototype.getClassName = function () {
  47322. return "FreeCamera";
  47323. };
  47324. __decorate([
  47325. BABYLON.serializeAsVector3()
  47326. ], FreeCamera.prototype, "ellipsoid", void 0);
  47327. __decorate([
  47328. BABYLON.serializeAsVector3()
  47329. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47330. __decorate([
  47331. BABYLON.serialize()
  47332. ], FreeCamera.prototype, "checkCollisions", void 0);
  47333. __decorate([
  47334. BABYLON.serialize()
  47335. ], FreeCamera.prototype, "applyGravity", void 0);
  47336. return FreeCamera;
  47337. }(BABYLON.TargetCamera));
  47338. BABYLON.FreeCamera = FreeCamera;
  47339. })(BABYLON || (BABYLON = {}));
  47340. //# sourceMappingURL=babylon.freeCamera.js.map
  47341. var BABYLON;
  47342. (function (BABYLON) {
  47343. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47344. function ArcRotateCameraKeyboardMoveInput() {
  47345. this._keys = new Array();
  47346. this.keysUp = [38];
  47347. this.keysDown = [40];
  47348. this.keysLeft = [37];
  47349. this.keysRight = [39];
  47350. this.keysReset = [220];
  47351. this.panningSensibility = 50.0;
  47352. this.zoomingSensibility = 25.0;
  47353. this.useAltToZoom = true;
  47354. }
  47355. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47356. var _this = this;
  47357. if (this._onCanvasBlurObserver) {
  47358. return;
  47359. }
  47360. this._scene = this.camera.getScene();
  47361. this._engine = this._scene.getEngine();
  47362. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47363. _this._keys = [];
  47364. });
  47365. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47366. var evt = info.event;
  47367. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47368. _this._ctrlPressed = evt.ctrlKey;
  47369. _this._altPressed = evt.altKey;
  47370. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47371. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47372. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47373. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47374. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47375. var index = _this._keys.indexOf(evt.keyCode);
  47376. if (index === -1) {
  47377. _this._keys.push(evt.keyCode);
  47378. }
  47379. if (evt.preventDefault) {
  47380. if (!noPreventDefault) {
  47381. evt.preventDefault();
  47382. }
  47383. }
  47384. }
  47385. }
  47386. else {
  47387. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47388. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47389. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47390. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47391. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47392. var index = _this._keys.indexOf(evt.keyCode);
  47393. if (index >= 0) {
  47394. _this._keys.splice(index, 1);
  47395. }
  47396. if (evt.preventDefault) {
  47397. if (!noPreventDefault) {
  47398. evt.preventDefault();
  47399. }
  47400. }
  47401. }
  47402. }
  47403. });
  47404. };
  47405. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47406. if (this._scene) {
  47407. if (this._onKeyboardObserver) {
  47408. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47409. }
  47410. if (this._onCanvasBlurObserver) {
  47411. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47412. }
  47413. this._onKeyboardObserver = null;
  47414. this._onCanvasBlurObserver = null;
  47415. }
  47416. this._keys = [];
  47417. };
  47418. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47419. if (this._onKeyboardObserver) {
  47420. var camera = this.camera;
  47421. for (var index = 0; index < this._keys.length; index++) {
  47422. var keyCode = this._keys[index];
  47423. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47424. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47425. camera.inertialPanningX -= 1 / this.panningSensibility;
  47426. }
  47427. else {
  47428. camera.inertialAlphaOffset -= 0.01;
  47429. }
  47430. }
  47431. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47432. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47433. camera.inertialPanningY += 1 / this.panningSensibility;
  47434. }
  47435. else if (this._altPressed && this.useAltToZoom) {
  47436. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47437. }
  47438. else {
  47439. camera.inertialBetaOffset -= 0.01;
  47440. }
  47441. }
  47442. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47443. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47444. camera.inertialPanningX += 1 / this.panningSensibility;
  47445. }
  47446. else {
  47447. camera.inertialAlphaOffset += 0.01;
  47448. }
  47449. }
  47450. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47451. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47452. camera.inertialPanningY -= 1 / this.panningSensibility;
  47453. }
  47454. else if (this._altPressed && this.useAltToZoom) {
  47455. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47456. }
  47457. else {
  47458. camera.inertialBetaOffset += 0.01;
  47459. }
  47460. }
  47461. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47462. camera.restoreState();
  47463. }
  47464. }
  47465. }
  47466. };
  47467. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47468. return "ArcRotateCameraKeyboardMoveInput";
  47469. };
  47470. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47471. return "keyboard";
  47472. };
  47473. __decorate([
  47474. BABYLON.serialize()
  47475. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47476. __decorate([
  47477. BABYLON.serialize()
  47478. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47479. __decorate([
  47480. BABYLON.serialize()
  47481. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47482. __decorate([
  47483. BABYLON.serialize()
  47484. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47485. __decorate([
  47486. BABYLON.serialize()
  47487. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47488. __decorate([
  47489. BABYLON.serialize()
  47490. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47491. __decorate([
  47492. BABYLON.serialize()
  47493. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47494. __decorate([
  47495. BABYLON.serialize()
  47496. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47497. return ArcRotateCameraKeyboardMoveInput;
  47498. }());
  47499. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47500. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47501. })(BABYLON || (BABYLON = {}));
  47502. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47503. var BABYLON;
  47504. (function (BABYLON) {
  47505. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47506. function ArcRotateCameraMouseWheelInput() {
  47507. this.wheelPrecision = 3.0;
  47508. /**
  47509. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47510. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47511. */
  47512. this.wheelDeltaPercentage = 0;
  47513. }
  47514. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47515. var _this = this;
  47516. this._wheel = function (p, s) {
  47517. //sanity check - this should be a PointerWheel event.
  47518. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47519. return;
  47520. var event = p.event;
  47521. var delta = 0;
  47522. if (event.wheelDelta) {
  47523. if (_this.wheelDeltaPercentage) {
  47524. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47525. if (event.wheelDelta > 0) {
  47526. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47527. }
  47528. else {
  47529. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47530. }
  47531. }
  47532. else {
  47533. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47534. }
  47535. }
  47536. else if (event.detail) {
  47537. delta = -event.detail / _this.wheelPrecision;
  47538. }
  47539. if (delta)
  47540. _this.camera.inertialRadiusOffset += delta;
  47541. if (event.preventDefault) {
  47542. if (!noPreventDefault) {
  47543. event.preventDefault();
  47544. }
  47545. }
  47546. };
  47547. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47548. };
  47549. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47550. if (this._observer && element) {
  47551. this.camera.getScene().onPointerObservable.remove(this._observer);
  47552. this._observer = null;
  47553. this._wheel = null;
  47554. }
  47555. };
  47556. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47557. return "ArcRotateCameraMouseWheelInput";
  47558. };
  47559. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47560. return "mousewheel";
  47561. };
  47562. __decorate([
  47563. BABYLON.serialize()
  47564. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47565. __decorate([
  47566. BABYLON.serialize()
  47567. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47568. return ArcRotateCameraMouseWheelInput;
  47569. }());
  47570. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47571. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47572. })(BABYLON || (BABYLON = {}));
  47573. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47574. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\npointLightingInfo pointInfo;\nspotLightingInfo spotInfo;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction.rgb*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration>\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*vec4(viewPos,1.0);\n#endif\n#include<clipPlaneVertex>\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#include<clipPlaneFragmentDeclaration>\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec4 baseColor=texture2D(diffuseSampler,vUV);\nbaseColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\nbaseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\nin float angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration2>\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*viewPosition;\n#endif \n#include<clipPlaneVertex>\n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#include<clipPlaneFragmentDeclaration2> \n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main() {\n#include<clipPlaneFragment> \noutFragColor=texture(textureSampler,vUV)*vColor;\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\noutFragColor=applyImageProcessing(outFragColor);\n#endif\n#endif\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#endif\n#ifdef HEMISPHERICEMITTER\nuniform float radius;\nuniform float radiusRange;\nuniform float directionRandomizer;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\nuniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=vec4(0.,0.,0.,0.);\n#endif\noutSize=vec3(0.,0.,0.);\n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif \noutDirection=direction;\noutAngle=angle;\n#ifdef ANIMATESHEET \noutCellIndex=cellIndex;\n#endif\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n\n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=vec3(0,0,0);\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(HEMISPHERICEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);\ndirection=position+directionRandomizer*randoms3; \n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.00001;\n#else\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\nvec3 initial=(emitterWM*vec4(normalize(direction),0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#endif\n} else { \nfloat directionScale=timeDelta;\nfloat ageGradient=age/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\noutDirection=direction+gravity*timeDelta;\n#ifdef NOISE\nvec3 localPosition=outPosition-emitterWM[3].xyz;\nfloat fetchedR=texture(noiseSampler,vec2(localPosition.y,localPosition.z)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(localPosition.x+0.33,localPosition.z+0.33)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(localPosition.z-0.33,localPosition.y-0.33)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat dist=cellInfos.y-cellInfos.x;\nfloat ratio=clamp(mod(outAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","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"};
  47575. var BABYLON;
  47576. (function (BABYLON) {
  47577. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47578. function ArcRotateCameraPointersInput() {
  47579. this.buttons = [0, 1, 2];
  47580. this.angularSensibilityX = 1000.0;
  47581. this.angularSensibilityY = 1000.0;
  47582. this.pinchPrecision = 12.0;
  47583. /**
  47584. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47585. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47586. */
  47587. this.pinchDeltaPercentage = 0;
  47588. this.panningSensibility = 1000.0;
  47589. this.multiTouchPanning = true;
  47590. this.multiTouchPanAndZoom = true;
  47591. this._isPanClick = false;
  47592. this.pinchInwards = true;
  47593. }
  47594. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47595. var _this = this;
  47596. var engine = this.camera.getEngine();
  47597. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47598. var pointA = null;
  47599. var pointB = null;
  47600. var previousPinchSquaredDistance = 0;
  47601. var initialDistance = 0;
  47602. var twoFingerActivityCount = 0;
  47603. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47604. this._pointerInput = function (p, s) {
  47605. var evt = p.event;
  47606. var isTouch = p.event.pointerType === "touch";
  47607. if (engine.isInVRExclusivePointerMode) {
  47608. return;
  47609. }
  47610. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47611. return;
  47612. }
  47613. var srcElement = (evt.srcElement || evt.target);
  47614. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47615. try {
  47616. srcElement.setPointerCapture(evt.pointerId);
  47617. }
  47618. catch (e) {
  47619. //Nothing to do with the error. Execution will continue.
  47620. }
  47621. // Manage panning with pan button click
  47622. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47623. // manage pointers
  47624. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47625. if (pointA === null) {
  47626. pointA = cacheSoloPointer;
  47627. }
  47628. else if (pointB === null) {
  47629. pointB = cacheSoloPointer;
  47630. }
  47631. if (!noPreventDefault) {
  47632. evt.preventDefault();
  47633. element.focus();
  47634. }
  47635. }
  47636. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47637. _this.camera.restoreState();
  47638. }
  47639. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47640. try {
  47641. srcElement.releasePointerCapture(evt.pointerId);
  47642. }
  47643. catch (e) {
  47644. //Nothing to do with the error.
  47645. }
  47646. cacheSoloPointer = null;
  47647. previousPinchSquaredDistance = 0;
  47648. previousMultiTouchPanPosition.isPaning = false;
  47649. previousMultiTouchPanPosition.isPinching = false;
  47650. twoFingerActivityCount = 0;
  47651. initialDistance = 0;
  47652. if (!isTouch) {
  47653. pointB = null; // Mouse and pen are mono pointer
  47654. }
  47655. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47656. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47657. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47658. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47659. if (engine._badOS) {
  47660. pointA = pointB = null;
  47661. }
  47662. else {
  47663. //only remove the impacted pointer in case of multitouch allowing on most
  47664. //platforms switching from rotate to zoom and pan seamlessly.
  47665. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47666. pointA = pointB;
  47667. pointB = null;
  47668. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47669. }
  47670. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47671. pointB = null;
  47672. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47673. }
  47674. else {
  47675. pointA = pointB = null;
  47676. }
  47677. }
  47678. if (!noPreventDefault) {
  47679. evt.preventDefault();
  47680. }
  47681. }
  47682. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47683. if (!noPreventDefault) {
  47684. evt.preventDefault();
  47685. }
  47686. // One button down
  47687. if (pointA && pointB === null && cacheSoloPointer) {
  47688. if (_this.panningSensibility !== 0 &&
  47689. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47690. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47691. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47692. }
  47693. else {
  47694. var offsetX = evt.clientX - cacheSoloPointer.x;
  47695. var offsetY = evt.clientY - cacheSoloPointer.y;
  47696. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47697. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47698. }
  47699. cacheSoloPointer.x = evt.clientX;
  47700. cacheSoloPointer.y = evt.clientY;
  47701. }
  47702. // Two buttons down: pinch/pan
  47703. else if (pointA && pointB) {
  47704. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47705. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47706. ed.x = evt.clientX;
  47707. ed.y = evt.clientY;
  47708. var direction = _this.pinchInwards ? 1 : -1;
  47709. var distX = pointA.x - pointB.x;
  47710. var distY = pointA.y - pointB.y;
  47711. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47712. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47713. if (previousPinchSquaredDistance === 0) {
  47714. initialDistance = pinchDistance;
  47715. previousPinchSquaredDistance = pinchSquaredDistance;
  47716. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47717. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47718. return;
  47719. }
  47720. if (_this.multiTouchPanAndZoom) {
  47721. if (_this.pinchDeltaPercentage) {
  47722. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47723. }
  47724. else {
  47725. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47726. (_this.pinchPrecision *
  47727. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47728. direction);
  47729. }
  47730. if (_this.panningSensibility !== 0) {
  47731. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47732. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47733. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47734. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47735. previousMultiTouchPanPosition.x = pointersCenterX;
  47736. previousMultiTouchPanPosition.y = pointersCenterY;
  47737. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47738. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47739. }
  47740. }
  47741. else {
  47742. twoFingerActivityCount++;
  47743. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47744. if (_this.pinchDeltaPercentage) {
  47745. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47746. }
  47747. else {
  47748. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47749. (_this.pinchPrecision *
  47750. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47751. direction);
  47752. }
  47753. previousMultiTouchPanPosition.isPaning = false;
  47754. previousMultiTouchPanPosition.isPinching = true;
  47755. }
  47756. else {
  47757. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47758. if (!previousMultiTouchPanPosition.isPaning) {
  47759. previousMultiTouchPanPosition.isPaning = true;
  47760. previousMultiTouchPanPosition.isPinching = false;
  47761. previousMultiTouchPanPosition.x = ed.x;
  47762. previousMultiTouchPanPosition.y = ed.y;
  47763. return;
  47764. }
  47765. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47766. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47767. }
  47768. }
  47769. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47770. previousMultiTouchPanPosition.x = ed.x;
  47771. previousMultiTouchPanPosition.y = ed.y;
  47772. }
  47773. }
  47774. previousPinchSquaredDistance = pinchSquaredDistance;
  47775. }
  47776. }
  47777. };
  47778. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47779. this._onContextMenu = function (evt) {
  47780. evt.preventDefault();
  47781. };
  47782. if (!this.camera._useCtrlForPanning) {
  47783. element.addEventListener("contextmenu", this._onContextMenu, false);
  47784. }
  47785. this._onLostFocus = function () {
  47786. //this._keys = [];
  47787. pointA = pointB = null;
  47788. previousPinchSquaredDistance = 0;
  47789. previousMultiTouchPanPosition.isPaning = false;
  47790. previousMultiTouchPanPosition.isPinching = false;
  47791. twoFingerActivityCount = 0;
  47792. cacheSoloPointer = null;
  47793. initialDistance = 0;
  47794. };
  47795. this._onMouseMove = function (evt) {
  47796. if (!engine.isPointerLock) {
  47797. return;
  47798. }
  47799. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47800. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47801. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47802. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47803. if (!noPreventDefault) {
  47804. evt.preventDefault();
  47805. }
  47806. };
  47807. this._onGestureStart = function (e) {
  47808. if (window.MSGesture === undefined) {
  47809. return;
  47810. }
  47811. if (!_this._MSGestureHandler) {
  47812. _this._MSGestureHandler = new MSGesture();
  47813. _this._MSGestureHandler.target = element;
  47814. }
  47815. _this._MSGestureHandler.addPointer(e.pointerId);
  47816. };
  47817. this._onGesture = function (e) {
  47818. _this.camera.radius *= e.scale;
  47819. if (e.preventDefault) {
  47820. if (!noPreventDefault) {
  47821. e.stopPropagation();
  47822. e.preventDefault();
  47823. }
  47824. }
  47825. };
  47826. element.addEventListener("mousemove", this._onMouseMove, false);
  47827. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47828. element.addEventListener("MSGestureChange", this._onGesture, false);
  47829. BABYLON.Tools.RegisterTopRootEvents([
  47830. { name: "blur", handler: this._onLostFocus }
  47831. ]);
  47832. };
  47833. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47834. if (this._onLostFocus) {
  47835. BABYLON.Tools.UnregisterTopRootEvents([
  47836. { name: "blur", handler: this._onLostFocus }
  47837. ]);
  47838. }
  47839. if (element && this._observer) {
  47840. this.camera.getScene().onPointerObservable.remove(this._observer);
  47841. this._observer = null;
  47842. if (this._onContextMenu) {
  47843. element.removeEventListener("contextmenu", this._onContextMenu);
  47844. }
  47845. if (this._onMouseMove) {
  47846. element.removeEventListener("mousemove", this._onMouseMove);
  47847. }
  47848. if (this._onGestureStart) {
  47849. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47850. }
  47851. if (this._onGesture) {
  47852. element.removeEventListener("MSGestureChange", this._onGesture);
  47853. }
  47854. this._isPanClick = false;
  47855. this.pinchInwards = true;
  47856. this._onMouseMove = null;
  47857. this._onGestureStart = null;
  47858. this._onGesture = null;
  47859. this._MSGestureHandler = null;
  47860. this._onLostFocus = null;
  47861. this._onContextMenu = null;
  47862. }
  47863. };
  47864. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47865. return "ArcRotateCameraPointersInput";
  47866. };
  47867. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47868. return "pointers";
  47869. };
  47870. __decorate([
  47871. BABYLON.serialize()
  47872. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47873. __decorate([
  47874. BABYLON.serialize()
  47875. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47876. __decorate([
  47877. BABYLON.serialize()
  47878. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47879. __decorate([
  47880. BABYLON.serialize()
  47881. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47882. __decorate([
  47883. BABYLON.serialize()
  47884. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47885. __decorate([
  47886. BABYLON.serialize()
  47887. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47888. __decorate([
  47889. BABYLON.serialize()
  47890. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47891. __decorate([
  47892. BABYLON.serialize()
  47893. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47894. return ArcRotateCameraPointersInput;
  47895. }());
  47896. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47897. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47898. })(BABYLON || (BABYLON = {}));
  47899. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47900. var BABYLON;
  47901. (function (BABYLON) {
  47902. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47903. __extends(ArcRotateCameraInputsManager, _super);
  47904. function ArcRotateCameraInputsManager(camera) {
  47905. return _super.call(this, camera) || this;
  47906. }
  47907. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47908. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47909. return this;
  47910. };
  47911. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47912. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47913. return this;
  47914. };
  47915. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47916. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47917. return this;
  47918. };
  47919. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47920. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47921. return this;
  47922. };
  47923. return ArcRotateCameraInputsManager;
  47924. }(BABYLON.CameraInputsManager));
  47925. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47926. })(BABYLON || (BABYLON = {}));
  47927. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47928. var BABYLON;
  47929. (function (BABYLON) {
  47930. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  47931. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  47932. });
  47933. var ArcRotateCamera = /** @class */ (function (_super) {
  47934. __extends(ArcRotateCamera, _super);
  47935. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47936. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47937. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47938. _this.inertialAlphaOffset = 0;
  47939. _this.inertialBetaOffset = 0;
  47940. _this.inertialRadiusOffset = 0;
  47941. _this.lowerAlphaLimit = null;
  47942. _this.upperAlphaLimit = null;
  47943. _this.lowerBetaLimit = 0.01;
  47944. _this.upperBetaLimit = Math.PI;
  47945. _this.lowerRadiusLimit = null;
  47946. _this.upperRadiusLimit = null;
  47947. _this.inertialPanningX = 0;
  47948. _this.inertialPanningY = 0;
  47949. _this.pinchToPanMaxDistance = 20;
  47950. _this.panningDistanceLimit = null;
  47951. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47952. _this.panningInertia = 0.9;
  47953. //-- end properties for backward compatibility for inputs
  47954. _this.zoomOnFactor = 1;
  47955. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47956. _this.allowUpsideDown = true;
  47957. /** @hidden */
  47958. _this._viewMatrix = new BABYLON.Matrix();
  47959. // Panning
  47960. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47961. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47962. _this.checkCollisions = false;
  47963. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47964. _this._previousPosition = BABYLON.Vector3.Zero();
  47965. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47966. _this._newPosition = BABYLON.Vector3.Zero();
  47967. _this._computationVector = BABYLON.Vector3.Zero();
  47968. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47969. if (collidedMesh === void 0) { collidedMesh = null; }
  47970. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47971. newPosition.multiplyInPlace(_this._collider._radius);
  47972. }
  47973. if (!collidedMesh) {
  47974. _this._previousPosition.copyFrom(_this.position);
  47975. }
  47976. else {
  47977. _this.setPosition(newPosition);
  47978. if (_this.onCollide) {
  47979. _this.onCollide(collidedMesh);
  47980. }
  47981. }
  47982. // Recompute because of constraints
  47983. var cosa = Math.cos(_this.alpha);
  47984. var sina = Math.sin(_this.alpha);
  47985. var cosb = Math.cos(_this.beta);
  47986. var sinb = Math.sin(_this.beta);
  47987. if (sinb === 0) {
  47988. sinb = 0.0001;
  47989. }
  47990. var target = _this._getTargetPosition();
  47991. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47992. target.addToRef(_this._computationVector, _this._newPosition);
  47993. _this.position.copyFrom(_this._newPosition);
  47994. var up = _this.upVector;
  47995. if (_this.allowUpsideDown && _this.beta < 0) {
  47996. up = up.clone();
  47997. up = up.negate();
  47998. }
  47999. _this._computeViewMatrix(_this.position, target, up);
  48000. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48001. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48002. _this._collisionTriggered = false;
  48003. };
  48004. _this._target = BABYLON.Vector3.Zero();
  48005. if (target) {
  48006. _this.setTarget(target);
  48007. }
  48008. _this.alpha = alpha;
  48009. _this.beta = beta;
  48010. _this.radius = radius;
  48011. _this.getViewMatrix();
  48012. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48013. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48014. return _this;
  48015. }
  48016. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48017. get: function () {
  48018. return this._target;
  48019. },
  48020. set: function (value) {
  48021. this.setTarget(value);
  48022. },
  48023. enumerable: true,
  48024. configurable: true
  48025. });
  48026. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48027. //-- begin properties for backward compatibility for inputs
  48028. get: function () {
  48029. var pointers = this.inputs.attached["pointers"];
  48030. if (pointers)
  48031. return pointers.angularSensibilityX;
  48032. return 0;
  48033. },
  48034. set: function (value) {
  48035. var pointers = this.inputs.attached["pointers"];
  48036. if (pointers) {
  48037. pointers.angularSensibilityX = value;
  48038. }
  48039. },
  48040. enumerable: true,
  48041. configurable: true
  48042. });
  48043. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48044. get: function () {
  48045. var pointers = this.inputs.attached["pointers"];
  48046. if (pointers)
  48047. return pointers.angularSensibilityY;
  48048. return 0;
  48049. },
  48050. set: function (value) {
  48051. var pointers = this.inputs.attached["pointers"];
  48052. if (pointers) {
  48053. pointers.angularSensibilityY = value;
  48054. }
  48055. },
  48056. enumerable: true,
  48057. configurable: true
  48058. });
  48059. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48060. get: function () {
  48061. var pointers = this.inputs.attached["pointers"];
  48062. if (pointers)
  48063. return pointers.pinchPrecision;
  48064. return 0;
  48065. },
  48066. set: function (value) {
  48067. var pointers = this.inputs.attached["pointers"];
  48068. if (pointers) {
  48069. pointers.pinchPrecision = value;
  48070. }
  48071. },
  48072. enumerable: true,
  48073. configurable: true
  48074. });
  48075. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48076. get: function () {
  48077. var pointers = this.inputs.attached["pointers"];
  48078. if (pointers)
  48079. return pointers.pinchDeltaPercentage;
  48080. return 0;
  48081. },
  48082. set: function (value) {
  48083. var pointers = this.inputs.attached["pointers"];
  48084. if (pointers) {
  48085. pointers.pinchDeltaPercentage = value;
  48086. }
  48087. },
  48088. enumerable: true,
  48089. configurable: true
  48090. });
  48091. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48092. get: function () {
  48093. var pointers = this.inputs.attached["pointers"];
  48094. if (pointers)
  48095. return pointers.panningSensibility;
  48096. return 0;
  48097. },
  48098. set: function (value) {
  48099. var pointers = this.inputs.attached["pointers"];
  48100. if (pointers) {
  48101. pointers.panningSensibility = value;
  48102. }
  48103. },
  48104. enumerable: true,
  48105. configurable: true
  48106. });
  48107. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48108. get: function () {
  48109. var keyboard = this.inputs.attached["keyboard"];
  48110. if (keyboard)
  48111. return keyboard.keysUp;
  48112. return [];
  48113. },
  48114. set: function (value) {
  48115. var keyboard = this.inputs.attached["keyboard"];
  48116. if (keyboard)
  48117. keyboard.keysUp = value;
  48118. },
  48119. enumerable: true,
  48120. configurable: true
  48121. });
  48122. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48123. get: function () {
  48124. var keyboard = this.inputs.attached["keyboard"];
  48125. if (keyboard)
  48126. return keyboard.keysDown;
  48127. return [];
  48128. },
  48129. set: function (value) {
  48130. var keyboard = this.inputs.attached["keyboard"];
  48131. if (keyboard)
  48132. keyboard.keysDown = value;
  48133. },
  48134. enumerable: true,
  48135. configurable: true
  48136. });
  48137. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48138. get: function () {
  48139. var keyboard = this.inputs.attached["keyboard"];
  48140. if (keyboard)
  48141. return keyboard.keysLeft;
  48142. return [];
  48143. },
  48144. set: function (value) {
  48145. var keyboard = this.inputs.attached["keyboard"];
  48146. if (keyboard)
  48147. keyboard.keysLeft = value;
  48148. },
  48149. enumerable: true,
  48150. configurable: true
  48151. });
  48152. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48153. get: function () {
  48154. var keyboard = this.inputs.attached["keyboard"];
  48155. if (keyboard)
  48156. return keyboard.keysRight;
  48157. return [];
  48158. },
  48159. set: function (value) {
  48160. var keyboard = this.inputs.attached["keyboard"];
  48161. if (keyboard)
  48162. keyboard.keysRight = value;
  48163. },
  48164. enumerable: true,
  48165. configurable: true
  48166. });
  48167. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48168. get: function () {
  48169. var mousewheel = this.inputs.attached["mousewheel"];
  48170. if (mousewheel)
  48171. return mousewheel.wheelPrecision;
  48172. return 0;
  48173. },
  48174. set: function (value) {
  48175. var mousewheel = this.inputs.attached["mousewheel"];
  48176. if (mousewheel)
  48177. mousewheel.wheelPrecision = value;
  48178. },
  48179. enumerable: true,
  48180. configurable: true
  48181. });
  48182. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48183. get: function () {
  48184. var mousewheel = this.inputs.attached["mousewheel"];
  48185. if (mousewheel)
  48186. return mousewheel.wheelDeltaPercentage;
  48187. return 0;
  48188. },
  48189. set: function (value) {
  48190. var mousewheel = this.inputs.attached["mousewheel"];
  48191. if (mousewheel)
  48192. mousewheel.wheelDeltaPercentage = value;
  48193. },
  48194. enumerable: true,
  48195. configurable: true
  48196. });
  48197. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48198. get: function () {
  48199. return this._bouncingBehavior;
  48200. },
  48201. enumerable: true,
  48202. configurable: true
  48203. });
  48204. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48205. get: function () {
  48206. return this._bouncingBehavior != null;
  48207. },
  48208. set: function (value) {
  48209. if (value === this.useBouncingBehavior) {
  48210. return;
  48211. }
  48212. if (value) {
  48213. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48214. this.addBehavior(this._bouncingBehavior);
  48215. }
  48216. else if (this._bouncingBehavior) {
  48217. this.removeBehavior(this._bouncingBehavior);
  48218. this._bouncingBehavior = null;
  48219. }
  48220. },
  48221. enumerable: true,
  48222. configurable: true
  48223. });
  48224. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48225. get: function () {
  48226. return this._framingBehavior;
  48227. },
  48228. enumerable: true,
  48229. configurable: true
  48230. });
  48231. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48232. get: function () {
  48233. return this._framingBehavior != null;
  48234. },
  48235. set: function (value) {
  48236. if (value === this.useFramingBehavior) {
  48237. return;
  48238. }
  48239. if (value) {
  48240. this._framingBehavior = new BABYLON.FramingBehavior();
  48241. this.addBehavior(this._framingBehavior);
  48242. }
  48243. else if (this._framingBehavior) {
  48244. this.removeBehavior(this._framingBehavior);
  48245. this._framingBehavior = null;
  48246. }
  48247. },
  48248. enumerable: true,
  48249. configurable: true
  48250. });
  48251. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48252. get: function () {
  48253. return this._autoRotationBehavior;
  48254. },
  48255. enumerable: true,
  48256. configurable: true
  48257. });
  48258. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48259. get: function () {
  48260. return this._autoRotationBehavior != null;
  48261. },
  48262. set: function (value) {
  48263. if (value === this.useAutoRotationBehavior) {
  48264. return;
  48265. }
  48266. if (value) {
  48267. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48268. this.addBehavior(this._autoRotationBehavior);
  48269. }
  48270. else if (this._autoRotationBehavior) {
  48271. this.removeBehavior(this._autoRotationBehavior);
  48272. this._autoRotationBehavior = null;
  48273. }
  48274. },
  48275. enumerable: true,
  48276. configurable: true
  48277. });
  48278. // Cache
  48279. /** @hidden */
  48280. ArcRotateCamera.prototype._initCache = function () {
  48281. _super.prototype._initCache.call(this);
  48282. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48283. this._cache.alpha = undefined;
  48284. this._cache.beta = undefined;
  48285. this._cache.radius = undefined;
  48286. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48287. };
  48288. /** @hidden */
  48289. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48290. if (!ignoreParentClass) {
  48291. _super.prototype._updateCache.call(this);
  48292. }
  48293. this._cache._target.copyFrom(this._getTargetPosition());
  48294. this._cache.alpha = this.alpha;
  48295. this._cache.beta = this.beta;
  48296. this._cache.radius = this.radius;
  48297. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48298. };
  48299. ArcRotateCamera.prototype._getTargetPosition = function () {
  48300. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48301. var pos = this._targetHost.getAbsolutePosition();
  48302. if (this._targetBoundingCenter) {
  48303. pos.addToRef(this._targetBoundingCenter, this._target);
  48304. }
  48305. else {
  48306. this._target.copyFrom(pos);
  48307. }
  48308. }
  48309. var lockedTargetPosition = this._getLockedTargetPosition();
  48310. if (lockedTargetPosition) {
  48311. return lockedTargetPosition;
  48312. }
  48313. return this._target;
  48314. };
  48315. ArcRotateCamera.prototype.storeState = function () {
  48316. this._storedAlpha = this.alpha;
  48317. this._storedBeta = this.beta;
  48318. this._storedRadius = this.radius;
  48319. this._storedTarget = this._getTargetPosition().clone();
  48320. return _super.prototype.storeState.call(this);
  48321. };
  48322. /**
  48323. * @hidden
  48324. * Restored camera state. You must call storeState() first
  48325. */
  48326. ArcRotateCamera.prototype._restoreStateValues = function () {
  48327. if (!_super.prototype._restoreStateValues.call(this)) {
  48328. return false;
  48329. }
  48330. this.alpha = this._storedAlpha;
  48331. this.beta = this._storedBeta;
  48332. this.radius = this._storedRadius;
  48333. this.setTarget(this._storedTarget.clone());
  48334. this.inertialAlphaOffset = 0;
  48335. this.inertialBetaOffset = 0;
  48336. this.inertialRadiusOffset = 0;
  48337. this.inertialPanningX = 0;
  48338. this.inertialPanningY = 0;
  48339. return true;
  48340. };
  48341. // Synchronized
  48342. /** @hidden */
  48343. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48344. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48345. return false;
  48346. return this._cache._target.equals(this._getTargetPosition())
  48347. && this._cache.alpha === this.alpha
  48348. && this._cache.beta === this.beta
  48349. && this._cache.radius === this.radius
  48350. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48351. };
  48352. // Methods
  48353. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48354. var _this = this;
  48355. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48356. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48357. this._useCtrlForPanning = useCtrlForPanning;
  48358. this._panningMouseButton = panningMouseButton;
  48359. this.inputs.attachElement(element, noPreventDefault);
  48360. this._reset = function () {
  48361. _this.inertialAlphaOffset = 0;
  48362. _this.inertialBetaOffset = 0;
  48363. _this.inertialRadiusOffset = 0;
  48364. _this.inertialPanningX = 0;
  48365. _this.inertialPanningY = 0;
  48366. };
  48367. };
  48368. ArcRotateCamera.prototype.detachControl = function (element) {
  48369. this.inputs.detachElement(element);
  48370. if (this._reset) {
  48371. this._reset();
  48372. }
  48373. };
  48374. /** @hidden */
  48375. ArcRotateCamera.prototype._checkInputs = function () {
  48376. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48377. if (this._collisionTriggered) {
  48378. return;
  48379. }
  48380. this.inputs.checkInputs();
  48381. // Inertia
  48382. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48383. var inertialAlphaOffset = this.inertialAlphaOffset;
  48384. if (this.beta <= 0)
  48385. inertialAlphaOffset *= -1;
  48386. if (this.getScene().useRightHandedSystem)
  48387. inertialAlphaOffset *= -1;
  48388. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48389. inertialAlphaOffset *= -1;
  48390. this.alpha += inertialAlphaOffset;
  48391. this.beta += this.inertialBetaOffset;
  48392. this.radius -= this.inertialRadiusOffset;
  48393. this.inertialAlphaOffset *= this.inertia;
  48394. this.inertialBetaOffset *= this.inertia;
  48395. this.inertialRadiusOffset *= this.inertia;
  48396. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48397. this.inertialAlphaOffset = 0;
  48398. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48399. this.inertialBetaOffset = 0;
  48400. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48401. this.inertialRadiusOffset = 0;
  48402. }
  48403. // Panning inertia
  48404. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48405. if (!this._localDirection) {
  48406. this._localDirection = BABYLON.Vector3.Zero();
  48407. this._transformedDirection = BABYLON.Vector3.Zero();
  48408. }
  48409. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48410. this._localDirection.multiplyInPlace(this.panningAxis);
  48411. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48412. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48413. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48414. if (!this.panningAxis.y) {
  48415. this._transformedDirection.y = 0;
  48416. }
  48417. if (!this._targetHost) {
  48418. if (this.panningDistanceLimit) {
  48419. this._transformedDirection.addInPlace(this._target);
  48420. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48421. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48422. this._target.copyFrom(this._transformedDirection);
  48423. }
  48424. }
  48425. else {
  48426. this._target.addInPlace(this._transformedDirection);
  48427. }
  48428. }
  48429. this.inertialPanningX *= this.panningInertia;
  48430. this.inertialPanningY *= this.panningInertia;
  48431. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48432. this.inertialPanningX = 0;
  48433. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48434. this.inertialPanningY = 0;
  48435. }
  48436. // Limits
  48437. this._checkLimits();
  48438. _super.prototype._checkInputs.call(this);
  48439. };
  48440. ArcRotateCamera.prototype._checkLimits = function () {
  48441. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48442. if (this.allowUpsideDown && this.beta > Math.PI) {
  48443. this.beta = this.beta - (2 * Math.PI);
  48444. }
  48445. }
  48446. else {
  48447. if (this.beta < this.lowerBetaLimit) {
  48448. this.beta = this.lowerBetaLimit;
  48449. }
  48450. }
  48451. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48452. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48453. this.beta = this.beta + (2 * Math.PI);
  48454. }
  48455. }
  48456. else {
  48457. if (this.beta > this.upperBetaLimit) {
  48458. this.beta = this.upperBetaLimit;
  48459. }
  48460. }
  48461. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  48462. this.alpha = this.lowerAlphaLimit;
  48463. }
  48464. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  48465. this.alpha = this.upperAlphaLimit;
  48466. }
  48467. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  48468. this.radius = this.lowerRadiusLimit;
  48469. }
  48470. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  48471. this.radius = this.upperRadiusLimit;
  48472. }
  48473. };
  48474. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48475. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48476. this.radius = this._computationVector.length();
  48477. if (this.radius === 0) {
  48478. this.radius = 0.0001; // Just to avoid division by zero
  48479. }
  48480. // Alpha
  48481. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48482. if (this._computationVector.z < 0) {
  48483. this.alpha = 2 * Math.PI - this.alpha;
  48484. }
  48485. // Beta
  48486. this.beta = Math.acos(this._computationVector.y / this.radius);
  48487. this._checkLimits();
  48488. };
  48489. ArcRotateCamera.prototype.setPosition = function (position) {
  48490. if (this.position.equals(position)) {
  48491. return;
  48492. }
  48493. this.position.copyFrom(position);
  48494. this.rebuildAnglesAndRadius();
  48495. };
  48496. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48497. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48498. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48499. if (target.getBoundingInfo) {
  48500. if (toBoundingCenter) {
  48501. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48502. }
  48503. else {
  48504. this._targetBoundingCenter = null;
  48505. }
  48506. this._targetHost = target;
  48507. this._target = this._getTargetPosition();
  48508. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48509. }
  48510. else {
  48511. var newTarget = target;
  48512. var currentTarget = this._getTargetPosition();
  48513. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48514. return;
  48515. }
  48516. this._targetHost = null;
  48517. this._target = newTarget;
  48518. this._targetBoundingCenter = null;
  48519. this.onMeshTargetChangedObservable.notifyObservers(null);
  48520. }
  48521. this.rebuildAnglesAndRadius();
  48522. };
  48523. /** @hidden */
  48524. ArcRotateCamera.prototype._getViewMatrix = function () {
  48525. // Compute
  48526. var cosa = Math.cos(this.alpha);
  48527. var sina = Math.sin(this.alpha);
  48528. var cosb = Math.cos(this.beta);
  48529. var sinb = Math.sin(this.beta);
  48530. if (sinb === 0) {
  48531. sinb = 0.0001;
  48532. }
  48533. var target = this._getTargetPosition();
  48534. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48535. target.addToRef(this._computationVector, this._newPosition);
  48536. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48537. if (!this._collider) {
  48538. this._collider = new BABYLON.Collider();
  48539. }
  48540. this._collider._radius = this.collisionRadius;
  48541. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48542. this._collisionTriggered = true;
  48543. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48544. }
  48545. else {
  48546. this.position.copyFrom(this._newPosition);
  48547. var up = this.upVector;
  48548. if (this.allowUpsideDown && sinb < 0) {
  48549. up = up.clone();
  48550. up = up.negate();
  48551. }
  48552. this._computeViewMatrix(this.position, target, up);
  48553. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48554. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48555. }
  48556. this._currentTarget = target;
  48557. return this._viewMatrix;
  48558. };
  48559. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48560. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48561. meshes = meshes || this.getScene().meshes;
  48562. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48563. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48564. this.radius = distance * this.zoomOnFactor;
  48565. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48566. };
  48567. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48568. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48569. var meshesOrMinMaxVector;
  48570. var distance;
  48571. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48572. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48573. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48574. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48575. }
  48576. else { //minMaxVector and distance
  48577. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48578. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48579. distance = minMaxVectorAndDistance.distance;
  48580. }
  48581. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48582. if (!doNotUpdateMaxZ) {
  48583. this.maxZ = distance * 2;
  48584. }
  48585. };
  48586. /**
  48587. * @override
  48588. * Override Camera.createRigCamera
  48589. */
  48590. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48591. var alphaShift = 0;
  48592. switch (this.cameraRigMode) {
  48593. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48594. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48595. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48596. case BABYLON.Camera.RIG_MODE_VR:
  48597. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48598. break;
  48599. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48600. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48601. break;
  48602. }
  48603. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48604. rigCam._cameraRigParams = {};
  48605. return rigCam;
  48606. };
  48607. /**
  48608. * @hidden
  48609. * @override
  48610. * Override Camera._updateRigCameras
  48611. */
  48612. ArcRotateCamera.prototype._updateRigCameras = function () {
  48613. var camLeft = this._rigCameras[0];
  48614. var camRight = this._rigCameras[1];
  48615. camLeft.beta = camRight.beta = this.beta;
  48616. camLeft.radius = camRight.radius = this.radius;
  48617. switch (this.cameraRigMode) {
  48618. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48619. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48620. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48621. case BABYLON.Camera.RIG_MODE_VR:
  48622. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48623. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48624. break;
  48625. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48626. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48627. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48628. break;
  48629. }
  48630. _super.prototype._updateRigCameras.call(this);
  48631. };
  48632. ArcRotateCamera.prototype.dispose = function () {
  48633. this.inputs.clear();
  48634. _super.prototype.dispose.call(this);
  48635. };
  48636. ArcRotateCamera.prototype.getClassName = function () {
  48637. return "ArcRotateCamera";
  48638. };
  48639. __decorate([
  48640. BABYLON.serialize()
  48641. ], ArcRotateCamera.prototype, "alpha", void 0);
  48642. __decorate([
  48643. BABYLON.serialize()
  48644. ], ArcRotateCamera.prototype, "beta", void 0);
  48645. __decorate([
  48646. BABYLON.serialize()
  48647. ], ArcRotateCamera.prototype, "radius", void 0);
  48648. __decorate([
  48649. BABYLON.serializeAsVector3("target")
  48650. ], ArcRotateCamera.prototype, "_target", void 0);
  48651. __decorate([
  48652. BABYLON.serialize()
  48653. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48654. __decorate([
  48655. BABYLON.serialize()
  48656. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48657. __decorate([
  48658. BABYLON.serialize()
  48659. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48660. __decorate([
  48661. BABYLON.serialize()
  48662. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48663. __decorate([
  48664. BABYLON.serialize()
  48665. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48666. __decorate([
  48667. BABYLON.serialize()
  48668. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48669. __decorate([
  48670. BABYLON.serialize()
  48671. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48672. __decorate([
  48673. BABYLON.serialize()
  48674. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48675. __decorate([
  48676. BABYLON.serialize()
  48677. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48678. __decorate([
  48679. BABYLON.serialize()
  48680. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48681. __decorate([
  48682. BABYLON.serialize()
  48683. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48684. __decorate([
  48685. BABYLON.serialize()
  48686. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48687. __decorate([
  48688. BABYLON.serialize()
  48689. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48690. __decorate([
  48691. BABYLON.serializeAsVector3()
  48692. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48693. __decorate([
  48694. BABYLON.serialize()
  48695. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48696. __decorate([
  48697. BABYLON.serialize()
  48698. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48699. __decorate([
  48700. BABYLON.serialize()
  48701. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48702. return ArcRotateCamera;
  48703. }(BABYLON.TargetCamera));
  48704. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48705. })(BABYLON || (BABYLON = {}));
  48706. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48707. var BABYLON;
  48708. (function (BABYLON) {
  48709. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  48710. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  48711. });
  48712. /**
  48713. * The HemisphericLight simulates the ambient environment light,
  48714. * so the passed direction is the light reflection direction, not the incoming direction.
  48715. */
  48716. var HemisphericLight = /** @class */ (function (_super) {
  48717. __extends(HemisphericLight, _super);
  48718. /**
  48719. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48720. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48721. * The HemisphericLight can't cast shadows.
  48722. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48723. * @param name The friendly name of the light
  48724. * @param direction The direction of the light reflection
  48725. * @param scene The scene the light belongs to
  48726. */
  48727. function HemisphericLight(name, direction, scene) {
  48728. var _this = _super.call(this, name, scene) || this;
  48729. /**
  48730. * The groundColor is the light in the opposite direction to the one specified during creation.
  48731. * 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.
  48732. */
  48733. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48734. _this.direction = direction || BABYLON.Vector3.Up();
  48735. return _this;
  48736. }
  48737. HemisphericLight.prototype._buildUniformLayout = function () {
  48738. this._uniformBuffer.addUniform("vLightData", 4);
  48739. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48740. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48741. this._uniformBuffer.addUniform("vLightGround", 3);
  48742. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48743. this._uniformBuffer.addUniform("depthValues", 2);
  48744. this._uniformBuffer.create();
  48745. };
  48746. /**
  48747. * Returns the string "HemisphericLight".
  48748. * @return The class name
  48749. */
  48750. HemisphericLight.prototype.getClassName = function () {
  48751. return "HemisphericLight";
  48752. };
  48753. /**
  48754. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48755. * Returns the updated direction.
  48756. * @param target The target the direction should point to
  48757. * @return The computed direction
  48758. */
  48759. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48760. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48761. return this.direction;
  48762. };
  48763. /**
  48764. * Returns the shadow generator associated to the light.
  48765. * @returns Always null for hemispheric lights because it does not support shadows.
  48766. */
  48767. HemisphericLight.prototype.getShadowGenerator = function () {
  48768. return null;
  48769. };
  48770. /**
  48771. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48772. * @param effect The effect to update
  48773. * @param lightIndex The index of the light in the effect to update
  48774. * @returns The hemispheric light
  48775. */
  48776. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48777. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48778. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48779. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48780. return this;
  48781. };
  48782. /**
  48783. * @hidden internal use only.
  48784. */
  48785. HemisphericLight.prototype._getWorldMatrix = function () {
  48786. if (!this._worldMatrix) {
  48787. this._worldMatrix = BABYLON.Matrix.Identity();
  48788. }
  48789. return this._worldMatrix;
  48790. };
  48791. /**
  48792. * Returns the integer 3.
  48793. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48794. */
  48795. HemisphericLight.prototype.getTypeID = function () {
  48796. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48797. };
  48798. /**
  48799. * Prepares the list of defines specific to the light type.
  48800. * @param defines the list of defines
  48801. * @param lightIndex defines the index of the light for the effect
  48802. */
  48803. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  48804. defines["HEMILIGHT" + lightIndex] = true;
  48805. };
  48806. __decorate([
  48807. BABYLON.serializeAsColor3()
  48808. ], HemisphericLight.prototype, "groundColor", void 0);
  48809. __decorate([
  48810. BABYLON.serializeAsVector3()
  48811. ], HemisphericLight.prototype, "direction", void 0);
  48812. return HemisphericLight;
  48813. }(BABYLON.Light));
  48814. BABYLON.HemisphericLight = HemisphericLight;
  48815. })(BABYLON || (BABYLON = {}));
  48816. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48817. var BABYLON;
  48818. (function (BABYLON) {
  48819. /**
  48820. * Base implementation IShadowLight
  48821. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48822. */
  48823. var ShadowLight = /** @class */ (function (_super) {
  48824. __extends(ShadowLight, _super);
  48825. function ShadowLight() {
  48826. var _this = _super !== null && _super.apply(this, arguments) || this;
  48827. _this._needProjectionMatrixCompute = true;
  48828. return _this;
  48829. }
  48830. ShadowLight.prototype._setPosition = function (value) {
  48831. this._position = value;
  48832. };
  48833. Object.defineProperty(ShadowLight.prototype, "position", {
  48834. /**
  48835. * Sets the position the shadow will be casted from. Also use as the light position for both
  48836. * point and spot lights.
  48837. */
  48838. get: function () {
  48839. return this._position;
  48840. },
  48841. /**
  48842. * Sets the position the shadow will be casted from. Also use as the light position for both
  48843. * point and spot lights.
  48844. */
  48845. set: function (value) {
  48846. this._setPosition(value);
  48847. },
  48848. enumerable: true,
  48849. configurable: true
  48850. });
  48851. ShadowLight.prototype._setDirection = function (value) {
  48852. this._direction = value;
  48853. };
  48854. Object.defineProperty(ShadowLight.prototype, "direction", {
  48855. /**
  48856. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48857. * Also use as the light direction on spot and directional lights.
  48858. */
  48859. get: function () {
  48860. return this._direction;
  48861. },
  48862. /**
  48863. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48864. * Also use as the light direction on spot and directional lights.
  48865. */
  48866. set: function (value) {
  48867. this._setDirection(value);
  48868. },
  48869. enumerable: true,
  48870. configurable: true
  48871. });
  48872. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48873. /**
  48874. * Gets the shadow projection clipping minimum z value.
  48875. */
  48876. get: function () {
  48877. return this._shadowMinZ;
  48878. },
  48879. /**
  48880. * Sets the shadow projection clipping minimum z value.
  48881. */
  48882. set: function (value) {
  48883. this._shadowMinZ = value;
  48884. this.forceProjectionMatrixCompute();
  48885. },
  48886. enumerable: true,
  48887. configurable: true
  48888. });
  48889. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48890. /**
  48891. * Sets the shadow projection clipping maximum z value.
  48892. */
  48893. get: function () {
  48894. return this._shadowMaxZ;
  48895. },
  48896. /**
  48897. * Gets the shadow projection clipping maximum z value.
  48898. */
  48899. set: function (value) {
  48900. this._shadowMaxZ = value;
  48901. this.forceProjectionMatrixCompute();
  48902. },
  48903. enumerable: true,
  48904. configurable: true
  48905. });
  48906. /**
  48907. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48908. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48909. */
  48910. ShadowLight.prototype.computeTransformedInformation = function () {
  48911. if (this.parent && this.parent.getWorldMatrix) {
  48912. if (!this.transformedPosition) {
  48913. this.transformedPosition = BABYLON.Vector3.Zero();
  48914. }
  48915. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48916. // In case the direction is present.
  48917. if (this.direction) {
  48918. if (!this.transformedDirection) {
  48919. this.transformedDirection = BABYLON.Vector3.Zero();
  48920. }
  48921. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48922. }
  48923. return true;
  48924. }
  48925. return false;
  48926. };
  48927. /**
  48928. * Return the depth scale used for the shadow map.
  48929. * @returns the depth scale.
  48930. */
  48931. ShadowLight.prototype.getDepthScale = function () {
  48932. return 50.0;
  48933. };
  48934. /**
  48935. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48936. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48937. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48938. */
  48939. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48940. return this.transformedDirection ? this.transformedDirection : this.direction;
  48941. };
  48942. /**
  48943. * Returns the ShadowLight absolute position in the World.
  48944. * @returns the position vector in world space
  48945. */
  48946. ShadowLight.prototype.getAbsolutePosition = function () {
  48947. return this.transformedPosition ? this.transformedPosition : this.position;
  48948. };
  48949. /**
  48950. * Sets the ShadowLight direction toward the passed target.
  48951. * @param target The point tot target in local space
  48952. * @returns the updated ShadowLight direction
  48953. */
  48954. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48955. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48956. return this.direction;
  48957. };
  48958. /**
  48959. * Returns the light rotation in euler definition.
  48960. * @returns the x y z rotation in local space.
  48961. */
  48962. ShadowLight.prototype.getRotation = function () {
  48963. this.direction.normalize();
  48964. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48965. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48966. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48967. };
  48968. /**
  48969. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48970. * @returns true if a cube texture needs to be use
  48971. */
  48972. ShadowLight.prototype.needCube = function () {
  48973. return false;
  48974. };
  48975. /**
  48976. * Detects if the projection matrix requires to be recomputed this frame.
  48977. * @returns true if it requires to be recomputed otherwise, false.
  48978. */
  48979. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48980. return this._needProjectionMatrixCompute;
  48981. };
  48982. /**
  48983. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48984. */
  48985. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48986. this._needProjectionMatrixCompute = true;
  48987. };
  48988. /**
  48989. * Get the world matrix of the sahdow lights.
  48990. * @hidden Internal Use Only
  48991. */
  48992. ShadowLight.prototype._getWorldMatrix = function () {
  48993. if (!this._worldMatrix) {
  48994. this._worldMatrix = BABYLON.Matrix.Identity();
  48995. }
  48996. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48997. return this._worldMatrix;
  48998. };
  48999. /**
  49000. * Gets the minZ used for shadow according to both the scene and the light.
  49001. * @param activeCamera The camera we are returning the min for
  49002. * @returns the depth min z
  49003. */
  49004. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49005. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49006. };
  49007. /**
  49008. * Gets the maxZ used for shadow according to both the scene and the light.
  49009. * @param activeCamera The camera we are returning the max for
  49010. * @returns the depth max z
  49011. */
  49012. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49013. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49014. };
  49015. /**
  49016. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49017. * @param matrix The materix to updated with the projection information
  49018. * @param viewMatrix The transform matrix of the light
  49019. * @param renderList The list of mesh to render in the map
  49020. * @returns The current light
  49021. */
  49022. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49023. if (this.customProjectionMatrixBuilder) {
  49024. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49025. }
  49026. else {
  49027. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49028. }
  49029. return this;
  49030. };
  49031. __decorate([
  49032. BABYLON.serializeAsVector3()
  49033. ], ShadowLight.prototype, "position", null);
  49034. __decorate([
  49035. BABYLON.serializeAsVector3()
  49036. ], ShadowLight.prototype, "direction", null);
  49037. __decorate([
  49038. BABYLON.serialize()
  49039. ], ShadowLight.prototype, "shadowMinZ", null);
  49040. __decorate([
  49041. BABYLON.serialize()
  49042. ], ShadowLight.prototype, "shadowMaxZ", null);
  49043. return ShadowLight;
  49044. }(BABYLON.Light));
  49045. BABYLON.ShadowLight = ShadowLight;
  49046. })(BABYLON || (BABYLON = {}));
  49047. //# sourceMappingURL=babylon.shadowLight.js.map
  49048. var BABYLON;
  49049. (function (BABYLON) {
  49050. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  49051. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  49052. });
  49053. /**
  49054. * A point light is a light defined by an unique point in world space.
  49055. * The light is emitted in every direction from this point.
  49056. * A good example of a point light is a standard light bulb.
  49057. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49058. */
  49059. var PointLight = /** @class */ (function (_super) {
  49060. __extends(PointLight, _super);
  49061. /**
  49062. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49063. * A PointLight emits the light in every direction.
  49064. * It can cast shadows.
  49065. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49066. * ```javascript
  49067. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49068. * ```
  49069. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49070. * @param name The light friendly name
  49071. * @param position The position of the point light in the scene
  49072. * @param scene The scene the lights belongs to
  49073. */
  49074. function PointLight(name, position, scene) {
  49075. var _this = _super.call(this, name, scene) || this;
  49076. _this._shadowAngle = Math.PI / 2;
  49077. _this.position = position;
  49078. return _this;
  49079. }
  49080. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49081. /**
  49082. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49083. * This specifies what angle the shadow will use to be created.
  49084. *
  49085. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49086. */
  49087. get: function () {
  49088. return this._shadowAngle;
  49089. },
  49090. /**
  49091. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49092. * This specifies what angle the shadow will use to be created.
  49093. *
  49094. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49095. */
  49096. set: function (value) {
  49097. this._shadowAngle = value;
  49098. this.forceProjectionMatrixCompute();
  49099. },
  49100. enumerable: true,
  49101. configurable: true
  49102. });
  49103. Object.defineProperty(PointLight.prototype, "direction", {
  49104. /**
  49105. * Gets the direction if it has been set.
  49106. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49107. */
  49108. get: function () {
  49109. return this._direction;
  49110. },
  49111. /**
  49112. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49113. */
  49114. set: function (value) {
  49115. var previousNeedCube = this.needCube();
  49116. this._direction = value;
  49117. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49118. this._shadowGenerator.recreateShadowMap();
  49119. }
  49120. },
  49121. enumerable: true,
  49122. configurable: true
  49123. });
  49124. /**
  49125. * Returns the string "PointLight"
  49126. * @returns the class name
  49127. */
  49128. PointLight.prototype.getClassName = function () {
  49129. return "PointLight";
  49130. };
  49131. /**
  49132. * Returns the integer 0.
  49133. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49134. */
  49135. PointLight.prototype.getTypeID = function () {
  49136. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49137. };
  49138. /**
  49139. * Specifies wether or not the shadowmap should be a cube texture.
  49140. * @returns true if the shadowmap needs to be a cube texture.
  49141. */
  49142. PointLight.prototype.needCube = function () {
  49143. return !this.direction;
  49144. };
  49145. /**
  49146. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49147. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49148. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49149. */
  49150. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49151. if (this.direction) {
  49152. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49153. }
  49154. else {
  49155. switch (faceIndex) {
  49156. case 0:
  49157. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49158. case 1:
  49159. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49160. case 2:
  49161. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49162. case 3:
  49163. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49164. case 4:
  49165. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49166. case 5:
  49167. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49168. }
  49169. }
  49170. return BABYLON.Vector3.Zero();
  49171. };
  49172. /**
  49173. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49174. * - fov = PI / 2
  49175. * - aspect ratio : 1.0
  49176. * - z-near and far equal to the active camera minZ and maxZ.
  49177. * Returns the PointLight.
  49178. */
  49179. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49180. var activeCamera = this.getScene().activeCamera;
  49181. if (!activeCamera) {
  49182. return;
  49183. }
  49184. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49185. };
  49186. PointLight.prototype._buildUniformLayout = function () {
  49187. this._uniformBuffer.addUniform("vLightData", 4);
  49188. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49189. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49190. this._uniformBuffer.addUniform("vLightFalloff", 4);
  49191. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49192. this._uniformBuffer.addUniform("depthValues", 2);
  49193. this._uniformBuffer.create();
  49194. };
  49195. /**
  49196. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49197. * @param effect The effect to update
  49198. * @param lightIndex The index of the light in the effect to update
  49199. * @returns The point light
  49200. */
  49201. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49202. if (this.computeTransformedInformation()) {
  49203. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49204. }
  49205. else {
  49206. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49207. }
  49208. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  49209. return this;
  49210. };
  49211. /**
  49212. * Prepares the list of defines specific to the light type.
  49213. * @param defines the list of defines
  49214. * @param lightIndex defines the index of the light for the effect
  49215. */
  49216. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49217. defines["POINTLIGHT" + lightIndex] = true;
  49218. };
  49219. __decorate([
  49220. BABYLON.serialize()
  49221. ], PointLight.prototype, "shadowAngle", null);
  49222. return PointLight;
  49223. }(BABYLON.ShadowLight));
  49224. BABYLON.PointLight = PointLight;
  49225. })(BABYLON || (BABYLON = {}));
  49226. //# sourceMappingURL=babylon.pointLight.js.map
  49227. var BABYLON;
  49228. (function (BABYLON) {
  49229. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  49230. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  49231. });
  49232. /**
  49233. * A directional light is defined by a direction (what a surprise!).
  49234. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49235. * 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.
  49236. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49237. */
  49238. var DirectionalLight = /** @class */ (function (_super) {
  49239. __extends(DirectionalLight, _super);
  49240. /**
  49241. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49242. * The directional light is emitted from everywhere in the given direction.
  49243. * It can cast shawdows.
  49244. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49245. * @param name The friendly name of the light
  49246. * @param direction The direction of the light
  49247. * @param scene The scene the light belongs to
  49248. */
  49249. function DirectionalLight(name, direction, scene) {
  49250. var _this = _super.call(this, name, scene) || this;
  49251. _this._shadowFrustumSize = 0;
  49252. _this._shadowOrthoScale = 0.1;
  49253. /**
  49254. * Automatically compute the projection matrix to best fit (including all the casters)
  49255. * on each frame.
  49256. */
  49257. _this.autoUpdateExtends = true;
  49258. // Cache
  49259. _this._orthoLeft = Number.MAX_VALUE;
  49260. _this._orthoRight = Number.MIN_VALUE;
  49261. _this._orthoTop = Number.MIN_VALUE;
  49262. _this._orthoBottom = Number.MAX_VALUE;
  49263. _this.position = direction.scale(-1.0);
  49264. _this.direction = direction;
  49265. return _this;
  49266. }
  49267. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49268. /**
  49269. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49270. */
  49271. get: function () {
  49272. return this._shadowFrustumSize;
  49273. },
  49274. /**
  49275. * Specifies a fix frustum size for the shadow generation.
  49276. */
  49277. set: function (value) {
  49278. this._shadowFrustumSize = value;
  49279. this.forceProjectionMatrixCompute();
  49280. },
  49281. enumerable: true,
  49282. configurable: true
  49283. });
  49284. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49285. /**
  49286. * Gets the shadow projection scale against the optimal computed one.
  49287. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49288. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49289. */
  49290. get: function () {
  49291. return this._shadowOrthoScale;
  49292. },
  49293. /**
  49294. * Sets the shadow projection scale against the optimal computed one.
  49295. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49296. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49297. */
  49298. set: function (value) {
  49299. this._shadowOrthoScale = value;
  49300. this.forceProjectionMatrixCompute();
  49301. },
  49302. enumerable: true,
  49303. configurable: true
  49304. });
  49305. /**
  49306. * Returns the string "DirectionalLight".
  49307. * @return The class name
  49308. */
  49309. DirectionalLight.prototype.getClassName = function () {
  49310. return "DirectionalLight";
  49311. };
  49312. /**
  49313. * Returns the integer 1.
  49314. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49315. */
  49316. DirectionalLight.prototype.getTypeID = function () {
  49317. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49318. };
  49319. /**
  49320. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49321. * Returns the DirectionalLight Shadow projection matrix.
  49322. */
  49323. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49324. if (this.shadowFrustumSize > 0) {
  49325. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49326. }
  49327. else {
  49328. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49329. }
  49330. };
  49331. /**
  49332. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49333. * Returns the DirectionalLight Shadow projection matrix.
  49334. */
  49335. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49336. var activeCamera = this.getScene().activeCamera;
  49337. if (!activeCamera) {
  49338. return;
  49339. }
  49340. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49341. };
  49342. /**
  49343. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49344. * Returns the DirectionalLight Shadow projection matrix.
  49345. */
  49346. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49347. var activeCamera = this.getScene().activeCamera;
  49348. if (!activeCamera) {
  49349. return;
  49350. }
  49351. // Check extends
  49352. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49353. var tempVector3 = BABYLON.Vector3.Zero();
  49354. this._orthoLeft = Number.MAX_VALUE;
  49355. this._orthoRight = Number.MIN_VALUE;
  49356. this._orthoTop = Number.MIN_VALUE;
  49357. this._orthoBottom = Number.MAX_VALUE;
  49358. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49359. var mesh = renderList[meshIndex];
  49360. if (!mesh) {
  49361. continue;
  49362. }
  49363. var boundingInfo = mesh.getBoundingInfo();
  49364. var boundingBox = boundingInfo.boundingBox;
  49365. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49366. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49367. if (tempVector3.x < this._orthoLeft)
  49368. this._orthoLeft = tempVector3.x;
  49369. if (tempVector3.y < this._orthoBottom)
  49370. this._orthoBottom = tempVector3.y;
  49371. if (tempVector3.x > this._orthoRight)
  49372. this._orthoRight = tempVector3.x;
  49373. if (tempVector3.y > this._orthoTop)
  49374. this._orthoTop = tempVector3.y;
  49375. }
  49376. }
  49377. }
  49378. var xOffset = this._orthoRight - this._orthoLeft;
  49379. var yOffset = this._orthoTop - this._orthoBottom;
  49380. 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);
  49381. };
  49382. DirectionalLight.prototype._buildUniformLayout = function () {
  49383. this._uniformBuffer.addUniform("vLightData", 4);
  49384. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49385. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49386. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49387. this._uniformBuffer.addUniform("depthValues", 2);
  49388. this._uniformBuffer.create();
  49389. };
  49390. /**
  49391. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49392. * @param effect The effect to update
  49393. * @param lightIndex The index of the light in the effect to update
  49394. * @returns The directional light
  49395. */
  49396. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49397. if (this.computeTransformedInformation()) {
  49398. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49399. return this;
  49400. }
  49401. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49402. return this;
  49403. };
  49404. /**
  49405. * Gets the minZ used for shadow according to both the scene and the light.
  49406. *
  49407. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49408. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49409. * @param activeCamera The camera we are returning the min for
  49410. * @returns the depth min z
  49411. */
  49412. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49413. return 1;
  49414. };
  49415. /**
  49416. * Gets the maxZ used for shadow according to both the scene and the light.
  49417. *
  49418. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49419. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49420. * @param activeCamera The camera we are returning the max for
  49421. * @returns the depth max z
  49422. */
  49423. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49424. return 1;
  49425. };
  49426. /**
  49427. * Prepares the list of defines specific to the light type.
  49428. * @param defines the list of defines
  49429. * @param lightIndex defines the index of the light for the effect
  49430. */
  49431. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49432. defines["DIRLIGHT" + lightIndex] = true;
  49433. };
  49434. __decorate([
  49435. BABYLON.serialize()
  49436. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49437. __decorate([
  49438. BABYLON.serialize()
  49439. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49440. __decorate([
  49441. BABYLON.serialize()
  49442. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49443. return DirectionalLight;
  49444. }(BABYLON.ShadowLight));
  49445. BABYLON.DirectionalLight = DirectionalLight;
  49446. })(BABYLON || (BABYLON = {}));
  49447. //# sourceMappingURL=babylon.directionalLight.js.map
  49448. var BABYLON;
  49449. (function (BABYLON) {
  49450. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  49451. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  49452. });
  49453. /**
  49454. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49455. * These values define a cone of light starting from the position, emitting toward the direction.
  49456. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49457. * and the exponent defines the speed of the decay of the light with distance (reach).
  49458. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49459. */
  49460. var SpotLight = /** @class */ (function (_super) {
  49461. __extends(SpotLight, _super);
  49462. /**
  49463. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49464. * It can cast shadows.
  49465. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49466. * @param name The light friendly name
  49467. * @param position The position of the spot light in the scene
  49468. * @param direction The direction of the light in the scene
  49469. * @param angle The cone angle of the light in Radians
  49470. * @param exponent The light decay speed with the distance from the emission spot
  49471. * @param scene The scene the lights belongs to
  49472. */
  49473. function SpotLight(name, position, direction, angle, exponent, scene) {
  49474. var _this = _super.call(this, name, scene) || this;
  49475. _this._innerAngle = 0;
  49476. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49477. _this._projectionTextureLightNear = 1e-6;
  49478. _this._projectionTextureLightFar = 1000.0;
  49479. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49480. _this._projectionTextureViewLightDirty = true;
  49481. _this._projectionTextureProjectionLightDirty = true;
  49482. _this._projectionTextureDirty = true;
  49483. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49484. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49485. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49486. _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);
  49487. _this.position = position;
  49488. _this.direction = direction;
  49489. _this.angle = angle;
  49490. _this.exponent = exponent;
  49491. return _this;
  49492. }
  49493. Object.defineProperty(SpotLight.prototype, "angle", {
  49494. /**
  49495. * Gets the cone angle of the spot light in Radians.
  49496. */
  49497. get: function () {
  49498. return this._angle;
  49499. },
  49500. /**
  49501. * Sets the cone angle of the spot light in Radians.
  49502. */
  49503. set: function (value) {
  49504. this._angle = value;
  49505. this._cosHalfAngle = Math.cos(value * 0.5);
  49506. this._projectionTextureProjectionLightDirty = true;
  49507. this.forceProjectionMatrixCompute();
  49508. this._computeAngleValues();
  49509. },
  49510. enumerable: true,
  49511. configurable: true
  49512. });
  49513. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  49514. /**
  49515. * Only used in gltf falloff mode, this defines the angle where
  49516. * the directional falloff will start before cutting at angle which could be seen
  49517. * as outer angle.
  49518. */
  49519. get: function () {
  49520. return this._angle;
  49521. },
  49522. /**
  49523. * Only used in gltf falloff mode, this defines the angle where
  49524. * the directional falloff will start before cutting at angle which could be seen
  49525. * as outer angle.
  49526. */
  49527. set: function (value) {
  49528. this._innerAngle = value;
  49529. this._computeAngleValues();
  49530. },
  49531. enumerable: true,
  49532. configurable: true
  49533. });
  49534. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49535. /**
  49536. * Allows scaling the angle of the light for shadow generation only.
  49537. */
  49538. get: function () {
  49539. return this._shadowAngleScale;
  49540. },
  49541. /**
  49542. * Allows scaling the angle of the light for shadow generation only.
  49543. */
  49544. set: function (value) {
  49545. this._shadowAngleScale = value;
  49546. this.forceProjectionMatrixCompute();
  49547. },
  49548. enumerable: true,
  49549. configurable: true
  49550. });
  49551. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49552. /**
  49553. * Allows reading the projecton texture
  49554. */
  49555. get: function () {
  49556. return this._projectionTextureMatrix;
  49557. },
  49558. enumerable: true,
  49559. configurable: true
  49560. });
  49561. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49562. /**
  49563. * Gets the near clip of the Spotlight for texture projection.
  49564. */
  49565. get: function () {
  49566. return this._projectionTextureLightNear;
  49567. },
  49568. /**
  49569. * Sets the near clip of the Spotlight for texture projection.
  49570. */
  49571. set: function (value) {
  49572. this._projectionTextureLightNear = value;
  49573. this._projectionTextureProjectionLightDirty = true;
  49574. },
  49575. enumerable: true,
  49576. configurable: true
  49577. });
  49578. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49579. /**
  49580. * Gets the far clip of the Spotlight for texture projection.
  49581. */
  49582. get: function () {
  49583. return this._projectionTextureLightFar;
  49584. },
  49585. /**
  49586. * Sets the far clip of the Spotlight for texture projection.
  49587. */
  49588. set: function (value) {
  49589. this._projectionTextureLightFar = value;
  49590. this._projectionTextureProjectionLightDirty = true;
  49591. },
  49592. enumerable: true,
  49593. configurable: true
  49594. });
  49595. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49596. /**
  49597. * Gets the Up vector of the Spotlight for texture projection.
  49598. */
  49599. get: function () {
  49600. return this._projectionTextureUpDirection;
  49601. },
  49602. /**
  49603. * Sets the Up vector of the Spotlight for texture projection.
  49604. */
  49605. set: function (value) {
  49606. this._projectionTextureUpDirection = value;
  49607. this._projectionTextureProjectionLightDirty = true;
  49608. },
  49609. enumerable: true,
  49610. configurable: true
  49611. });
  49612. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49613. /**
  49614. * Gets the projection texture of the light.
  49615. */
  49616. get: function () {
  49617. return this._projectionTexture;
  49618. },
  49619. /**
  49620. * Sets the projection texture of the light.
  49621. */
  49622. set: function (value) {
  49623. this._projectionTexture = value;
  49624. this._projectionTextureDirty = true;
  49625. },
  49626. enumerable: true,
  49627. configurable: true
  49628. });
  49629. /**
  49630. * Returns the string "SpotLight".
  49631. * @returns the class name
  49632. */
  49633. SpotLight.prototype.getClassName = function () {
  49634. return "SpotLight";
  49635. };
  49636. /**
  49637. * Returns the integer 2.
  49638. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49639. */
  49640. SpotLight.prototype.getTypeID = function () {
  49641. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49642. };
  49643. /**
  49644. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49645. */
  49646. SpotLight.prototype._setDirection = function (value) {
  49647. _super.prototype._setDirection.call(this, value);
  49648. this._projectionTextureViewLightDirty = true;
  49649. };
  49650. /**
  49651. * Overrides the position setter to recompute the projection texture view light Matrix.
  49652. */
  49653. SpotLight.prototype._setPosition = function (value) {
  49654. _super.prototype._setPosition.call(this, value);
  49655. this._projectionTextureViewLightDirty = true;
  49656. };
  49657. /**
  49658. * 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.
  49659. * Returns the SpotLight.
  49660. */
  49661. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49662. var activeCamera = this.getScene().activeCamera;
  49663. if (!activeCamera) {
  49664. return;
  49665. }
  49666. this._shadowAngleScale = this._shadowAngleScale || 1;
  49667. var angle = this._shadowAngleScale * this._angle;
  49668. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49669. };
  49670. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49671. this._projectionTextureViewLightDirty = false;
  49672. this._projectionTextureDirty = true;
  49673. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49674. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49675. };
  49676. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49677. this._projectionTextureProjectionLightDirty = false;
  49678. this._projectionTextureDirty = true;
  49679. var light_far = this.projectionTextureLightFar;
  49680. var light_near = this.projectionTextureLightNear;
  49681. var P = light_far / (light_far - light_near);
  49682. var Q = -P * light_near;
  49683. var S = 1.0 / Math.tan(this._angle / 2.0);
  49684. var A = 1.0;
  49685. 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);
  49686. };
  49687. /**
  49688. * Main function for light texture projection matrix computing.
  49689. */
  49690. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49691. this._projectionTextureDirty = false;
  49692. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49693. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49694. };
  49695. SpotLight.prototype._buildUniformLayout = function () {
  49696. this._uniformBuffer.addUniform("vLightData", 4);
  49697. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49698. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49699. this._uniformBuffer.addUniform("vLightDirection", 3);
  49700. this._uniformBuffer.addUniform("vLightFalloff", 4);
  49701. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49702. this._uniformBuffer.addUniform("depthValues", 2);
  49703. this._uniformBuffer.create();
  49704. };
  49705. SpotLight.prototype._computeAngleValues = function () {
  49706. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  49707. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  49708. };
  49709. /**
  49710. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49711. * @param effect The effect to update
  49712. * @param lightIndex The index of the light in the effect to update
  49713. * @returns The spot light
  49714. */
  49715. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49716. var normalizeDirection;
  49717. if (this.computeTransformedInformation()) {
  49718. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49719. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49720. }
  49721. else {
  49722. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49723. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49724. }
  49725. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  49726. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  49727. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49728. if (this._projectionTextureViewLightDirty) {
  49729. this._computeProjectionTextureViewLightMatrix();
  49730. }
  49731. if (this._projectionTextureProjectionLightDirty) {
  49732. this._computeProjectionTextureProjectionLightMatrix();
  49733. }
  49734. if (this._projectionTextureDirty) {
  49735. this._computeProjectionTextureMatrix();
  49736. }
  49737. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49738. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49739. }
  49740. return this;
  49741. };
  49742. /**
  49743. * Disposes the light and the associated resources.
  49744. */
  49745. SpotLight.prototype.dispose = function () {
  49746. _super.prototype.dispose.call(this);
  49747. if (this._projectionTexture) {
  49748. this._projectionTexture.dispose();
  49749. }
  49750. };
  49751. /**
  49752. * Prepares the list of defines specific to the light type.
  49753. * @param defines the list of defines
  49754. * @param lightIndex defines the index of the light for the effect
  49755. */
  49756. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  49757. defines["SPOTLIGHT" + lightIndex] = true;
  49758. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  49759. };
  49760. __decorate([
  49761. BABYLON.serialize()
  49762. ], SpotLight.prototype, "angle", null);
  49763. __decorate([
  49764. BABYLON.serialize()
  49765. ], SpotLight.prototype, "innerAngle", null);
  49766. __decorate([
  49767. BABYLON.serialize()
  49768. ], SpotLight.prototype, "shadowAngleScale", null);
  49769. __decorate([
  49770. BABYLON.serialize()
  49771. ], SpotLight.prototype, "exponent", void 0);
  49772. __decorate([
  49773. BABYLON.serialize()
  49774. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49775. __decorate([
  49776. BABYLON.serialize()
  49777. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49778. __decorate([
  49779. BABYLON.serialize()
  49780. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49781. __decorate([
  49782. BABYLON.serializeAsTexture("projectedLightTexture")
  49783. ], SpotLight.prototype, "_projectionTexture", void 0);
  49784. return SpotLight;
  49785. }(BABYLON.ShadowLight));
  49786. BABYLON.SpotLight = SpotLight;
  49787. })(BABYLON || (BABYLON = {}));
  49788. //# sourceMappingURL=babylon.spotLight.js.map
  49789. var BABYLON;
  49790. (function (BABYLON) {
  49791. /**
  49792. * Class used to override all child animations of a given target
  49793. */
  49794. var AnimationPropertiesOverride = /** @class */ (function () {
  49795. function AnimationPropertiesOverride() {
  49796. /**
  49797. * Gets or sets a value indicating if animation blending must be used
  49798. */
  49799. this.enableBlending = false;
  49800. /**
  49801. * Gets or sets the blending speed to use when enableBlending is true
  49802. */
  49803. this.blendingSpeed = 0.01;
  49804. /**
  49805. * Gets or sets the default loop mode to use
  49806. */
  49807. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49808. }
  49809. return AnimationPropertiesOverride;
  49810. }());
  49811. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49812. })(BABYLON || (BABYLON = {}));
  49813. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49814. var BABYLON;
  49815. (function (BABYLON) {
  49816. /**
  49817. * Represents the range of an animation
  49818. */
  49819. var AnimationRange = /** @class */ (function () {
  49820. /**
  49821. * Initializes the range of an animation
  49822. * @param name The name of the animation range
  49823. * @param from The starting frame of the animation
  49824. * @param to The ending frame of the animation
  49825. */
  49826. function AnimationRange(
  49827. /**The name of the animation range**/
  49828. name,
  49829. /**The starting frame of the animation */
  49830. from,
  49831. /**The ending frame of the animation*/
  49832. to) {
  49833. this.name = name;
  49834. this.from = from;
  49835. this.to = to;
  49836. }
  49837. /**
  49838. * Makes a copy of the animation range
  49839. * @returns A copy of the animation range
  49840. */
  49841. AnimationRange.prototype.clone = function () {
  49842. return new AnimationRange(this.name, this.from, this.to);
  49843. };
  49844. return AnimationRange;
  49845. }());
  49846. BABYLON.AnimationRange = AnimationRange;
  49847. /**
  49848. * Composed of a frame, and an action function
  49849. */
  49850. var AnimationEvent = /** @class */ (function () {
  49851. /**
  49852. * Initializes the animation event
  49853. * @param frame The frame for which the event is triggered
  49854. * @param action The event to perform when triggered
  49855. * @param onlyOnce Specifies if the event should be triggered only once
  49856. */
  49857. function AnimationEvent(
  49858. /** The frame for which the event is triggered **/
  49859. frame,
  49860. /** The event to perform when triggered **/
  49861. action,
  49862. /** Specifies if the event should be triggered only once**/
  49863. onlyOnce) {
  49864. this.frame = frame;
  49865. this.action = action;
  49866. this.onlyOnce = onlyOnce;
  49867. /**
  49868. * Specifies if the animation event is done
  49869. */
  49870. this.isDone = false;
  49871. }
  49872. /** @hidden */
  49873. AnimationEvent.prototype._clone = function () {
  49874. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49875. };
  49876. return AnimationEvent;
  49877. }());
  49878. BABYLON.AnimationEvent = AnimationEvent;
  49879. /**
  49880. * A cursor which tracks a point on a path
  49881. */
  49882. var PathCursor = /** @class */ (function () {
  49883. /**
  49884. * Initializes the path cursor
  49885. * @param path The path to track
  49886. */
  49887. function PathCursor(path) {
  49888. this.path = path;
  49889. /**
  49890. * Stores path cursor callbacks for when an onchange event is triggered
  49891. */
  49892. this._onchange = new Array();
  49893. /**
  49894. * The value of the path cursor
  49895. */
  49896. this.value = 0;
  49897. /**
  49898. * The animation array of the path cursor
  49899. */
  49900. this.animations = new Array();
  49901. }
  49902. /**
  49903. * Gets the cursor point on the path
  49904. * @returns A point on the path cursor at the cursor location
  49905. */
  49906. PathCursor.prototype.getPoint = function () {
  49907. var point = this.path.getPointAtLengthPosition(this.value);
  49908. return new BABYLON.Vector3(point.x, 0, point.y);
  49909. };
  49910. /**
  49911. * Moves the cursor ahead by the step amount
  49912. * @param step The amount to move the cursor forward
  49913. * @returns This path cursor
  49914. */
  49915. PathCursor.prototype.moveAhead = function (step) {
  49916. if (step === void 0) { step = 0.002; }
  49917. this.move(step);
  49918. return this;
  49919. };
  49920. /**
  49921. * Moves the cursor behind by the step amount
  49922. * @param step The amount to move the cursor back
  49923. * @returns This path cursor
  49924. */
  49925. PathCursor.prototype.moveBack = function (step) {
  49926. if (step === void 0) { step = 0.002; }
  49927. this.move(-step);
  49928. return this;
  49929. };
  49930. /**
  49931. * Moves the cursor by the step amount
  49932. * If the step amount is greater than one, an exception is thrown
  49933. * @param step The amount to move the cursor
  49934. * @returns This path cursor
  49935. */
  49936. PathCursor.prototype.move = function (step) {
  49937. if (Math.abs(step) > 1) {
  49938. throw "step size should be less than 1.";
  49939. }
  49940. this.value += step;
  49941. this.ensureLimits();
  49942. this.raiseOnChange();
  49943. return this;
  49944. };
  49945. /**
  49946. * Ensures that the value is limited between zero and one
  49947. * @returns This path cursor
  49948. */
  49949. PathCursor.prototype.ensureLimits = function () {
  49950. while (this.value > 1) {
  49951. this.value -= 1;
  49952. }
  49953. while (this.value < 0) {
  49954. this.value += 1;
  49955. }
  49956. return this;
  49957. };
  49958. /**
  49959. * Runs onchange callbacks on change (used by the animation engine)
  49960. * @returns This path cursor
  49961. */
  49962. PathCursor.prototype.raiseOnChange = function () {
  49963. var _this = this;
  49964. this._onchange.forEach(function (f) { return f(_this); });
  49965. return this;
  49966. };
  49967. /**
  49968. * Executes a function on change
  49969. * @param f A path cursor onchange callback
  49970. * @returns This path cursor
  49971. */
  49972. PathCursor.prototype.onchange = function (f) {
  49973. this._onchange.push(f);
  49974. return this;
  49975. };
  49976. return PathCursor;
  49977. }());
  49978. BABYLON.PathCursor = PathCursor;
  49979. /**
  49980. * Enum for the animation key frame interpolation type
  49981. */
  49982. var AnimationKeyInterpolation;
  49983. (function (AnimationKeyInterpolation) {
  49984. /**
  49985. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49986. */
  49987. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49988. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49989. /**
  49990. * Class used to store any kind of animation
  49991. */
  49992. var Animation = /** @class */ (function () {
  49993. /**
  49994. * Initializes the animation
  49995. * @param name Name of the animation
  49996. * @param targetProperty Property to animate
  49997. * @param framePerSecond The frames per second of the animation
  49998. * @param dataType The data type of the animation
  49999. * @param loopMode The loop mode of the animation
  50000. * @param enableBlendings Specifies if blending should be enabled
  50001. */
  50002. function Animation(
  50003. /**Name of the animation */
  50004. name,
  50005. /**Property to animate */
  50006. targetProperty,
  50007. /**The frames per second of the animation */
  50008. framePerSecond,
  50009. /**The data type of the animation */
  50010. dataType,
  50011. /**The loop mode of the animation */
  50012. loopMode,
  50013. /**Specifies if blending should be enabled */
  50014. enableBlending) {
  50015. this.name = name;
  50016. this.targetProperty = targetProperty;
  50017. this.framePerSecond = framePerSecond;
  50018. this.dataType = dataType;
  50019. this.loopMode = loopMode;
  50020. this.enableBlending = enableBlending;
  50021. /**
  50022. * @hidden Internal use only
  50023. */
  50024. this._runtimeAnimations = new Array();
  50025. /**
  50026. * The set of event that will be linked to this animation
  50027. */
  50028. this._events = new Array();
  50029. /**
  50030. * Stores the blending speed of the animation
  50031. */
  50032. this.blendingSpeed = 0.01;
  50033. /**
  50034. * Stores the animation ranges for the animation
  50035. */
  50036. this._ranges = {};
  50037. this.targetPropertyPath = targetProperty.split(".");
  50038. this.dataType = dataType;
  50039. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50040. }
  50041. /**
  50042. * @hidden Internal use
  50043. */
  50044. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50045. var dataType = undefined;
  50046. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50047. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50048. }
  50049. else if (from instanceof BABYLON.Quaternion) {
  50050. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50051. }
  50052. else if (from instanceof BABYLON.Vector3) {
  50053. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50054. }
  50055. else if (from instanceof BABYLON.Vector2) {
  50056. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50057. }
  50058. else if (from instanceof BABYLON.Color3) {
  50059. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50060. }
  50061. else if (from instanceof BABYLON.Size) {
  50062. dataType = Animation.ANIMATIONTYPE_SIZE;
  50063. }
  50064. if (dataType == undefined) {
  50065. return null;
  50066. }
  50067. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50068. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50069. animation.setKeys(keys);
  50070. if (easingFunction !== undefined) {
  50071. animation.setEasingFunction(easingFunction);
  50072. }
  50073. return animation;
  50074. };
  50075. /**
  50076. * Sets up an animation
  50077. * @param property The property to animate
  50078. * @param animationType The animation type to apply
  50079. * @param framePerSecond The frames per second of the animation
  50080. * @param easingFunction The easing function used in the animation
  50081. * @returns The created animation
  50082. */
  50083. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50084. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50085. animation.setEasingFunction(easingFunction);
  50086. return animation;
  50087. };
  50088. /**
  50089. * Create and start an animation on a node
  50090. * @param name defines the name of the global animation that will be run on all nodes
  50091. * @param node defines the root node where the animation will take place
  50092. * @param targetProperty defines property to animate
  50093. * @param framePerSecond defines the number of frame per second yo use
  50094. * @param totalFrame defines the number of frames in total
  50095. * @param from defines the initial value
  50096. * @param to defines the final value
  50097. * @param loopMode defines which loop mode you want to use (off by default)
  50098. * @param easingFunction defines the easing function to use (linear by default)
  50099. * @param onAnimationEnd defines the callback to call when animation end
  50100. * @returns the animatable created for this animation
  50101. */
  50102. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50103. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50104. if (!animation) {
  50105. return null;
  50106. }
  50107. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50108. };
  50109. /**
  50110. * Create and start an animation on a node and its descendants
  50111. * @param name defines the name of the global animation that will be run on all nodes
  50112. * @param node defines the root node where the animation will take place
  50113. * @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
  50114. * @param targetProperty defines property to animate
  50115. * @param framePerSecond defines the number of frame per second to use
  50116. * @param totalFrame defines the number of frames in total
  50117. * @param from defines the initial value
  50118. * @param to defines the final value
  50119. * @param loopMode defines which loop mode you want to use (off by default)
  50120. * @param easingFunction defines the easing function to use (linear by default)
  50121. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50122. * @returns the list of animatables created for all nodes
  50123. * @example https://www.babylonjs-playground.com/#MH0VLI
  50124. */
  50125. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50126. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50127. if (!animation) {
  50128. return null;
  50129. }
  50130. var scene = node.getScene();
  50131. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50132. };
  50133. /**
  50134. * Creates a new animation, merges it with the existing animations and starts it
  50135. * @param name Name of the animation
  50136. * @param node Node which contains the scene that begins the animations
  50137. * @param targetProperty Specifies which property to animate
  50138. * @param framePerSecond The frames per second of the animation
  50139. * @param totalFrame The total number of frames
  50140. * @param from The frame at the beginning of the animation
  50141. * @param to The frame at the end of the animation
  50142. * @param loopMode Specifies the loop mode of the animation
  50143. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50144. * @param onAnimationEnd Callback to run once the animation is complete
  50145. * @returns Nullable animation
  50146. */
  50147. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50148. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50149. if (!animation) {
  50150. return null;
  50151. }
  50152. node.animations.push(animation);
  50153. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50154. };
  50155. /**
  50156. * Transition property of an host to the target Value
  50157. * @param property The property to transition
  50158. * @param targetValue The target Value of the property
  50159. * @param host The object where the property to animate belongs
  50160. * @param scene Scene used to run the animation
  50161. * @param frameRate Framerate (in frame/s) to use
  50162. * @param transition The transition type we want to use
  50163. * @param duration The duration of the animation, in milliseconds
  50164. * @param onAnimationEnd Callback trigger at the end of the animation
  50165. * @returns Nullable animation
  50166. */
  50167. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50168. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50169. if (duration <= 0) {
  50170. host[property] = targetValue;
  50171. if (onAnimationEnd) {
  50172. onAnimationEnd();
  50173. }
  50174. return null;
  50175. }
  50176. var endFrame = frameRate * (duration / 1000);
  50177. transition.setKeys([{
  50178. frame: 0,
  50179. value: host[property].clone ? host[property].clone() : host[property]
  50180. },
  50181. {
  50182. frame: endFrame,
  50183. value: targetValue
  50184. }]);
  50185. if (!host.animations) {
  50186. host.animations = [];
  50187. }
  50188. host.animations.push(transition);
  50189. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50190. animation.onAnimationEnd = onAnimationEnd;
  50191. return animation;
  50192. };
  50193. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50194. /**
  50195. * Return the array of runtime animations currently using this animation
  50196. */
  50197. get: function () {
  50198. return this._runtimeAnimations;
  50199. },
  50200. enumerable: true,
  50201. configurable: true
  50202. });
  50203. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50204. /**
  50205. * Specifies if any of the runtime animations are currently running
  50206. */
  50207. get: function () {
  50208. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50209. var runtimeAnimation = _a[_i];
  50210. if (!runtimeAnimation.isStopped) {
  50211. return true;
  50212. }
  50213. }
  50214. return false;
  50215. },
  50216. enumerable: true,
  50217. configurable: true
  50218. });
  50219. // Methods
  50220. /**
  50221. * Converts the animation to a string
  50222. * @param fullDetails support for multiple levels of logging within scene loading
  50223. * @returns String form of the animation
  50224. */
  50225. Animation.prototype.toString = function (fullDetails) {
  50226. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50227. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50228. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50229. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50230. if (fullDetails) {
  50231. ret += ", Ranges: {";
  50232. var first = true;
  50233. for (var name in this._ranges) {
  50234. if (first) {
  50235. ret += ", ";
  50236. first = false;
  50237. }
  50238. ret += name;
  50239. }
  50240. ret += "}";
  50241. }
  50242. return ret;
  50243. };
  50244. /**
  50245. * Add an event to this animation
  50246. * @param event Event to add
  50247. */
  50248. Animation.prototype.addEvent = function (event) {
  50249. this._events.push(event);
  50250. };
  50251. /**
  50252. * Remove all events found at the given frame
  50253. * @param frame The frame to remove events from
  50254. */
  50255. Animation.prototype.removeEvents = function (frame) {
  50256. for (var index = 0; index < this._events.length; index++) {
  50257. if (this._events[index].frame === frame) {
  50258. this._events.splice(index, 1);
  50259. index--;
  50260. }
  50261. }
  50262. };
  50263. /**
  50264. * Retrieves all the events from the animation
  50265. * @returns Events from the animation
  50266. */
  50267. Animation.prototype.getEvents = function () {
  50268. return this._events;
  50269. };
  50270. /**
  50271. * Creates an animation range
  50272. * @param name Name of the animation range
  50273. * @param from Starting frame of the animation range
  50274. * @param to Ending frame of the animation
  50275. */
  50276. Animation.prototype.createRange = function (name, from, to) {
  50277. // check name not already in use; could happen for bones after serialized
  50278. if (!this._ranges[name]) {
  50279. this._ranges[name] = new AnimationRange(name, from, to);
  50280. }
  50281. };
  50282. /**
  50283. * Deletes an animation range by name
  50284. * @param name Name of the animation range to delete
  50285. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50286. */
  50287. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50288. if (deleteFrames === void 0) { deleteFrames = true; }
  50289. var range = this._ranges[name];
  50290. if (!range) {
  50291. return;
  50292. }
  50293. if (deleteFrames) {
  50294. var from = range.from;
  50295. var to = range.to;
  50296. // this loop MUST go high to low for multiple splices to work
  50297. for (var key = this._keys.length - 1; key >= 0; key--) {
  50298. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50299. this._keys.splice(key, 1);
  50300. }
  50301. }
  50302. }
  50303. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50304. };
  50305. /**
  50306. * Gets the animation range by name, or null if not defined
  50307. * @param name Name of the animation range
  50308. * @returns Nullable animation range
  50309. */
  50310. Animation.prototype.getRange = function (name) {
  50311. return this._ranges[name];
  50312. };
  50313. /**
  50314. * Gets the key frames from the animation
  50315. * @returns The key frames of the animation
  50316. */
  50317. Animation.prototype.getKeys = function () {
  50318. return this._keys;
  50319. };
  50320. /**
  50321. * Gets the highest frame rate of the animation
  50322. * @returns Highest frame rate of the animation
  50323. */
  50324. Animation.prototype.getHighestFrame = function () {
  50325. var ret = 0;
  50326. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50327. if (ret < this._keys[key].frame) {
  50328. ret = this._keys[key].frame;
  50329. }
  50330. }
  50331. return ret;
  50332. };
  50333. /**
  50334. * Gets the easing function of the animation
  50335. * @returns Easing function of the animation
  50336. */
  50337. Animation.prototype.getEasingFunction = function () {
  50338. return this._easingFunction;
  50339. };
  50340. /**
  50341. * Sets the easing function of the animation
  50342. * @param easingFunction A custom mathematical formula for animation
  50343. */
  50344. Animation.prototype.setEasingFunction = function (easingFunction) {
  50345. this._easingFunction = easingFunction;
  50346. };
  50347. /**
  50348. * Interpolates a scalar linearly
  50349. * @param startValue Start value of the animation curve
  50350. * @param endValue End value of the animation curve
  50351. * @param gradient Scalar amount to interpolate
  50352. * @returns Interpolated scalar value
  50353. */
  50354. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50355. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50356. };
  50357. /**
  50358. * Interpolates a scalar cubically
  50359. * @param startValue Start value of the animation curve
  50360. * @param outTangent End tangent of the animation
  50361. * @param endValue End value of the animation curve
  50362. * @param inTangent Start tangent of the animation curve
  50363. * @param gradient Scalar amount to interpolate
  50364. * @returns Interpolated scalar value
  50365. */
  50366. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50367. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50368. };
  50369. /**
  50370. * Interpolates a quaternion using a spherical linear interpolation
  50371. * @param startValue Start value of the animation curve
  50372. * @param endValue End value of the animation curve
  50373. * @param gradient Scalar amount to interpolate
  50374. * @returns Interpolated quaternion value
  50375. */
  50376. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50377. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50378. };
  50379. /**
  50380. * Interpolates a quaternion cubically
  50381. * @param startValue Start value of the animation curve
  50382. * @param outTangent End tangent of the animation curve
  50383. * @param endValue End value of the animation curve
  50384. * @param inTangent Start tangent of the animation curve
  50385. * @param gradient Scalar amount to interpolate
  50386. * @returns Interpolated quaternion value
  50387. */
  50388. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50389. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50390. };
  50391. /**
  50392. * Interpolates a Vector3 linearl
  50393. * @param startValue Start value of the animation curve
  50394. * @param endValue End value of the animation curve
  50395. * @param gradient Scalar amount to interpolate
  50396. * @returns Interpolated scalar value
  50397. */
  50398. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50399. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50400. };
  50401. /**
  50402. * Interpolates a Vector3 cubically
  50403. * @param startValue Start value of the animation curve
  50404. * @param outTangent End tangent of the animation
  50405. * @param endValue End value of the animation curve
  50406. * @param inTangent Start tangent of the animation curve
  50407. * @param gradient Scalar amount to interpolate
  50408. * @returns InterpolatedVector3 value
  50409. */
  50410. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50411. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50412. };
  50413. /**
  50414. * Interpolates a Vector2 linearly
  50415. * @param startValue Start value of the animation curve
  50416. * @param endValue End value of the animation curve
  50417. * @param gradient Scalar amount to interpolate
  50418. * @returns Interpolated Vector2 value
  50419. */
  50420. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50421. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50422. };
  50423. /**
  50424. * Interpolates a Vector2 cubically
  50425. * @param startValue Start value of the animation curve
  50426. * @param outTangent End tangent of the animation
  50427. * @param endValue End value of the animation curve
  50428. * @param inTangent Start tangent of the animation curve
  50429. * @param gradient Scalar amount to interpolate
  50430. * @returns Interpolated Vector2 value
  50431. */
  50432. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50433. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50434. };
  50435. /**
  50436. * Interpolates a size linearly
  50437. * @param startValue Start value of the animation curve
  50438. * @param endValue End value of the animation curve
  50439. * @param gradient Scalar amount to interpolate
  50440. * @returns Interpolated Size value
  50441. */
  50442. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50443. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50444. };
  50445. /**
  50446. * Interpolates a Color3 linearly
  50447. * @param startValue Start value of the animation curve
  50448. * @param endValue End value of the animation curve
  50449. * @param gradient Scalar amount to interpolate
  50450. * @returns Interpolated Color3 value
  50451. */
  50452. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50453. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50454. };
  50455. /**
  50456. * @hidden Internal use only
  50457. */
  50458. Animation.prototype._getKeyValue = function (value) {
  50459. if (typeof value === "function") {
  50460. return value();
  50461. }
  50462. return value;
  50463. };
  50464. /**
  50465. * @hidden Internal use only
  50466. */
  50467. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50468. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50469. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50470. }
  50471. var keys = this.getKeys();
  50472. // Try to get a hash to find the right key
  50473. 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));
  50474. if (keys[startKeyIndex].frame >= currentFrame) {
  50475. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50476. startKeyIndex--;
  50477. }
  50478. }
  50479. for (var key = startKeyIndex; key < keys.length; key++) {
  50480. var endKey = keys[key + 1];
  50481. if (endKey.frame >= currentFrame) {
  50482. var startKey = keys[key];
  50483. var startValue = this._getKeyValue(startKey.value);
  50484. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50485. return startValue;
  50486. }
  50487. var endValue = this._getKeyValue(endKey.value);
  50488. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50489. var frameDelta = endKey.frame - startKey.frame;
  50490. // gradient : percent of currentFrame between the frame inf and the frame sup
  50491. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50492. // check for easingFunction and correction of gradient
  50493. var easingFunction = this.getEasingFunction();
  50494. if (easingFunction != null) {
  50495. gradient = easingFunction.ease(gradient);
  50496. }
  50497. switch (this.dataType) {
  50498. // Float
  50499. case Animation.ANIMATIONTYPE_FLOAT:
  50500. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50501. switch (loopMode) {
  50502. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50503. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50504. return floatValue;
  50505. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50506. return offsetValue * repeatCount + floatValue;
  50507. }
  50508. break;
  50509. // Quaternion
  50510. case Animation.ANIMATIONTYPE_QUATERNION:
  50511. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50512. switch (loopMode) {
  50513. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50514. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50515. return quatValue;
  50516. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50517. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50518. }
  50519. return quatValue;
  50520. // Vector3
  50521. case Animation.ANIMATIONTYPE_VECTOR3:
  50522. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50523. switch (loopMode) {
  50524. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50525. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50526. return vec3Value;
  50527. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50528. return vec3Value.add(offsetValue.scale(repeatCount));
  50529. }
  50530. // Vector2
  50531. case Animation.ANIMATIONTYPE_VECTOR2:
  50532. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50533. switch (loopMode) {
  50534. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50535. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50536. return vec2Value;
  50537. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50538. return vec2Value.add(offsetValue.scale(repeatCount));
  50539. }
  50540. // Size
  50541. case Animation.ANIMATIONTYPE_SIZE:
  50542. switch (loopMode) {
  50543. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50544. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50545. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50546. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50547. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50548. }
  50549. // Color3
  50550. case Animation.ANIMATIONTYPE_COLOR3:
  50551. switch (loopMode) {
  50552. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50553. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50554. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50555. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50556. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50557. }
  50558. // Matrix
  50559. case Animation.ANIMATIONTYPE_MATRIX:
  50560. switch (loopMode) {
  50561. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50562. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50563. if (Animation.AllowMatricesInterpolation) {
  50564. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50565. }
  50566. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50567. return startValue;
  50568. }
  50569. default:
  50570. break;
  50571. }
  50572. break;
  50573. }
  50574. }
  50575. return this._getKeyValue(keys[keys.length - 1].value);
  50576. };
  50577. /**
  50578. * Defines the function to use to interpolate matrices
  50579. * @param startValue defines the start matrix
  50580. * @param endValue defines the end matrix
  50581. * @param gradient defines the gradient between both matrices
  50582. * @param result defines an optional target matrix where to store the interpolation
  50583. * @returns the interpolated matrix
  50584. */
  50585. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50586. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50587. if (result) {
  50588. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50589. return result;
  50590. }
  50591. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50592. }
  50593. if (result) {
  50594. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50595. return result;
  50596. }
  50597. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50598. };
  50599. /**
  50600. * Makes a copy of the animation
  50601. * @returns Cloned animation
  50602. */
  50603. Animation.prototype.clone = function () {
  50604. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50605. clone.enableBlending = this.enableBlending;
  50606. clone.blendingSpeed = this.blendingSpeed;
  50607. if (this._keys) {
  50608. clone.setKeys(this._keys);
  50609. }
  50610. if (this._ranges) {
  50611. clone._ranges = {};
  50612. for (var name in this._ranges) {
  50613. var range = this._ranges[name];
  50614. if (!range) {
  50615. continue;
  50616. }
  50617. clone._ranges[name] = range.clone();
  50618. }
  50619. }
  50620. return clone;
  50621. };
  50622. /**
  50623. * Sets the key frames of the animation
  50624. * @param values The animation key frames to set
  50625. */
  50626. Animation.prototype.setKeys = function (values) {
  50627. this._keys = values.slice(0);
  50628. };
  50629. /**
  50630. * Serializes the animation to an object
  50631. * @returns Serialized object
  50632. */
  50633. Animation.prototype.serialize = function () {
  50634. var serializationObject = {};
  50635. serializationObject.name = this.name;
  50636. serializationObject.property = this.targetProperty;
  50637. serializationObject.framePerSecond = this.framePerSecond;
  50638. serializationObject.dataType = this.dataType;
  50639. serializationObject.loopBehavior = this.loopMode;
  50640. serializationObject.enableBlending = this.enableBlending;
  50641. serializationObject.blendingSpeed = this.blendingSpeed;
  50642. var dataType = this.dataType;
  50643. serializationObject.keys = [];
  50644. var keys = this.getKeys();
  50645. for (var index = 0; index < keys.length; index++) {
  50646. var animationKey = keys[index];
  50647. var key = {};
  50648. key.frame = animationKey.frame;
  50649. switch (dataType) {
  50650. case Animation.ANIMATIONTYPE_FLOAT:
  50651. key.values = [animationKey.value];
  50652. break;
  50653. case Animation.ANIMATIONTYPE_QUATERNION:
  50654. case Animation.ANIMATIONTYPE_MATRIX:
  50655. case Animation.ANIMATIONTYPE_VECTOR3:
  50656. case Animation.ANIMATIONTYPE_COLOR3:
  50657. key.values = animationKey.value.asArray();
  50658. break;
  50659. }
  50660. serializationObject.keys.push(key);
  50661. }
  50662. serializationObject.ranges = [];
  50663. for (var name in this._ranges) {
  50664. var source = this._ranges[name];
  50665. if (!source) {
  50666. continue;
  50667. }
  50668. var range = {};
  50669. range.name = name;
  50670. range.from = source.from;
  50671. range.to = source.to;
  50672. serializationObject.ranges.push(range);
  50673. }
  50674. return serializationObject;
  50675. };
  50676. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50677. /**
  50678. * Get the float animation type
  50679. */
  50680. get: function () {
  50681. return Animation._ANIMATIONTYPE_FLOAT;
  50682. },
  50683. enumerable: true,
  50684. configurable: true
  50685. });
  50686. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50687. /**
  50688. * Get the Vector3 animation type
  50689. */
  50690. get: function () {
  50691. return Animation._ANIMATIONTYPE_VECTOR3;
  50692. },
  50693. enumerable: true,
  50694. configurable: true
  50695. });
  50696. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50697. /**
  50698. * Get the Vector2 animation type
  50699. */
  50700. get: function () {
  50701. return Animation._ANIMATIONTYPE_VECTOR2;
  50702. },
  50703. enumerable: true,
  50704. configurable: true
  50705. });
  50706. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50707. /**
  50708. * Get the Size animation type
  50709. */
  50710. get: function () {
  50711. return Animation._ANIMATIONTYPE_SIZE;
  50712. },
  50713. enumerable: true,
  50714. configurable: true
  50715. });
  50716. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50717. /**
  50718. * Get the Quaternion animation type
  50719. */
  50720. get: function () {
  50721. return Animation._ANIMATIONTYPE_QUATERNION;
  50722. },
  50723. enumerable: true,
  50724. configurable: true
  50725. });
  50726. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50727. /**
  50728. * Get the Matrix animation type
  50729. */
  50730. get: function () {
  50731. return Animation._ANIMATIONTYPE_MATRIX;
  50732. },
  50733. enumerable: true,
  50734. configurable: true
  50735. });
  50736. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50737. /**
  50738. * Get the Color3 animation type
  50739. */
  50740. get: function () {
  50741. return Animation._ANIMATIONTYPE_COLOR3;
  50742. },
  50743. enumerable: true,
  50744. configurable: true
  50745. });
  50746. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50747. /**
  50748. * Get the Relative Loop Mode
  50749. */
  50750. get: function () {
  50751. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50752. },
  50753. enumerable: true,
  50754. configurable: true
  50755. });
  50756. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50757. /**
  50758. * Get the Cycle Loop Mode
  50759. */
  50760. get: function () {
  50761. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50762. },
  50763. enumerable: true,
  50764. configurable: true
  50765. });
  50766. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50767. /**
  50768. * Get the Constant Loop Mode
  50769. */
  50770. get: function () {
  50771. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50772. },
  50773. enumerable: true,
  50774. configurable: true
  50775. });
  50776. /** @hidden */
  50777. Animation._UniversalLerp = function (left, right, amount) {
  50778. var constructor = left.constructor;
  50779. if (constructor.Lerp) { // Lerp supported
  50780. return constructor.Lerp(left, right, amount);
  50781. }
  50782. else if (constructor.Slerp) { // Slerp supported
  50783. return constructor.Slerp(left, right, amount);
  50784. }
  50785. else if (left.toFixed) { // Number
  50786. return left * (1.0 - amount) + amount * right;
  50787. }
  50788. else { // Blending not supported
  50789. return right;
  50790. }
  50791. };
  50792. /**
  50793. * Parses an animation object and creates an animation
  50794. * @param parsedAnimation Parsed animation object
  50795. * @returns Animation object
  50796. */
  50797. Animation.Parse = function (parsedAnimation) {
  50798. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50799. var dataType = parsedAnimation.dataType;
  50800. var keys = [];
  50801. var data;
  50802. var index;
  50803. if (parsedAnimation.enableBlending) {
  50804. animation.enableBlending = parsedAnimation.enableBlending;
  50805. }
  50806. if (parsedAnimation.blendingSpeed) {
  50807. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50808. }
  50809. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50810. var key = parsedAnimation.keys[index];
  50811. var inTangent;
  50812. var outTangent;
  50813. switch (dataType) {
  50814. case Animation.ANIMATIONTYPE_FLOAT:
  50815. data = key.values[0];
  50816. if (key.values.length >= 1) {
  50817. inTangent = key.values[1];
  50818. }
  50819. if (key.values.length >= 2) {
  50820. outTangent = key.values[2];
  50821. }
  50822. break;
  50823. case Animation.ANIMATIONTYPE_QUATERNION:
  50824. data = BABYLON.Quaternion.FromArray(key.values);
  50825. if (key.values.length >= 8) {
  50826. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50827. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50828. inTangent = _inTangent;
  50829. }
  50830. }
  50831. if (key.values.length >= 12) {
  50832. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50833. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50834. outTangent = _outTangent;
  50835. }
  50836. }
  50837. break;
  50838. case Animation.ANIMATIONTYPE_MATRIX:
  50839. data = BABYLON.Matrix.FromArray(key.values);
  50840. break;
  50841. case Animation.ANIMATIONTYPE_COLOR3:
  50842. data = BABYLON.Color3.FromArray(key.values);
  50843. break;
  50844. case Animation.ANIMATIONTYPE_VECTOR3:
  50845. default:
  50846. data = BABYLON.Vector3.FromArray(key.values);
  50847. break;
  50848. }
  50849. var keyData = {};
  50850. keyData.frame = key.frame;
  50851. keyData.value = data;
  50852. if (inTangent != undefined) {
  50853. keyData.inTangent = inTangent;
  50854. }
  50855. if (outTangent != undefined) {
  50856. keyData.outTangent = outTangent;
  50857. }
  50858. keys.push(keyData);
  50859. }
  50860. animation.setKeys(keys);
  50861. if (parsedAnimation.ranges) {
  50862. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50863. data = parsedAnimation.ranges[index];
  50864. animation.createRange(data.name, data.from, data.to);
  50865. }
  50866. }
  50867. return animation;
  50868. };
  50869. /**
  50870. * Appends the serialized animations from the source animations
  50871. * @param source Source containing the animations
  50872. * @param destination Target to store the animations
  50873. */
  50874. Animation.AppendSerializedAnimations = function (source, destination) {
  50875. if (source.animations) {
  50876. destination.animations = [];
  50877. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50878. var animation = source.animations[animationIndex];
  50879. destination.animations.push(animation.serialize());
  50880. }
  50881. }
  50882. };
  50883. /**
  50884. * Use matrix interpolation instead of using direct key value when animating matrices
  50885. */
  50886. Animation.AllowMatricesInterpolation = false;
  50887. /**
  50888. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50889. */
  50890. Animation.AllowMatrixDecomposeForInterpolation = true;
  50891. // Statics
  50892. /**
  50893. * Float animation type
  50894. */
  50895. Animation._ANIMATIONTYPE_FLOAT = 0;
  50896. /**
  50897. * Vector3 animation type
  50898. */
  50899. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50900. /**
  50901. * Quaternion animation type
  50902. */
  50903. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50904. /**
  50905. * Matrix animation type
  50906. */
  50907. Animation._ANIMATIONTYPE_MATRIX = 3;
  50908. /**
  50909. * Color3 animation type
  50910. */
  50911. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50912. /**
  50913. * Vector2 animation type
  50914. */
  50915. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50916. /**
  50917. * Size animation type
  50918. */
  50919. Animation._ANIMATIONTYPE_SIZE = 6;
  50920. /**
  50921. * Relative Loop Mode
  50922. */
  50923. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50924. /**
  50925. * Cycle Loop Mode
  50926. */
  50927. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50928. /**
  50929. * Constant Loop Mode
  50930. */
  50931. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50932. return Animation;
  50933. }());
  50934. BABYLON.Animation = Animation;
  50935. })(BABYLON || (BABYLON = {}));
  50936. //# sourceMappingURL=babylon.animation.js.map
  50937. var BABYLON;
  50938. (function (BABYLON) {
  50939. /**
  50940. * This class defines the direct association between an animation and a target
  50941. */
  50942. var TargetedAnimation = /** @class */ (function () {
  50943. function TargetedAnimation() {
  50944. }
  50945. return TargetedAnimation;
  50946. }());
  50947. BABYLON.TargetedAnimation = TargetedAnimation;
  50948. /**
  50949. * Use this class to create coordinated animations on multiple targets
  50950. */
  50951. var AnimationGroup = /** @class */ (function () {
  50952. function AnimationGroup(name, scene) {
  50953. if (scene === void 0) { scene = null; }
  50954. this.name = name;
  50955. this._targetedAnimations = new Array();
  50956. this._animatables = new Array();
  50957. this._from = Number.MAX_VALUE;
  50958. this._to = -Number.MAX_VALUE;
  50959. this._speedRatio = 1;
  50960. this.onAnimationEndObservable = new BABYLON.Observable();
  50961. /**
  50962. * This observable will notify when all animations have ended.
  50963. */
  50964. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50965. /**
  50966. * This observable will notify when all animations have paused.
  50967. */
  50968. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  50969. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50970. this._scene.animationGroups.push(this);
  50971. }
  50972. Object.defineProperty(AnimationGroup.prototype, "from", {
  50973. /**
  50974. * Gets the first frame
  50975. */
  50976. get: function () {
  50977. return this._from;
  50978. },
  50979. enumerable: true,
  50980. configurable: true
  50981. });
  50982. Object.defineProperty(AnimationGroup.prototype, "to", {
  50983. /**
  50984. * Gets the last frame
  50985. */
  50986. get: function () {
  50987. return this._to;
  50988. },
  50989. enumerable: true,
  50990. configurable: true
  50991. });
  50992. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50993. /**
  50994. * Define if the animations are started
  50995. */
  50996. get: function () {
  50997. return this._isStarted;
  50998. },
  50999. enumerable: true,
  51000. configurable: true
  51001. });
  51002. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51003. /**
  51004. * Gets or sets the speed ratio to use for all animations
  51005. */
  51006. get: function () {
  51007. return this._speedRatio;
  51008. },
  51009. /**
  51010. * Gets or sets the speed ratio to use for all animations
  51011. */
  51012. set: function (value) {
  51013. if (this._speedRatio === value) {
  51014. return;
  51015. }
  51016. this._speedRatio = value;
  51017. for (var index = 0; index < this._animatables.length; index++) {
  51018. var animatable = this._animatables[index];
  51019. animatable.speedRatio = this._speedRatio;
  51020. }
  51021. },
  51022. enumerable: true,
  51023. configurable: true
  51024. });
  51025. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51026. /**
  51027. * Gets the targeted animations for this animation group
  51028. */
  51029. get: function () {
  51030. return this._targetedAnimations;
  51031. },
  51032. enumerable: true,
  51033. configurable: true
  51034. });
  51035. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51036. /**
  51037. * returning the list of animatables controlled by this animation group.
  51038. */
  51039. get: function () {
  51040. return this._animatables;
  51041. },
  51042. enumerable: true,
  51043. configurable: true
  51044. });
  51045. /**
  51046. * Add an animation (with its target) in the group
  51047. * @param animation defines the animation we want to add
  51048. * @param target defines the target of the animation
  51049. * @returns the {BABYLON.TargetedAnimation} object
  51050. */
  51051. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51052. var targetedAnimation = {
  51053. animation: animation,
  51054. target: target
  51055. };
  51056. var keys = animation.getKeys();
  51057. if (this._from > keys[0].frame) {
  51058. this._from = keys[0].frame;
  51059. }
  51060. if (this._to < keys[keys.length - 1].frame) {
  51061. this._to = keys[keys.length - 1].frame;
  51062. }
  51063. this._targetedAnimations.push(targetedAnimation);
  51064. return targetedAnimation;
  51065. };
  51066. /**
  51067. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51068. * It can add constant keys at begin or end
  51069. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  51070. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  51071. */
  51072. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51073. if (beginFrame === void 0) { beginFrame = null; }
  51074. if (endFrame === void 0) { endFrame = null; }
  51075. if (beginFrame == null)
  51076. beginFrame = this._from;
  51077. if (endFrame == null)
  51078. endFrame = this._to;
  51079. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51080. var targetedAnimation = this._targetedAnimations[index];
  51081. var keys = targetedAnimation.animation.getKeys();
  51082. var startKey = keys[0];
  51083. var endKey = keys[keys.length - 1];
  51084. if (startKey.frame > beginFrame) {
  51085. var newKey = {
  51086. frame: beginFrame,
  51087. value: startKey.value,
  51088. inTangent: startKey.inTangent,
  51089. outTangent: startKey.outTangent,
  51090. interpolation: startKey.interpolation
  51091. };
  51092. keys.splice(0, 0, newKey);
  51093. }
  51094. if (endKey.frame < endFrame) {
  51095. var newKey = {
  51096. frame: endFrame,
  51097. value: endKey.value,
  51098. inTangent: endKey.outTangent,
  51099. outTangent: endKey.outTangent,
  51100. interpolation: endKey.interpolation
  51101. };
  51102. keys.push(newKey);
  51103. }
  51104. }
  51105. this._from = beginFrame;
  51106. this._to = endFrame;
  51107. return this;
  51108. };
  51109. /**
  51110. * Start all animations on given targets
  51111. * @param loop defines if animations must loop
  51112. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51113. * @param from defines the from key (optional)
  51114. * @param to defines the to key (optional)
  51115. * @returns the current animation group
  51116. */
  51117. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51118. var _this = this;
  51119. if (loop === void 0) { loop = false; }
  51120. if (speedRatio === void 0) { speedRatio = 1; }
  51121. if (this._isStarted || this._targetedAnimations.length === 0) {
  51122. return this;
  51123. }
  51124. var _loop_1 = function (targetedAnimation) {
  51125. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  51126. animatable.onAnimationEnd = function () {
  51127. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51128. _this._checkAnimationGroupEnded(animatable);
  51129. };
  51130. this_1._animatables.push(animatable);
  51131. };
  51132. var this_1 = this;
  51133. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51134. var targetedAnimation = _a[_i];
  51135. _loop_1(targetedAnimation);
  51136. }
  51137. this._speedRatio = speedRatio;
  51138. this._isStarted = true;
  51139. return this;
  51140. };
  51141. /**
  51142. * Pause all animations
  51143. */
  51144. AnimationGroup.prototype.pause = function () {
  51145. if (!this._isStarted) {
  51146. return this;
  51147. }
  51148. for (var index = 0; index < this._animatables.length; index++) {
  51149. var animatable = this._animatables[index];
  51150. animatable.pause();
  51151. }
  51152. this.onAnimationGroupPauseObservable.notifyObservers(this);
  51153. return this;
  51154. };
  51155. /**
  51156. * Play all animations to initial state
  51157. * This function will start() the animations if they were not started or will restart() them if they were paused
  51158. * @param loop defines if animations must loop
  51159. */
  51160. AnimationGroup.prototype.play = function (loop) {
  51161. // only if all animatables are ready and exist
  51162. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  51163. if (loop !== undefined) {
  51164. for (var index = 0; index < this._animatables.length; index++) {
  51165. var animatable = this._animatables[index];
  51166. animatable.loopAnimation = loop;
  51167. }
  51168. }
  51169. this.restart();
  51170. }
  51171. else {
  51172. this.stop();
  51173. this.start(loop, this._speedRatio);
  51174. }
  51175. return this;
  51176. };
  51177. /**
  51178. * Reset all animations to initial state
  51179. */
  51180. AnimationGroup.prototype.reset = function () {
  51181. if (!this._isStarted) {
  51182. return this;
  51183. }
  51184. for (var index = 0; index < this._animatables.length; index++) {
  51185. var animatable = this._animatables[index];
  51186. animatable.reset();
  51187. }
  51188. return this;
  51189. };
  51190. /**
  51191. * Restart animations from key 0
  51192. */
  51193. AnimationGroup.prototype.restart = function () {
  51194. if (!this._isStarted) {
  51195. return this;
  51196. }
  51197. for (var index = 0; index < this._animatables.length; index++) {
  51198. var animatable = this._animatables[index];
  51199. animatable.restart();
  51200. }
  51201. return this;
  51202. };
  51203. /**
  51204. * Stop all animations
  51205. */
  51206. AnimationGroup.prototype.stop = function () {
  51207. if (!this._isStarted) {
  51208. return this;
  51209. }
  51210. var list = this._animatables.slice();
  51211. for (var index = 0; index < list.length; index++) {
  51212. list[index].stop();
  51213. }
  51214. this._isStarted = false;
  51215. return this;
  51216. };
  51217. /**
  51218. * Set animation weight for all animatables
  51219. * @param weight defines the weight to use
  51220. * @return the animationGroup
  51221. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51222. */
  51223. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51224. for (var index = 0; index < this._animatables.length; index++) {
  51225. var animatable = this._animatables[index];
  51226. animatable.weight = weight;
  51227. }
  51228. return this;
  51229. };
  51230. /**
  51231. * Synchronize and normalize all animatables with a source animatable
  51232. * @param root defines the root animatable to synchronize with
  51233. * @return the animationGroup
  51234. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51235. */
  51236. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51237. for (var index = 0; index < this._animatables.length; index++) {
  51238. var animatable = this._animatables[index];
  51239. animatable.syncWith(root);
  51240. }
  51241. return this;
  51242. };
  51243. /**
  51244. * Goes to a specific frame in this animation group
  51245. * @param frame the frame number to go to
  51246. * @return the animationGroup
  51247. */
  51248. AnimationGroup.prototype.goToFrame = function (frame) {
  51249. if (!this._isStarted) {
  51250. return this;
  51251. }
  51252. for (var index = 0; index < this._animatables.length; index++) {
  51253. var animatable = this._animatables[index];
  51254. animatable.goToFrame(frame);
  51255. }
  51256. return this;
  51257. };
  51258. /**
  51259. * Dispose all associated resources
  51260. */
  51261. AnimationGroup.prototype.dispose = function () {
  51262. this._targetedAnimations = [];
  51263. this._animatables = [];
  51264. var index = this._scene.animationGroups.indexOf(this);
  51265. if (index > -1) {
  51266. this._scene.animationGroups.splice(index, 1);
  51267. }
  51268. };
  51269. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  51270. // animatable should be taken out of the array
  51271. var idx = this._animatables.indexOf(animatable);
  51272. if (idx > -1) {
  51273. this._animatables.splice(idx, 1);
  51274. }
  51275. // all animatables were removed? animation group ended!
  51276. if (this._animatables.length === 0) {
  51277. this._isStarted = false;
  51278. this.onAnimationGroupEndObservable.notifyObservers(this);
  51279. }
  51280. };
  51281. return AnimationGroup;
  51282. }());
  51283. BABYLON.AnimationGroup = AnimationGroup;
  51284. })(BABYLON || (BABYLON = {}));
  51285. //# sourceMappingURL=babylon.animationGroup.js.map
  51286. var BABYLON;
  51287. (function (BABYLON) {
  51288. /**
  51289. * Defines a runtime animation
  51290. */
  51291. var RuntimeAnimation = /** @class */ (function () {
  51292. /**
  51293. * Create a new RuntimeAnimation object
  51294. * @param target defines the target of the animation
  51295. * @param animation defines the source animation object
  51296. * @param scene defines the hosting scene
  51297. * @param host defines the initiating Animatable
  51298. */
  51299. function RuntimeAnimation(target, animation, scene, host) {
  51300. var _this = this;
  51301. this._events = new Array();
  51302. /**
  51303. * The current frame of the runtime animation
  51304. */
  51305. this._currentFrame = 0;
  51306. /**
  51307. * The original value of the runtime animation
  51308. */
  51309. this._originalValue = new Array();
  51310. /**
  51311. * The offsets cache of the runtime animation
  51312. */
  51313. this._offsetsCache = {};
  51314. /**
  51315. * The high limits cache of the runtime animation
  51316. */
  51317. this._highLimitsCache = {};
  51318. /**
  51319. * Specifies if the runtime animation has been stopped
  51320. */
  51321. this._stopped = false;
  51322. /**
  51323. * The blending factor of the runtime animation
  51324. */
  51325. this._blendingFactor = 0;
  51326. /**
  51327. * The target path of the runtime animation
  51328. */
  51329. this._targetPath = "";
  51330. /**
  51331. * The weight of the runtime animation
  51332. */
  51333. this._weight = 1.0;
  51334. /**
  51335. * The ratio offset of the runtime animation
  51336. */
  51337. this._ratioOffset = 0;
  51338. /**
  51339. * The previous delay of the runtime animation
  51340. */
  51341. this._previousDelay = 0;
  51342. /**
  51343. * The previous ratio of the runtime animation
  51344. */
  51345. this._previousRatio = 0;
  51346. this._animation = animation;
  51347. this._target = target;
  51348. this._scene = scene;
  51349. this._host = host;
  51350. animation._runtimeAnimations.push(this);
  51351. // Cloning events locally
  51352. var events = animation.getEvents();
  51353. if (events && events.length > 0) {
  51354. events.forEach(function (e) {
  51355. _this._events.push(e._clone());
  51356. });
  51357. }
  51358. }
  51359. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51360. /**
  51361. * Gets the current frame of the runtime animation
  51362. */
  51363. get: function () {
  51364. return this._currentFrame;
  51365. },
  51366. enumerable: true,
  51367. configurable: true
  51368. });
  51369. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51370. /**
  51371. * Gets the weight of the runtime animation
  51372. */
  51373. get: function () {
  51374. return this._weight;
  51375. },
  51376. enumerable: true,
  51377. configurable: true
  51378. });
  51379. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51380. /**
  51381. * Gets the current value of the runtime animation
  51382. */
  51383. get: function () {
  51384. return this._currentValue;
  51385. },
  51386. enumerable: true,
  51387. configurable: true
  51388. });
  51389. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51390. /**
  51391. * Gets the target path of the runtime animation
  51392. */
  51393. get: function () {
  51394. return this._targetPath;
  51395. },
  51396. enumerable: true,
  51397. configurable: true
  51398. });
  51399. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51400. /**
  51401. * Gets the actual target of the runtime animation
  51402. */
  51403. get: function () {
  51404. return this._activeTarget;
  51405. },
  51406. enumerable: true,
  51407. configurable: true
  51408. });
  51409. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51410. /**
  51411. * Gets the animation from the runtime animation
  51412. */
  51413. get: function () {
  51414. return this._animation;
  51415. },
  51416. enumerable: true,
  51417. configurable: true
  51418. });
  51419. /**
  51420. * Resets the runtime animation to the beginning
  51421. * @param restoreOriginal defines whether to restore the target property to the original value
  51422. */
  51423. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  51424. if (restoreOriginal === void 0) { restoreOriginal = false; }
  51425. if (restoreOriginal) {
  51426. if (this._target instanceof Array) {
  51427. var index = 0;
  51428. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51429. var target = _a[_i];
  51430. if (this._originalValue[index] !== undefined) {
  51431. this._setValue(target, this._originalValue[index], -1);
  51432. }
  51433. index++;
  51434. }
  51435. }
  51436. else {
  51437. if (this._originalValue[0] !== undefined) {
  51438. this._setValue(this._target, this._originalValue[0], -1);
  51439. }
  51440. }
  51441. }
  51442. this._offsetsCache = {};
  51443. this._highLimitsCache = {};
  51444. this._currentFrame = 0;
  51445. this._blendingFactor = 0;
  51446. this._originalValue = new Array();
  51447. // Events
  51448. for (var index = 0; index < this._events.length; index++) {
  51449. this._events[index].isDone = false;
  51450. }
  51451. };
  51452. /**
  51453. * Specifies if the runtime animation is stopped
  51454. * @returns Boolean specifying if the runtime animation is stopped
  51455. */
  51456. RuntimeAnimation.prototype.isStopped = function () {
  51457. return this._stopped;
  51458. };
  51459. /**
  51460. * Disposes of the runtime animation
  51461. */
  51462. RuntimeAnimation.prototype.dispose = function () {
  51463. var index = this._animation.runtimeAnimations.indexOf(this);
  51464. if (index > -1) {
  51465. this._animation.runtimeAnimations.splice(index, 1);
  51466. }
  51467. };
  51468. /**
  51469. * Interpolates the animation from the current frame
  51470. * @param currentFrame The frame to interpolate the animation to
  51471. * @param repeatCount The number of times that the animation should loop
  51472. * @param loopMode The type of looping mode to use
  51473. * @param offsetValue Animation offset value
  51474. * @param highLimitValue The high limit value
  51475. * @returns The interpolated value
  51476. */
  51477. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51478. this._currentFrame = currentFrame;
  51479. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51480. this._workValue = BABYLON.Matrix.Zero();
  51481. }
  51482. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51483. };
  51484. /**
  51485. * Apply the interpolated value to the target
  51486. * @param currentValue defines the value computed by the animation
  51487. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  51488. */
  51489. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51490. if (weight === void 0) { weight = 1.0; }
  51491. if (this._target instanceof Array) {
  51492. var index = 0;
  51493. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51494. var target = _a[_i];
  51495. this._setValue(target, currentValue, weight, index);
  51496. index++;
  51497. }
  51498. }
  51499. else {
  51500. this._setValue(this._target, currentValue, weight);
  51501. }
  51502. };
  51503. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  51504. if (targetIndex === void 0) { targetIndex = 0; }
  51505. // Set value
  51506. var path;
  51507. var destination;
  51508. var targetPropertyPath = this._animation.targetPropertyPath;
  51509. if (targetPropertyPath.length > 1) {
  51510. var property = target[targetPropertyPath[0]];
  51511. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51512. property = property[targetPropertyPath[index]];
  51513. }
  51514. path = targetPropertyPath[targetPropertyPath.length - 1];
  51515. destination = property;
  51516. }
  51517. else {
  51518. path = targetPropertyPath[0];
  51519. destination = target;
  51520. }
  51521. this._targetPath = path;
  51522. this._activeTarget = destination;
  51523. this._weight = weight;
  51524. if (this._originalValue[targetIndex] === undefined) {
  51525. var originalValue = void 0;
  51526. if (destination.getRestPose && path === "_matrix") { // For bones
  51527. originalValue = destination.getRestPose();
  51528. }
  51529. else {
  51530. originalValue = destination[path];
  51531. }
  51532. if (originalValue && originalValue.clone) {
  51533. this._originalValue[targetIndex] = originalValue.clone();
  51534. }
  51535. else {
  51536. this._originalValue[targetIndex] = originalValue;
  51537. }
  51538. }
  51539. // Blending
  51540. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51541. if (enableBlending && this._blendingFactor <= 1.0) {
  51542. if (!this._originalBlendValue) {
  51543. var originalValue = destination[path];
  51544. if (originalValue.clone) {
  51545. this._originalBlendValue = originalValue.clone();
  51546. }
  51547. else {
  51548. this._originalBlendValue = originalValue;
  51549. }
  51550. }
  51551. if (this._originalBlendValue.m) { // Matrix
  51552. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51553. if (this._currentValue) {
  51554. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51555. }
  51556. else {
  51557. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51558. }
  51559. }
  51560. else {
  51561. if (this._currentValue) {
  51562. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51563. }
  51564. else {
  51565. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51566. }
  51567. }
  51568. }
  51569. else {
  51570. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51571. }
  51572. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51573. this._blendingFactor += blendingSpeed;
  51574. }
  51575. else {
  51576. this._currentValue = currentValue;
  51577. }
  51578. if (weight !== -1.0) {
  51579. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51580. }
  51581. else {
  51582. destination[path] = this._currentValue;
  51583. }
  51584. if (target.markAsDirty) {
  51585. target.markAsDirty(this._animation.targetProperty);
  51586. }
  51587. };
  51588. /**
  51589. * Gets the loop pmode of the runtime animation
  51590. * @returns Loop Mode
  51591. */
  51592. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51593. if (this._target && this._target.animationPropertiesOverride) {
  51594. return this._target.animationPropertiesOverride.loopMode;
  51595. }
  51596. return this._animation.loopMode;
  51597. };
  51598. /**
  51599. * Move the current animation to a given frame
  51600. * @param frame defines the frame to move to
  51601. */
  51602. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51603. var keys = this._animation.getKeys();
  51604. if (frame < keys[0].frame) {
  51605. frame = keys[0].frame;
  51606. }
  51607. else if (frame > keys[keys.length - 1].frame) {
  51608. frame = keys[keys.length - 1].frame;
  51609. }
  51610. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51611. this.setValue(currentValue, -1);
  51612. };
  51613. /**
  51614. * @hidden Internal use only
  51615. */
  51616. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51617. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51618. this._ratioOffset = this._previousRatio - newRatio;
  51619. };
  51620. /**
  51621. * Execute the current animation
  51622. * @param delay defines the delay to add to the current frame
  51623. * @param from defines the lower bound of the animation range
  51624. * @param to defines the upper bound of the animation range
  51625. * @param loop defines if the current animation must loop
  51626. * @param speedRatio defines the current speed ratio
  51627. * @param weight defines the weight of the animation (default is -1 so no weight)
  51628. * @returns a boolean indicating if the animation is running
  51629. */
  51630. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51631. if (weight === void 0) { weight = -1.0; }
  51632. var targetPropertyPath = this._animation.targetPropertyPath;
  51633. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51634. this._stopped = true;
  51635. return false;
  51636. }
  51637. var returnValue = true;
  51638. var keys = this._animation.getKeys();
  51639. // Adding a start key at frame 0 if missing
  51640. if (keys[0].frame !== 0) {
  51641. var newKey = { frame: 0, value: keys[0].value };
  51642. keys.splice(0, 0, newKey);
  51643. }
  51644. // Adding a duplicate key when there is only one key at frame zero
  51645. else if (keys.length === 1) {
  51646. var newKey = { frame: 0.001, value: keys[0].value };
  51647. keys.push(newKey);
  51648. }
  51649. // Check limits
  51650. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51651. from = keys[0].frame;
  51652. }
  51653. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51654. to = keys[keys.length - 1].frame;
  51655. }
  51656. //to and from cannot be the same key
  51657. if (from === to) {
  51658. if (from > keys[0].frame) {
  51659. from--;
  51660. }
  51661. else if (to < keys[keys.length - 1].frame) {
  51662. to++;
  51663. }
  51664. }
  51665. // Compute ratio
  51666. var range = to - from;
  51667. var offsetValue;
  51668. // ratio represents the frame delta between from and to
  51669. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51670. var highLimitValue = 0;
  51671. this._previousDelay = delay;
  51672. this._previousRatio = ratio;
  51673. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  51674. returnValue = false;
  51675. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51676. }
  51677. else {
  51678. // Get max value if required
  51679. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51680. var keyOffset = to.toString() + from.toString();
  51681. if (!this._offsetsCache[keyOffset]) {
  51682. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51683. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51684. switch (this._animation.dataType) {
  51685. // Float
  51686. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51687. this._offsetsCache[keyOffset] = toValue - fromValue;
  51688. break;
  51689. // Quaternion
  51690. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51691. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51692. break;
  51693. // Vector3
  51694. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51695. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51696. // Vector2
  51697. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51698. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51699. // Size
  51700. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51701. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51702. // Color3
  51703. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51704. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51705. default:
  51706. break;
  51707. }
  51708. this._highLimitsCache[keyOffset] = toValue;
  51709. }
  51710. highLimitValue = this._highLimitsCache[keyOffset];
  51711. offsetValue = this._offsetsCache[keyOffset];
  51712. }
  51713. }
  51714. if (offsetValue === undefined) {
  51715. switch (this._animation.dataType) {
  51716. // Float
  51717. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51718. offsetValue = 0;
  51719. break;
  51720. // Quaternion
  51721. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51722. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51723. break;
  51724. // Vector3
  51725. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51726. offsetValue = BABYLON.Vector3.Zero();
  51727. break;
  51728. // Vector2
  51729. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51730. offsetValue = BABYLON.Vector2.Zero();
  51731. break;
  51732. // Size
  51733. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51734. offsetValue = BABYLON.Size.Zero();
  51735. break;
  51736. // Color3
  51737. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51738. offsetValue = BABYLON.Color3.Black();
  51739. }
  51740. }
  51741. // Compute value
  51742. var repeatCount = (ratio / range) >> 0;
  51743. var currentFrame = returnValue ? from + ratio % range : to;
  51744. // Need to normalize?
  51745. if (this._host && this._host.syncRoot) {
  51746. var syncRoot = this._host.syncRoot;
  51747. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51748. currentFrame = from + (to - from) * hostNormalizedFrame;
  51749. }
  51750. // Reset events if looping
  51751. var events = this._events;
  51752. if (range > 0 && this.currentFrame > currentFrame ||
  51753. range < 0 && this.currentFrame < currentFrame) {
  51754. // Need to reset animation events
  51755. for (var index = 0; index < events.length; index++) {
  51756. if (!events[index].onlyOnce) {
  51757. // reset event, the animation is looping
  51758. events[index].isDone = false;
  51759. }
  51760. }
  51761. }
  51762. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51763. // Set value
  51764. this.setValue(currentValue, weight);
  51765. // Check events
  51766. for (var index = 0; index < events.length; index++) {
  51767. // Make sure current frame has passed event frame and that event frame is within the current range
  51768. // Also, handle both forward and reverse animations
  51769. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51770. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51771. var event = events[index];
  51772. if (!event.isDone) {
  51773. // If event should be done only once, remove it.
  51774. if (event.onlyOnce) {
  51775. events.splice(index, 1);
  51776. index--;
  51777. }
  51778. event.isDone = true;
  51779. event.action(currentFrame);
  51780. } // Don't do anything if the event has already be done.
  51781. }
  51782. }
  51783. if (!returnValue) {
  51784. this._stopped = true;
  51785. }
  51786. return returnValue;
  51787. };
  51788. return RuntimeAnimation;
  51789. }());
  51790. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51791. })(BABYLON || (BABYLON = {}));
  51792. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51793. var BABYLON;
  51794. (function (BABYLON) {
  51795. /**
  51796. * Class used to store an actual running animation
  51797. */
  51798. var Animatable = /** @class */ (function () {
  51799. /**
  51800. * Creates a new Animatable
  51801. * @param scene defines the hosting scene
  51802. * @param target defines the target object
  51803. * @param fromFrame defines the starting frame number (default is 0)
  51804. * @param toFrame defines the ending frame number (default is 100)
  51805. * @param loopAnimation defines if the animation must loop (default is false)
  51806. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  51807. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  51808. * @param animations defines a group of animation to add to the new Animatable
  51809. */
  51810. function Animatable(scene,
  51811. /** defines the target object */
  51812. target,
  51813. /** defines the starting frame number (default is 0) */
  51814. fromFrame,
  51815. /** defines the ending frame number (default is 100) */
  51816. toFrame,
  51817. /** defines if the animation must loop (default is false) */
  51818. loopAnimation, speedRatio,
  51819. /** defines a callback to call when animation ends if it is not looping */
  51820. onAnimationEnd, animations) {
  51821. if (fromFrame === void 0) { fromFrame = 0; }
  51822. if (toFrame === void 0) { toFrame = 100; }
  51823. if (loopAnimation === void 0) { loopAnimation = false; }
  51824. if (speedRatio === void 0) { speedRatio = 1.0; }
  51825. this.target = target;
  51826. this.fromFrame = fromFrame;
  51827. this.toFrame = toFrame;
  51828. this.loopAnimation = loopAnimation;
  51829. this.onAnimationEnd = onAnimationEnd;
  51830. this._localDelayOffset = null;
  51831. this._pausedDelay = null;
  51832. this._runtimeAnimations = new Array();
  51833. this._paused = false;
  51834. this._speedRatio = 1;
  51835. this._weight = -1.0;
  51836. /**
  51837. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  51838. * This will only apply for non looping animation (default is true)
  51839. */
  51840. this.disposeOnEnd = true;
  51841. /**
  51842. * Gets a boolean indicating if the animation has started
  51843. */
  51844. this.animationStarted = false;
  51845. /**
  51846. * Observer raised when the animation ends
  51847. */
  51848. this.onAnimationEndObservable = new BABYLON.Observable();
  51849. this._scene = scene;
  51850. if (animations) {
  51851. this.appendAnimations(target, animations);
  51852. }
  51853. this._speedRatio = speedRatio;
  51854. scene._activeAnimatables.push(this);
  51855. }
  51856. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51857. /**
  51858. * Gets the root Animatable used to synchronize and normalize animations
  51859. */
  51860. get: function () {
  51861. return this._syncRoot;
  51862. },
  51863. enumerable: true,
  51864. configurable: true
  51865. });
  51866. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51867. /**
  51868. * Gets the current frame of the first RuntimeAnimation
  51869. * Used to synchronize Animatables
  51870. */
  51871. get: function () {
  51872. if (this._runtimeAnimations.length === 0) {
  51873. return 0;
  51874. }
  51875. return this._runtimeAnimations[0].currentFrame;
  51876. },
  51877. enumerable: true,
  51878. configurable: true
  51879. });
  51880. Object.defineProperty(Animatable.prototype, "weight", {
  51881. /**
  51882. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51883. */
  51884. get: function () {
  51885. return this._weight;
  51886. },
  51887. set: function (value) {
  51888. if (value === -1) { // -1 is ok and means no weight
  51889. this._weight = -1;
  51890. return;
  51891. }
  51892. // Else weight must be in [0, 1] range
  51893. this._weight = Math.min(Math.max(value, 0), 1.0);
  51894. },
  51895. enumerable: true,
  51896. configurable: true
  51897. });
  51898. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51899. /**
  51900. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51901. */
  51902. get: function () {
  51903. return this._speedRatio;
  51904. },
  51905. set: function (value) {
  51906. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51907. var animation = this._runtimeAnimations[index];
  51908. animation._prepareForSpeedRatioChange(value);
  51909. }
  51910. this._speedRatio = value;
  51911. },
  51912. enumerable: true,
  51913. configurable: true
  51914. });
  51915. // Methods
  51916. /**
  51917. * Synchronize and normalize current Animatable with a source Animatable
  51918. * This is useful when using animation weights and when animations are not of the same length
  51919. * @param root defines the root Animatable to synchronize with
  51920. * @returns the current Animatable
  51921. */
  51922. Animatable.prototype.syncWith = function (root) {
  51923. this._syncRoot = root;
  51924. if (root) {
  51925. // Make sure this animatable will animate after the root
  51926. var index = this._scene._activeAnimatables.indexOf(this);
  51927. if (index > -1) {
  51928. this._scene._activeAnimatables.splice(index, 1);
  51929. this._scene._activeAnimatables.push(this);
  51930. }
  51931. }
  51932. return this;
  51933. };
  51934. /**
  51935. * Gets the list of runtime animations
  51936. * @returns an array of RuntimeAnimation
  51937. */
  51938. Animatable.prototype.getAnimations = function () {
  51939. return this._runtimeAnimations;
  51940. };
  51941. /**
  51942. * Adds more animations to the current animatable
  51943. * @param target defines the target of the animations
  51944. * @param animations defines the new animations to add
  51945. */
  51946. Animatable.prototype.appendAnimations = function (target, animations) {
  51947. for (var index = 0; index < animations.length; index++) {
  51948. var animation = animations[index];
  51949. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51950. }
  51951. };
  51952. /**
  51953. * Gets the source animation for a specific property
  51954. * @param property defines the propertyu to look for
  51955. * @returns null or the source animation for the given property
  51956. */
  51957. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51958. var runtimeAnimations = this._runtimeAnimations;
  51959. for (var index = 0; index < runtimeAnimations.length; index++) {
  51960. if (runtimeAnimations[index].animation.targetProperty === property) {
  51961. return runtimeAnimations[index].animation;
  51962. }
  51963. }
  51964. return null;
  51965. };
  51966. /**
  51967. * Gets the runtime animation for a specific property
  51968. * @param property defines the propertyu to look for
  51969. * @returns null or the runtime animation for the given property
  51970. */
  51971. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51972. var runtimeAnimations = this._runtimeAnimations;
  51973. for (var index = 0; index < runtimeAnimations.length; index++) {
  51974. if (runtimeAnimations[index].animation.targetProperty === property) {
  51975. return runtimeAnimations[index];
  51976. }
  51977. }
  51978. return null;
  51979. };
  51980. /**
  51981. * Resets the animatable to its original state
  51982. */
  51983. Animatable.prototype.reset = function () {
  51984. var runtimeAnimations = this._runtimeAnimations;
  51985. for (var index = 0; index < runtimeAnimations.length; index++) {
  51986. runtimeAnimations[index].reset(true);
  51987. }
  51988. this._localDelayOffset = null;
  51989. this._pausedDelay = null;
  51990. };
  51991. /**
  51992. * Allows the animatable to blend with current running animations
  51993. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51994. * @param blendingSpeed defines the blending speed to use
  51995. */
  51996. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51997. var runtimeAnimations = this._runtimeAnimations;
  51998. for (var index = 0; index < runtimeAnimations.length; index++) {
  51999. runtimeAnimations[index].animation.enableBlending = true;
  52000. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52001. }
  52002. };
  52003. /**
  52004. * Disable animation blending
  52005. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  52006. */
  52007. Animatable.prototype.disableBlending = function () {
  52008. var runtimeAnimations = this._runtimeAnimations;
  52009. for (var index = 0; index < runtimeAnimations.length; index++) {
  52010. runtimeAnimations[index].animation.enableBlending = false;
  52011. }
  52012. };
  52013. /**
  52014. * Jump directly to a given frame
  52015. * @param frame defines the frame to jump to
  52016. */
  52017. Animatable.prototype.goToFrame = function (frame) {
  52018. var runtimeAnimations = this._runtimeAnimations;
  52019. if (runtimeAnimations[0]) {
  52020. var fps = runtimeAnimations[0].animation.framePerSecond;
  52021. var currentFrame = runtimeAnimations[0].currentFrame;
  52022. var adjustTime = frame - currentFrame;
  52023. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52024. if (this._localDelayOffset === null) {
  52025. this._localDelayOffset = 0;
  52026. }
  52027. this._localDelayOffset -= delay;
  52028. }
  52029. for (var index = 0; index < runtimeAnimations.length; index++) {
  52030. runtimeAnimations[index].goToFrame(frame);
  52031. }
  52032. };
  52033. /**
  52034. * Pause the animation
  52035. */
  52036. Animatable.prototype.pause = function () {
  52037. if (this._paused) {
  52038. return;
  52039. }
  52040. this._paused = true;
  52041. };
  52042. /**
  52043. * Restart the animation
  52044. */
  52045. Animatable.prototype.restart = function () {
  52046. this._paused = false;
  52047. };
  52048. Animatable.prototype._raiseOnAnimationEnd = function () {
  52049. if (this.onAnimationEnd) {
  52050. this.onAnimationEnd();
  52051. }
  52052. this.onAnimationEndObservable.notifyObservers(this);
  52053. };
  52054. /**
  52055. * Stop and delete the current animation
  52056. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  52057. * @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)
  52058. */
  52059. Animatable.prototype.stop = function (animationName, targetMask) {
  52060. if (animationName || targetMask) {
  52061. var idx = this._scene._activeAnimatables.indexOf(this);
  52062. if (idx > -1) {
  52063. var runtimeAnimations = this._runtimeAnimations;
  52064. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52065. var runtimeAnimation = runtimeAnimations[index];
  52066. if (animationName && runtimeAnimation.animation.name != animationName) {
  52067. continue;
  52068. }
  52069. if (targetMask && !targetMask(runtimeAnimation.target)) {
  52070. continue;
  52071. }
  52072. runtimeAnimation.dispose();
  52073. runtimeAnimations.splice(index, 1);
  52074. }
  52075. if (runtimeAnimations.length == 0) {
  52076. this._scene._activeAnimatables.splice(idx, 1);
  52077. this._raiseOnAnimationEnd();
  52078. }
  52079. }
  52080. }
  52081. else {
  52082. var index = this._scene._activeAnimatables.indexOf(this);
  52083. if (index > -1) {
  52084. this._scene._activeAnimatables.splice(index, 1);
  52085. var runtimeAnimations = this._runtimeAnimations;
  52086. for (var index = 0; index < runtimeAnimations.length; index++) {
  52087. runtimeAnimations[index].dispose();
  52088. }
  52089. this._raiseOnAnimationEnd();
  52090. }
  52091. }
  52092. };
  52093. /**
  52094. * Wait asynchronously for the animation to end
  52095. * @returns a promise which will be fullfilled when the animation ends
  52096. */
  52097. Animatable.prototype.waitAsync = function () {
  52098. var _this = this;
  52099. return new Promise(function (resolve, reject) {
  52100. _this.onAnimationEndObservable.add(function () {
  52101. resolve(_this);
  52102. }, undefined, undefined, _this, true);
  52103. });
  52104. };
  52105. /** @hidden */
  52106. Animatable.prototype._animate = function (delay) {
  52107. if (this._paused) {
  52108. this.animationStarted = false;
  52109. if (this._pausedDelay === null) {
  52110. this._pausedDelay = delay;
  52111. }
  52112. return true;
  52113. }
  52114. if (this._localDelayOffset === null) {
  52115. this._localDelayOffset = delay;
  52116. this._pausedDelay = null;
  52117. }
  52118. else if (this._pausedDelay !== null) {
  52119. this._localDelayOffset += delay - this._pausedDelay;
  52120. this._pausedDelay = null;
  52121. }
  52122. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52123. return true;
  52124. }
  52125. // Animating
  52126. var running = false;
  52127. var runtimeAnimations = this._runtimeAnimations;
  52128. var index;
  52129. for (index = 0; index < runtimeAnimations.length; index++) {
  52130. var animation = runtimeAnimations[index];
  52131. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52132. running = running || isRunning;
  52133. }
  52134. this.animationStarted = running;
  52135. if (!running) {
  52136. if (this.disposeOnEnd) {
  52137. // Remove from active animatables
  52138. index = this._scene._activeAnimatables.indexOf(this);
  52139. this._scene._activeAnimatables.splice(index, 1);
  52140. // Dispose all runtime animations
  52141. for (index = 0; index < runtimeAnimations.length; index++) {
  52142. runtimeAnimations[index].dispose();
  52143. }
  52144. }
  52145. this._raiseOnAnimationEnd();
  52146. if (this.disposeOnEnd) {
  52147. this.onAnimationEnd = null;
  52148. this.onAnimationEndObservable.clear();
  52149. }
  52150. }
  52151. return running;
  52152. };
  52153. return Animatable;
  52154. }());
  52155. BABYLON.Animatable = Animatable;
  52156. })(BABYLON || (BABYLON = {}));
  52157. //# sourceMappingURL=babylon.animatable.js.map
  52158. var BABYLON;
  52159. (function (BABYLON) {
  52160. var EasingFunction = /** @class */ (function () {
  52161. function EasingFunction() {
  52162. // Properties
  52163. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52164. }
  52165. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  52166. get: function () {
  52167. return EasingFunction._EASINGMODE_EASEIN;
  52168. },
  52169. enumerable: true,
  52170. configurable: true
  52171. });
  52172. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  52173. get: function () {
  52174. return EasingFunction._EASINGMODE_EASEOUT;
  52175. },
  52176. enumerable: true,
  52177. configurable: true
  52178. });
  52179. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  52180. get: function () {
  52181. return EasingFunction._EASINGMODE_EASEINOUT;
  52182. },
  52183. enumerable: true,
  52184. configurable: true
  52185. });
  52186. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52187. var n = Math.min(Math.max(easingMode, 0), 2);
  52188. this._easingMode = n;
  52189. };
  52190. EasingFunction.prototype.getEasingMode = function () {
  52191. return this._easingMode;
  52192. };
  52193. EasingFunction.prototype.easeInCore = function (gradient) {
  52194. throw new Error('You must implement this method');
  52195. };
  52196. EasingFunction.prototype.ease = function (gradient) {
  52197. switch (this._easingMode) {
  52198. case EasingFunction.EASINGMODE_EASEIN:
  52199. return this.easeInCore(gradient);
  52200. case EasingFunction.EASINGMODE_EASEOUT:
  52201. return (1 - this.easeInCore(1 - gradient));
  52202. }
  52203. if (gradient >= 0.5) {
  52204. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52205. }
  52206. return (this.easeInCore(gradient * 2) * 0.5);
  52207. };
  52208. //Statics
  52209. EasingFunction._EASINGMODE_EASEIN = 0;
  52210. EasingFunction._EASINGMODE_EASEOUT = 1;
  52211. EasingFunction._EASINGMODE_EASEINOUT = 2;
  52212. return EasingFunction;
  52213. }());
  52214. BABYLON.EasingFunction = EasingFunction;
  52215. var CircleEase = /** @class */ (function (_super) {
  52216. __extends(CircleEase, _super);
  52217. function CircleEase() {
  52218. return _super !== null && _super.apply(this, arguments) || this;
  52219. }
  52220. CircleEase.prototype.easeInCore = function (gradient) {
  52221. gradient = Math.max(0, Math.min(1, gradient));
  52222. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52223. };
  52224. return CircleEase;
  52225. }(EasingFunction));
  52226. BABYLON.CircleEase = CircleEase;
  52227. var BackEase = /** @class */ (function (_super) {
  52228. __extends(BackEase, _super);
  52229. function BackEase(amplitude) {
  52230. if (amplitude === void 0) { amplitude = 1; }
  52231. var _this = _super.call(this) || this;
  52232. _this.amplitude = amplitude;
  52233. return _this;
  52234. }
  52235. BackEase.prototype.easeInCore = function (gradient) {
  52236. var num = Math.max(0, this.amplitude);
  52237. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52238. };
  52239. return BackEase;
  52240. }(EasingFunction));
  52241. BABYLON.BackEase = BackEase;
  52242. var BounceEase = /** @class */ (function (_super) {
  52243. __extends(BounceEase, _super);
  52244. function BounceEase(bounces, bounciness) {
  52245. if (bounces === void 0) { bounces = 3; }
  52246. if (bounciness === void 0) { bounciness = 2; }
  52247. var _this = _super.call(this) || this;
  52248. _this.bounces = bounces;
  52249. _this.bounciness = bounciness;
  52250. return _this;
  52251. }
  52252. BounceEase.prototype.easeInCore = function (gradient) {
  52253. var y = Math.max(0.0, this.bounces);
  52254. var bounciness = this.bounciness;
  52255. if (bounciness <= 1.0) {
  52256. bounciness = 1.001;
  52257. }
  52258. var num9 = Math.pow(bounciness, y);
  52259. var num5 = 1.0 - bounciness;
  52260. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52261. var num15 = gradient * num4;
  52262. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52263. var num3 = Math.floor(num65);
  52264. var num13 = num3 + 1.0;
  52265. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52266. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52267. var num7 = (num8 + num12) * 0.5;
  52268. var num6 = gradient - num7;
  52269. var num2 = num7 - num8;
  52270. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52271. };
  52272. return BounceEase;
  52273. }(EasingFunction));
  52274. BABYLON.BounceEase = BounceEase;
  52275. var CubicEase = /** @class */ (function (_super) {
  52276. __extends(CubicEase, _super);
  52277. function CubicEase() {
  52278. return _super !== null && _super.apply(this, arguments) || this;
  52279. }
  52280. CubicEase.prototype.easeInCore = function (gradient) {
  52281. return (gradient * gradient * gradient);
  52282. };
  52283. return CubicEase;
  52284. }(EasingFunction));
  52285. BABYLON.CubicEase = CubicEase;
  52286. var ElasticEase = /** @class */ (function (_super) {
  52287. __extends(ElasticEase, _super);
  52288. function ElasticEase(oscillations, springiness) {
  52289. if (oscillations === void 0) { oscillations = 3; }
  52290. if (springiness === void 0) { springiness = 3; }
  52291. var _this = _super.call(this) || this;
  52292. _this.oscillations = oscillations;
  52293. _this.springiness = springiness;
  52294. return _this;
  52295. }
  52296. ElasticEase.prototype.easeInCore = function (gradient) {
  52297. var num2;
  52298. var num3 = Math.max(0.0, this.oscillations);
  52299. var num = Math.max(0.0, this.springiness);
  52300. if (num == 0) {
  52301. num2 = gradient;
  52302. }
  52303. else {
  52304. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52305. }
  52306. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52307. };
  52308. return ElasticEase;
  52309. }(EasingFunction));
  52310. BABYLON.ElasticEase = ElasticEase;
  52311. var ExponentialEase = /** @class */ (function (_super) {
  52312. __extends(ExponentialEase, _super);
  52313. function ExponentialEase(exponent) {
  52314. if (exponent === void 0) { exponent = 2; }
  52315. var _this = _super.call(this) || this;
  52316. _this.exponent = exponent;
  52317. return _this;
  52318. }
  52319. ExponentialEase.prototype.easeInCore = function (gradient) {
  52320. if (this.exponent <= 0) {
  52321. return gradient;
  52322. }
  52323. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52324. };
  52325. return ExponentialEase;
  52326. }(EasingFunction));
  52327. BABYLON.ExponentialEase = ExponentialEase;
  52328. var PowerEase = /** @class */ (function (_super) {
  52329. __extends(PowerEase, _super);
  52330. function PowerEase(power) {
  52331. if (power === void 0) { power = 2; }
  52332. var _this = _super.call(this) || this;
  52333. _this.power = power;
  52334. return _this;
  52335. }
  52336. PowerEase.prototype.easeInCore = function (gradient) {
  52337. var y = Math.max(0.0, this.power);
  52338. return Math.pow(gradient, y);
  52339. };
  52340. return PowerEase;
  52341. }(EasingFunction));
  52342. BABYLON.PowerEase = PowerEase;
  52343. var QuadraticEase = /** @class */ (function (_super) {
  52344. __extends(QuadraticEase, _super);
  52345. function QuadraticEase() {
  52346. return _super !== null && _super.apply(this, arguments) || this;
  52347. }
  52348. QuadraticEase.prototype.easeInCore = function (gradient) {
  52349. return (gradient * gradient);
  52350. };
  52351. return QuadraticEase;
  52352. }(EasingFunction));
  52353. BABYLON.QuadraticEase = QuadraticEase;
  52354. var QuarticEase = /** @class */ (function (_super) {
  52355. __extends(QuarticEase, _super);
  52356. function QuarticEase() {
  52357. return _super !== null && _super.apply(this, arguments) || this;
  52358. }
  52359. QuarticEase.prototype.easeInCore = function (gradient) {
  52360. return (gradient * gradient * gradient * gradient);
  52361. };
  52362. return QuarticEase;
  52363. }(EasingFunction));
  52364. BABYLON.QuarticEase = QuarticEase;
  52365. var QuinticEase = /** @class */ (function (_super) {
  52366. __extends(QuinticEase, _super);
  52367. function QuinticEase() {
  52368. return _super !== null && _super.apply(this, arguments) || this;
  52369. }
  52370. QuinticEase.prototype.easeInCore = function (gradient) {
  52371. return (gradient * gradient * gradient * gradient * gradient);
  52372. };
  52373. return QuinticEase;
  52374. }(EasingFunction));
  52375. BABYLON.QuinticEase = QuinticEase;
  52376. var SineEase = /** @class */ (function (_super) {
  52377. __extends(SineEase, _super);
  52378. function SineEase() {
  52379. return _super !== null && _super.apply(this, arguments) || this;
  52380. }
  52381. SineEase.prototype.easeInCore = function (gradient) {
  52382. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52383. };
  52384. return SineEase;
  52385. }(EasingFunction));
  52386. BABYLON.SineEase = SineEase;
  52387. var BezierCurveEase = /** @class */ (function (_super) {
  52388. __extends(BezierCurveEase, _super);
  52389. function BezierCurveEase(x1, y1, x2, y2) {
  52390. if (x1 === void 0) { x1 = 0; }
  52391. if (y1 === void 0) { y1 = 0; }
  52392. if (x2 === void 0) { x2 = 1; }
  52393. if (y2 === void 0) { y2 = 1; }
  52394. var _this = _super.call(this) || this;
  52395. _this.x1 = x1;
  52396. _this.y1 = y1;
  52397. _this.x2 = x2;
  52398. _this.y2 = y2;
  52399. return _this;
  52400. }
  52401. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52402. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52403. };
  52404. return BezierCurveEase;
  52405. }(EasingFunction));
  52406. BABYLON.BezierCurveEase = BezierCurveEase;
  52407. })(BABYLON || (BABYLON = {}));
  52408. //# sourceMappingURL=babylon.easing.js.map
  52409. var BABYLON;
  52410. (function (BABYLON) {
  52411. /**
  52412. * A Condition applied to an Action
  52413. */
  52414. var Condition = /** @class */ (function () {
  52415. /**
  52416. * Creates a new Condition
  52417. * @param actionManager the manager of the action the condition is applied to
  52418. */
  52419. function Condition(actionManager) {
  52420. this._actionManager = actionManager;
  52421. }
  52422. /**
  52423. * Check if the current condition is valid
  52424. * @returns a boolean
  52425. */
  52426. Condition.prototype.isValid = function () {
  52427. return true;
  52428. };
  52429. /**
  52430. * Internal only
  52431. * @hidden
  52432. */
  52433. Condition.prototype._getProperty = function (propertyPath) {
  52434. return this._actionManager._getProperty(propertyPath);
  52435. };
  52436. /**
  52437. * Internal only
  52438. * @hidden
  52439. */
  52440. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52441. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52442. };
  52443. /**
  52444. * Serialize placeholder for child classes
  52445. * @returns the serialized object
  52446. */
  52447. Condition.prototype.serialize = function () {
  52448. };
  52449. /**
  52450. * Internal only
  52451. * @hidden
  52452. */
  52453. Condition.prototype._serialize = function (serializedCondition) {
  52454. return {
  52455. type: 2,
  52456. children: [],
  52457. name: serializedCondition.name,
  52458. properties: serializedCondition.properties
  52459. };
  52460. };
  52461. return Condition;
  52462. }());
  52463. BABYLON.Condition = Condition;
  52464. /**
  52465. * Defines specific conditional operators as extensions of Condition
  52466. */
  52467. var ValueCondition = /** @class */ (function (_super) {
  52468. __extends(ValueCondition, _super);
  52469. /**
  52470. * Creates a new ValueCondition
  52471. * @param actionManager manager for the action the condition applies to
  52472. * @param target for the action
  52473. * @param propertyPath path to specify the property of the target the conditional operator uses
  52474. * @param value the value compared by the conditional operator against the current value of the property
  52475. * @param operator the conditional operator, default ValueCondition.IsEqual
  52476. */
  52477. function ValueCondition(actionManager, target,
  52478. /** path to specify the property of the target the conditional operator uses */
  52479. propertyPath,
  52480. /** the value compared by the conditional operator against the current value of the property */
  52481. value,
  52482. /** the conditional operator, default ValueCondition.IsEqual */
  52483. operator) {
  52484. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52485. var _this = _super.call(this, actionManager) || this;
  52486. _this.propertyPath = propertyPath;
  52487. _this.value = value;
  52488. _this.operator = operator;
  52489. _this._target = target;
  52490. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52491. _this._property = _this._getProperty(_this.propertyPath);
  52492. return _this;
  52493. }
  52494. Object.defineProperty(ValueCondition, "IsEqual", {
  52495. /**
  52496. * returns the number for IsEqual
  52497. */
  52498. get: function () {
  52499. return ValueCondition._IsEqual;
  52500. },
  52501. enumerable: true,
  52502. configurable: true
  52503. });
  52504. Object.defineProperty(ValueCondition, "IsDifferent", {
  52505. /**
  52506. * Returns the number for IsDifferent
  52507. */
  52508. get: function () {
  52509. return ValueCondition._IsDifferent;
  52510. },
  52511. enumerable: true,
  52512. configurable: true
  52513. });
  52514. Object.defineProperty(ValueCondition, "IsGreater", {
  52515. /**
  52516. * Returns the number for IsGreater
  52517. */
  52518. get: function () {
  52519. return ValueCondition._IsGreater;
  52520. },
  52521. enumerable: true,
  52522. configurable: true
  52523. });
  52524. Object.defineProperty(ValueCondition, "IsLesser", {
  52525. /**
  52526. * Returns the number for IsLesser
  52527. */
  52528. get: function () {
  52529. return ValueCondition._IsLesser;
  52530. },
  52531. enumerable: true,
  52532. configurable: true
  52533. });
  52534. /**
  52535. * Compares the given value with the property value for the specified conditional operator
  52536. * @returns the result of the comparison
  52537. */
  52538. ValueCondition.prototype.isValid = function () {
  52539. switch (this.operator) {
  52540. case ValueCondition.IsGreater:
  52541. return this._effectiveTarget[this._property] > this.value;
  52542. case ValueCondition.IsLesser:
  52543. return this._effectiveTarget[this._property] < this.value;
  52544. case ValueCondition.IsEqual:
  52545. case ValueCondition.IsDifferent:
  52546. var check;
  52547. if (this.value.equals) {
  52548. check = this.value.equals(this._effectiveTarget[this._property]);
  52549. }
  52550. else {
  52551. check = this.value === this._effectiveTarget[this._property];
  52552. }
  52553. return this.operator === ValueCondition.IsEqual ? check : !check;
  52554. }
  52555. return false;
  52556. };
  52557. /**
  52558. * Serialize the ValueCondition into a JSON compatible object
  52559. * @returns serialization object
  52560. */
  52561. ValueCondition.prototype.serialize = function () {
  52562. return this._serialize({
  52563. name: "ValueCondition",
  52564. properties: [
  52565. BABYLON.Action._GetTargetProperty(this._target),
  52566. { name: "propertyPath", value: this.propertyPath },
  52567. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52568. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52569. ]
  52570. });
  52571. };
  52572. /**
  52573. * Gets the name of the conditional operator for the ValueCondition
  52574. * @param operator the conditional operator
  52575. * @returns the name
  52576. */
  52577. ValueCondition.GetOperatorName = function (operator) {
  52578. switch (operator) {
  52579. case ValueCondition._IsEqual: return "IsEqual";
  52580. case ValueCondition._IsDifferent: return "IsDifferent";
  52581. case ValueCondition._IsGreater: return "IsGreater";
  52582. case ValueCondition._IsLesser: return "IsLesser";
  52583. default: return "";
  52584. }
  52585. };
  52586. /**
  52587. * Internal only
  52588. * @hidden
  52589. */
  52590. ValueCondition._IsEqual = 0;
  52591. /**
  52592. * Internal only
  52593. * @hidden
  52594. */
  52595. ValueCondition._IsDifferent = 1;
  52596. /**
  52597. * Internal only
  52598. * @hidden
  52599. */
  52600. ValueCondition._IsGreater = 2;
  52601. /**
  52602. * Internal only
  52603. * @hidden
  52604. */
  52605. ValueCondition._IsLesser = 3;
  52606. return ValueCondition;
  52607. }(Condition));
  52608. BABYLON.ValueCondition = ValueCondition;
  52609. /**
  52610. * Defines a predicate condition as an extension of Condition
  52611. */
  52612. var PredicateCondition = /** @class */ (function (_super) {
  52613. __extends(PredicateCondition, _super);
  52614. /**
  52615. * Creates a new PredicateCondition
  52616. * @param actionManager manager for the action the condition applies to
  52617. * @param predicate defines the predicate function used to validate the condition
  52618. */
  52619. function PredicateCondition(actionManager,
  52620. /** defines the predicate function used to validate the condition */
  52621. predicate) {
  52622. var _this = _super.call(this, actionManager) || this;
  52623. _this.predicate = predicate;
  52624. return _this;
  52625. }
  52626. /**
  52627. * @returns the validity of the predicate condition
  52628. */
  52629. PredicateCondition.prototype.isValid = function () {
  52630. return this.predicate();
  52631. };
  52632. return PredicateCondition;
  52633. }(Condition));
  52634. BABYLON.PredicateCondition = PredicateCondition;
  52635. /**
  52636. * Defines a state condition as an extension of Condition
  52637. */
  52638. var StateCondition = /** @class */ (function (_super) {
  52639. __extends(StateCondition, _super);
  52640. /**
  52641. * Creates a new StateCondition
  52642. * @param actionManager manager for the action the condition applies to
  52643. * @param target of the condition
  52644. * @param value to compare with target state
  52645. */
  52646. function StateCondition(actionManager, target, value) {
  52647. var _this = _super.call(this, actionManager) || this;
  52648. _this.value = value;
  52649. _this._target = target;
  52650. return _this;
  52651. }
  52652. /**
  52653. * @returns the validity of the state
  52654. */
  52655. StateCondition.prototype.isValid = function () {
  52656. return this._target.state === this.value;
  52657. };
  52658. /**
  52659. * Serialize the StateCondition into a JSON compatible object
  52660. * @returns serialization object
  52661. */
  52662. StateCondition.prototype.serialize = function () {
  52663. return this._serialize({
  52664. name: "StateCondition",
  52665. properties: [
  52666. BABYLON.Action._GetTargetProperty(this._target),
  52667. { name: "value", value: this.value }
  52668. ]
  52669. });
  52670. };
  52671. return StateCondition;
  52672. }(Condition));
  52673. BABYLON.StateCondition = StateCondition;
  52674. })(BABYLON || (BABYLON = {}));
  52675. //# sourceMappingURL=babylon.condition.js.map
  52676. var BABYLON;
  52677. (function (BABYLON) {
  52678. /**
  52679. * The action to be carried out following a trigger
  52680. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52681. */
  52682. var Action = /** @class */ (function () {
  52683. /**
  52684. * Creates a new Action
  52685. * @param triggerOptions the trigger, with or without parameters, for the action
  52686. * @param condition an optional determinant of action
  52687. */
  52688. function Action(
  52689. /** the trigger, with or without parameters, for the action */
  52690. triggerOptions, condition) {
  52691. this.triggerOptions = triggerOptions;
  52692. /**
  52693. * An event triggered prior to action being executed.
  52694. */
  52695. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52696. if (triggerOptions.parameter) {
  52697. this.trigger = triggerOptions.trigger;
  52698. this._triggerParameter = triggerOptions.parameter;
  52699. }
  52700. else {
  52701. this.trigger = triggerOptions;
  52702. }
  52703. this._nextActiveAction = this;
  52704. this._condition = condition;
  52705. }
  52706. /**
  52707. * Internal only
  52708. * @hidden
  52709. */
  52710. Action.prototype._prepare = function () {
  52711. };
  52712. /**
  52713. * Gets the trigger parameters
  52714. * @returns the trigger parameters
  52715. */
  52716. Action.prototype.getTriggerParameter = function () {
  52717. return this._triggerParameter;
  52718. };
  52719. /**
  52720. * Internal only - executes current action event
  52721. * @hidden
  52722. */
  52723. Action.prototype._executeCurrent = function (evt) {
  52724. if (this._nextActiveAction._condition) {
  52725. var condition = this._nextActiveAction._condition;
  52726. var currentRenderId = this._actionManager.getScene().getRenderId();
  52727. // We cache the current evaluation for the current frame
  52728. if (condition._evaluationId === currentRenderId) {
  52729. if (!condition._currentResult) {
  52730. return;
  52731. }
  52732. }
  52733. else {
  52734. condition._evaluationId = currentRenderId;
  52735. if (!condition.isValid()) {
  52736. condition._currentResult = false;
  52737. return;
  52738. }
  52739. condition._currentResult = true;
  52740. }
  52741. }
  52742. this.onBeforeExecuteObservable.notifyObservers(this);
  52743. this._nextActiveAction.execute(evt);
  52744. this.skipToNextActiveAction();
  52745. };
  52746. /**
  52747. * Execute placeholder for child classes
  52748. * @param evt optional action event
  52749. */
  52750. Action.prototype.execute = function (evt) {
  52751. };
  52752. /**
  52753. * Skips to next active action
  52754. */
  52755. Action.prototype.skipToNextActiveAction = function () {
  52756. if (this._nextActiveAction._child) {
  52757. if (!this._nextActiveAction._child._actionManager) {
  52758. this._nextActiveAction._child._actionManager = this._actionManager;
  52759. }
  52760. this._nextActiveAction = this._nextActiveAction._child;
  52761. }
  52762. else {
  52763. this._nextActiveAction = this;
  52764. }
  52765. };
  52766. /**
  52767. * Adds action to chain of actions, may be a DoNothingAction
  52768. * @param action defines the next action to execute
  52769. * @returns The action passed in
  52770. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52771. */
  52772. Action.prototype.then = function (action) {
  52773. this._child = action;
  52774. action._actionManager = this._actionManager;
  52775. action._prepare();
  52776. return action;
  52777. };
  52778. /**
  52779. * Internal only
  52780. * @hidden
  52781. */
  52782. Action.prototype._getProperty = function (propertyPath) {
  52783. return this._actionManager._getProperty(propertyPath);
  52784. };
  52785. /**
  52786. * Internal only
  52787. * @hidden
  52788. */
  52789. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52790. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52791. };
  52792. /**
  52793. * Serialize placeholder for child classes
  52794. * @param parent of child
  52795. * @returns the serialized object
  52796. */
  52797. Action.prototype.serialize = function (parent) {
  52798. };
  52799. /**
  52800. * Internal only called by serialize
  52801. * @hidden
  52802. */
  52803. Action.prototype._serialize = function (serializedAction, parent) {
  52804. var serializationObject = {
  52805. type: 1,
  52806. children: [],
  52807. name: serializedAction.name,
  52808. properties: serializedAction.properties || []
  52809. };
  52810. // Serialize child
  52811. if (this._child) {
  52812. this._child.serialize(serializationObject);
  52813. }
  52814. // Check if "this" has a condition
  52815. if (this._condition) {
  52816. var serializedCondition = this._condition.serialize();
  52817. serializedCondition.children.push(serializationObject);
  52818. if (parent) {
  52819. parent.children.push(serializedCondition);
  52820. }
  52821. return serializedCondition;
  52822. }
  52823. if (parent) {
  52824. parent.children.push(serializationObject);
  52825. }
  52826. return serializationObject;
  52827. };
  52828. /**
  52829. * Internal only
  52830. * @hidden
  52831. */
  52832. Action._SerializeValueAsString = function (value) {
  52833. if (typeof value === "number") {
  52834. return value.toString();
  52835. }
  52836. if (typeof value === "boolean") {
  52837. return value ? "true" : "false";
  52838. }
  52839. if (value instanceof BABYLON.Vector2) {
  52840. return value.x + ", " + value.y;
  52841. }
  52842. if (value instanceof BABYLON.Vector3) {
  52843. return value.x + ", " + value.y + ", " + value.z;
  52844. }
  52845. if (value instanceof BABYLON.Color3) {
  52846. return value.r + ", " + value.g + ", " + value.b;
  52847. }
  52848. if (value instanceof BABYLON.Color4) {
  52849. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52850. }
  52851. return value; // string
  52852. };
  52853. /**
  52854. * Internal only
  52855. * @hidden
  52856. */
  52857. Action._GetTargetProperty = function (target) {
  52858. return {
  52859. name: "target",
  52860. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52861. : target instanceof BABYLON.Light ? "LightProperties"
  52862. : target instanceof BABYLON.Camera ? "CameraProperties"
  52863. : "SceneProperties",
  52864. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52865. };
  52866. };
  52867. return Action;
  52868. }());
  52869. BABYLON.Action = Action;
  52870. })(BABYLON || (BABYLON = {}));
  52871. //# sourceMappingURL=babylon.action.js.map
  52872. var BABYLON;
  52873. (function (BABYLON) {
  52874. /**
  52875. * ActionEvent is the event being sent when an action is triggered.
  52876. */
  52877. var ActionEvent = /** @class */ (function () {
  52878. /**
  52879. * Creates a new ActionEvent
  52880. * @param source The mesh or sprite that triggered the action
  52881. * @param pointerX The X mouse cursor position at the time of the event
  52882. * @param pointerY The Y mouse cursor position at the time of the event
  52883. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52884. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52885. * @param additionalData additional data for the event
  52886. */
  52887. function ActionEvent(
  52888. /** The mesh or sprite that triggered the action */
  52889. source,
  52890. /** The X mouse cursor position at the time of the event */
  52891. pointerX,
  52892. /** The Y mouse cursor position at the time of the event */
  52893. pointerY,
  52894. /** The mesh that is currently pointed at (can be null) */
  52895. meshUnderPointer,
  52896. /** the original (browser) event that triggered the ActionEvent */
  52897. sourceEvent,
  52898. /** additional data for the event */
  52899. additionalData) {
  52900. this.source = source;
  52901. this.pointerX = pointerX;
  52902. this.pointerY = pointerY;
  52903. this.meshUnderPointer = meshUnderPointer;
  52904. this.sourceEvent = sourceEvent;
  52905. this.additionalData = additionalData;
  52906. }
  52907. /**
  52908. * Helper function to auto-create an ActionEvent from a source mesh.
  52909. * @param source The source mesh that triggered the event
  52910. * @param evt The original (browser) event
  52911. * @param additionalData additional data for the event
  52912. * @returns the new ActionEvent
  52913. */
  52914. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52915. var scene = source.getScene();
  52916. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52917. };
  52918. /**
  52919. * Helper function to auto-create an ActionEvent from a source sprite
  52920. * @param source The source sprite that triggered the event
  52921. * @param scene Scene associated with the sprite
  52922. * @param evt The original (browser) event
  52923. * @param additionalData additional data for the event
  52924. * @returns the new ActionEvent
  52925. */
  52926. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52927. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52928. };
  52929. /**
  52930. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52931. * @param scene the scene where the event occurred
  52932. * @param evt The original (browser) event
  52933. * @returns the new ActionEvent
  52934. */
  52935. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52936. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52937. };
  52938. /**
  52939. * Helper function to auto-create an ActionEvent from a primitive
  52940. * @param prim defines the target primitive
  52941. * @param pointerPos defines the pointer position
  52942. * @param evt The original (browser) event
  52943. * @param additionalData additional data for the event
  52944. * @returns the new ActionEvent
  52945. */
  52946. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52947. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52948. };
  52949. return ActionEvent;
  52950. }());
  52951. BABYLON.ActionEvent = ActionEvent;
  52952. /**
  52953. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52954. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52955. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52956. */
  52957. var ActionManager = /** @class */ (function () {
  52958. /**
  52959. * Creates a new action manager
  52960. * @param scene defines the hosting scene
  52961. */
  52962. function ActionManager(scene) {
  52963. // Members
  52964. /** Gets the list of actions */
  52965. this.actions = new Array();
  52966. /** Gets the cursor to use when hovering items */
  52967. this.hoverCursor = '';
  52968. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52969. scene.actionManagers.push(this);
  52970. }
  52971. Object.defineProperty(ActionManager, "NothingTrigger", {
  52972. /**
  52973. * Nothing
  52974. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52975. */
  52976. get: function () {
  52977. return ActionManager._NothingTrigger;
  52978. },
  52979. enumerable: true,
  52980. configurable: true
  52981. });
  52982. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52983. /**
  52984. * On pick
  52985. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52986. */
  52987. get: function () {
  52988. return ActionManager._OnPickTrigger;
  52989. },
  52990. enumerable: true,
  52991. configurable: true
  52992. });
  52993. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52994. /**
  52995. * On left pick
  52996. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52997. */
  52998. get: function () {
  52999. return ActionManager._OnLeftPickTrigger;
  53000. },
  53001. enumerable: true,
  53002. configurable: true
  53003. });
  53004. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  53005. /**
  53006. * On right pick
  53007. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53008. */
  53009. get: function () {
  53010. return ActionManager._OnRightPickTrigger;
  53011. },
  53012. enumerable: true,
  53013. configurable: true
  53014. });
  53015. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  53016. /**
  53017. * On center pick
  53018. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53019. */
  53020. get: function () {
  53021. return ActionManager._OnCenterPickTrigger;
  53022. },
  53023. enumerable: true,
  53024. configurable: true
  53025. });
  53026. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  53027. /**
  53028. * On pick down
  53029. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53030. */
  53031. get: function () {
  53032. return ActionManager._OnPickDownTrigger;
  53033. },
  53034. enumerable: true,
  53035. configurable: true
  53036. });
  53037. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  53038. /**
  53039. * On double pick
  53040. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53041. */
  53042. get: function () {
  53043. return ActionManager._OnDoublePickTrigger;
  53044. },
  53045. enumerable: true,
  53046. configurable: true
  53047. });
  53048. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  53049. /**
  53050. * On pick up
  53051. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53052. */
  53053. get: function () {
  53054. return ActionManager._OnPickUpTrigger;
  53055. },
  53056. enumerable: true,
  53057. configurable: true
  53058. });
  53059. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  53060. /**
  53061. * On pick out.
  53062. * This trigger will only be raised if you also declared a OnPickDown
  53063. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53064. */
  53065. get: function () {
  53066. return ActionManager._OnPickOutTrigger;
  53067. },
  53068. enumerable: true,
  53069. configurable: true
  53070. });
  53071. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  53072. /**
  53073. * On long press
  53074. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53075. */
  53076. get: function () {
  53077. return ActionManager._OnLongPressTrigger;
  53078. },
  53079. enumerable: true,
  53080. configurable: true
  53081. });
  53082. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  53083. /**
  53084. * On pointer over
  53085. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53086. */
  53087. get: function () {
  53088. return ActionManager._OnPointerOverTrigger;
  53089. },
  53090. enumerable: true,
  53091. configurable: true
  53092. });
  53093. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  53094. /**
  53095. * On pointer out
  53096. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53097. */
  53098. get: function () {
  53099. return ActionManager._OnPointerOutTrigger;
  53100. },
  53101. enumerable: true,
  53102. configurable: true
  53103. });
  53104. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  53105. /**
  53106. * On every frame
  53107. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53108. */
  53109. get: function () {
  53110. return ActionManager._OnEveryFrameTrigger;
  53111. },
  53112. enumerable: true,
  53113. configurable: true
  53114. });
  53115. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  53116. /**
  53117. * On intersection enter
  53118. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53119. */
  53120. get: function () {
  53121. return ActionManager._OnIntersectionEnterTrigger;
  53122. },
  53123. enumerable: true,
  53124. configurable: true
  53125. });
  53126. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  53127. /**
  53128. * On intersection exit
  53129. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53130. */
  53131. get: function () {
  53132. return ActionManager._OnIntersectionExitTrigger;
  53133. },
  53134. enumerable: true,
  53135. configurable: true
  53136. });
  53137. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  53138. /**
  53139. * On key down
  53140. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53141. */
  53142. get: function () {
  53143. return ActionManager._OnKeyDownTrigger;
  53144. },
  53145. enumerable: true,
  53146. configurable: true
  53147. });
  53148. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  53149. /**
  53150. * On key up
  53151. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53152. */
  53153. get: function () {
  53154. return ActionManager._OnKeyUpTrigger;
  53155. },
  53156. enumerable: true,
  53157. configurable: true
  53158. });
  53159. // Methods
  53160. /**
  53161. * Releases all associated resources
  53162. */
  53163. ActionManager.prototype.dispose = function () {
  53164. var index = this._scene.actionManagers.indexOf(this);
  53165. for (var i = 0; i < this.actions.length; i++) {
  53166. var action = this.actions[i];
  53167. ActionManager.Triggers[action.trigger]--;
  53168. if (ActionManager.Triggers[action.trigger] === 0) {
  53169. delete ActionManager.Triggers[action.trigger];
  53170. }
  53171. }
  53172. if (index > -1) {
  53173. this._scene.actionManagers.splice(index, 1);
  53174. }
  53175. };
  53176. /**
  53177. * Gets hosting scene
  53178. * @returns the hosting scene
  53179. */
  53180. ActionManager.prototype.getScene = function () {
  53181. return this._scene;
  53182. };
  53183. /**
  53184. * Does this action manager handles actions of any of the given triggers
  53185. * @param triggers defines the triggers to be tested
  53186. * @return a boolean indicating whether one (or more) of the triggers is handled
  53187. */
  53188. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53189. for (var index = 0; index < this.actions.length; index++) {
  53190. var action = this.actions[index];
  53191. if (triggers.indexOf(action.trigger) > -1) {
  53192. return true;
  53193. }
  53194. }
  53195. return false;
  53196. };
  53197. /**
  53198. * Does this action manager handles actions of a given trigger
  53199. * @param trigger defines the trigger to be tested
  53200. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53201. * @return whether the trigger is handled
  53202. */
  53203. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53204. for (var index = 0; index < this.actions.length; index++) {
  53205. var action = this.actions[index];
  53206. if (action.trigger === trigger) {
  53207. if (parameterPredicate) {
  53208. if (parameterPredicate(action.getTriggerParameter())) {
  53209. return true;
  53210. }
  53211. }
  53212. else {
  53213. return true;
  53214. }
  53215. }
  53216. }
  53217. return false;
  53218. };
  53219. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53220. /**
  53221. * Does this action manager has pointer triggers
  53222. */
  53223. get: function () {
  53224. for (var index = 0; index < this.actions.length; index++) {
  53225. var action = this.actions[index];
  53226. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  53227. return true;
  53228. }
  53229. }
  53230. return false;
  53231. },
  53232. enumerable: true,
  53233. configurable: true
  53234. });
  53235. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53236. /**
  53237. * Does this action manager has pick triggers
  53238. */
  53239. get: function () {
  53240. for (var index = 0; index < this.actions.length; index++) {
  53241. var action = this.actions[index];
  53242. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  53243. return true;
  53244. }
  53245. }
  53246. return false;
  53247. },
  53248. enumerable: true,
  53249. configurable: true
  53250. });
  53251. Object.defineProperty(ActionManager, "HasTriggers", {
  53252. /**
  53253. * Does exist one action manager with at least one trigger
  53254. **/
  53255. get: function () {
  53256. for (var t in ActionManager.Triggers) {
  53257. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53258. return true;
  53259. }
  53260. }
  53261. return false;
  53262. },
  53263. enumerable: true,
  53264. configurable: true
  53265. });
  53266. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53267. /**
  53268. * Does exist one action manager with at least one pick trigger
  53269. **/
  53270. get: function () {
  53271. for (var t in ActionManager.Triggers) {
  53272. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53273. var t_int = parseInt(t);
  53274. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53275. return true;
  53276. }
  53277. }
  53278. }
  53279. return false;
  53280. },
  53281. enumerable: true,
  53282. configurable: true
  53283. });
  53284. /**
  53285. * Does exist one action manager that handles actions of a given trigger
  53286. * @param trigger defines the trigger to be tested
  53287. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53288. **/
  53289. ActionManager.HasSpecificTrigger = function (trigger) {
  53290. for (var t in ActionManager.Triggers) {
  53291. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53292. var t_int = parseInt(t);
  53293. if (t_int === trigger) {
  53294. return true;
  53295. }
  53296. }
  53297. }
  53298. return false;
  53299. };
  53300. /**
  53301. * Registers an action to this action manager
  53302. * @param action defines the action to be registered
  53303. * @return the action amended (prepared) after registration
  53304. */
  53305. ActionManager.prototype.registerAction = function (action) {
  53306. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53307. if (this.getScene().actionManager !== this) {
  53308. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53309. return null;
  53310. }
  53311. }
  53312. this.actions.push(action);
  53313. if (ActionManager.Triggers[action.trigger]) {
  53314. ActionManager.Triggers[action.trigger]++;
  53315. }
  53316. else {
  53317. ActionManager.Triggers[action.trigger] = 1;
  53318. }
  53319. action._actionManager = this;
  53320. action._prepare();
  53321. return action;
  53322. };
  53323. /**
  53324. * Unregisters an action to this action manager
  53325. * @param action defines the action to be unregistered
  53326. * @return a boolean indicating whether the action has been unregistered
  53327. */
  53328. ActionManager.prototype.unregisterAction = function (action) {
  53329. var index = this.actions.indexOf(action);
  53330. if (index !== -1) {
  53331. this.actions.splice(index, 1);
  53332. ActionManager.Triggers[action.trigger] -= 1;
  53333. if (ActionManager.Triggers[action.trigger] === 0) {
  53334. delete ActionManager.Triggers[action.trigger];
  53335. }
  53336. delete action._actionManager;
  53337. return true;
  53338. }
  53339. return false;
  53340. };
  53341. /**
  53342. * Process a specific trigger
  53343. * @param trigger defines the trigger to process
  53344. * @param evt defines the event details to be processed
  53345. */
  53346. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53347. for (var index = 0; index < this.actions.length; index++) {
  53348. var action = this.actions[index];
  53349. if (action.trigger === trigger) {
  53350. if (evt) {
  53351. if (trigger === ActionManager.OnKeyUpTrigger
  53352. || trigger === ActionManager.OnKeyDownTrigger) {
  53353. var parameter = action.getTriggerParameter();
  53354. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53355. if (!parameter.toLowerCase) {
  53356. continue;
  53357. }
  53358. var lowerCase = parameter.toLowerCase();
  53359. if (lowerCase !== evt.sourceEvent.key) {
  53360. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53361. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53362. if (actualkey !== lowerCase) {
  53363. continue;
  53364. }
  53365. }
  53366. }
  53367. }
  53368. }
  53369. action._executeCurrent(evt);
  53370. }
  53371. }
  53372. };
  53373. /** @hidden */
  53374. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53375. var properties = propertyPath.split(".");
  53376. for (var index = 0; index < properties.length - 1; index++) {
  53377. target = target[properties[index]];
  53378. }
  53379. return target;
  53380. };
  53381. /** @hidden */
  53382. ActionManager.prototype._getProperty = function (propertyPath) {
  53383. var properties = propertyPath.split(".");
  53384. return properties[properties.length - 1];
  53385. };
  53386. /**
  53387. * Serialize this manager to a JSON object
  53388. * @param name defines the property name to store this manager
  53389. * @returns a JSON representation of this manager
  53390. */
  53391. ActionManager.prototype.serialize = function (name) {
  53392. var root = {
  53393. children: new Array(),
  53394. name: name,
  53395. type: 3,
  53396. properties: new Array() // Empty for root but required
  53397. };
  53398. for (var i = 0; i < this.actions.length; i++) {
  53399. var triggerObject = {
  53400. type: 0,
  53401. children: new Array(),
  53402. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53403. properties: new Array()
  53404. };
  53405. var triggerOptions = this.actions[i].triggerOptions;
  53406. if (triggerOptions && typeof triggerOptions !== "number") {
  53407. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53408. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53409. }
  53410. else {
  53411. var parameter = {};
  53412. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53413. if (triggerOptions.parameter.mesh) {
  53414. parameter._meshId = triggerOptions.parameter.mesh.id;
  53415. }
  53416. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53417. }
  53418. }
  53419. // Serialize child action, recursively
  53420. this.actions[i].serialize(triggerObject);
  53421. // Add serialized trigger
  53422. root.children.push(triggerObject);
  53423. }
  53424. return root;
  53425. };
  53426. /**
  53427. * Creates a new ActionManager from a JSON data
  53428. * @param parsedActions defines the JSON data to read from
  53429. * @param object defines the hosting mesh
  53430. * @param scene defines the hosting scene
  53431. */
  53432. ActionManager.Parse = function (parsedActions, object, scene) {
  53433. var actionManager = new ActionManager(scene);
  53434. if (object === null)
  53435. scene.actionManager = actionManager;
  53436. else
  53437. object.actionManager = actionManager;
  53438. // instanciate a new object
  53439. var instanciate = function (name, params) {
  53440. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53441. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53442. newInstance.constructor.apply(newInstance, params);
  53443. return newInstance;
  53444. };
  53445. var parseParameter = function (name, value, target, propertyPath) {
  53446. if (propertyPath === null) {
  53447. // String, boolean or float
  53448. var floatValue = parseFloat(value);
  53449. if (value === "true" || value === "false")
  53450. return value === "true";
  53451. else
  53452. return isNaN(floatValue) ? value : floatValue;
  53453. }
  53454. var effectiveTarget = propertyPath.split(".");
  53455. var values = value.split(",");
  53456. // Get effective Target
  53457. for (var i = 0; i < effectiveTarget.length; i++) {
  53458. target = target[effectiveTarget[i]];
  53459. }
  53460. // Return appropriate value with its type
  53461. if (typeof (target) === "boolean")
  53462. return values[0] === "true";
  53463. if (typeof (target) === "string")
  53464. return values[0];
  53465. // Parameters with multiple values such as Vector3 etc.
  53466. var split = new Array();
  53467. for (var i = 0; i < values.length; i++)
  53468. split.push(parseFloat(values[i]));
  53469. if (target instanceof BABYLON.Vector3)
  53470. return BABYLON.Vector3.FromArray(split);
  53471. if (target instanceof BABYLON.Vector4)
  53472. return BABYLON.Vector4.FromArray(split);
  53473. if (target instanceof BABYLON.Color3)
  53474. return BABYLON.Color3.FromArray(split);
  53475. if (target instanceof BABYLON.Color4)
  53476. return BABYLON.Color4.FromArray(split);
  53477. return parseFloat(values[0]);
  53478. };
  53479. // traverse graph per trigger
  53480. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53481. if (combineArray === void 0) { combineArray = null; }
  53482. if (parsedAction.detached)
  53483. return;
  53484. var parameters = new Array();
  53485. var target = null;
  53486. var propertyPath = null;
  53487. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53488. // Parameters
  53489. if (parsedAction.type === 2)
  53490. parameters.push(actionManager);
  53491. else
  53492. parameters.push(trigger);
  53493. if (combine) {
  53494. var actions = new Array();
  53495. for (var j = 0; j < parsedAction.combine.length; j++) {
  53496. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53497. }
  53498. parameters.push(actions);
  53499. }
  53500. else {
  53501. for (var i = 0; i < parsedAction.properties.length; i++) {
  53502. var value = parsedAction.properties[i].value;
  53503. var name = parsedAction.properties[i].name;
  53504. var targetType = parsedAction.properties[i].targetType;
  53505. if (name === "target")
  53506. if (targetType !== null && targetType === "SceneProperties")
  53507. value = target = scene;
  53508. else
  53509. value = target = scene.getNodeByName(value);
  53510. else if (name === "parent")
  53511. value = scene.getNodeByName(value);
  53512. else if (name === "sound")
  53513. value = scene.getSoundByName(value);
  53514. else if (name !== "propertyPath") {
  53515. if (parsedAction.type === 2 && name === "operator")
  53516. value = BABYLON.ValueCondition[value];
  53517. else
  53518. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53519. }
  53520. else {
  53521. propertyPath = value;
  53522. }
  53523. parameters.push(value);
  53524. }
  53525. }
  53526. if (combineArray === null) {
  53527. parameters.push(condition);
  53528. }
  53529. else {
  53530. parameters.push(null);
  53531. }
  53532. // If interpolate value action
  53533. if (parsedAction.name === "InterpolateValueAction") {
  53534. var param = parameters[parameters.length - 2];
  53535. parameters[parameters.length - 1] = param;
  53536. parameters[parameters.length - 2] = condition;
  53537. }
  53538. // Action or condition(s) and not CombineAction
  53539. var newAction = instanciate(parsedAction.name, parameters);
  53540. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53541. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53542. if (action)
  53543. action.then(nothing);
  53544. else
  53545. actionManager.registerAction(nothing);
  53546. action = nothing;
  53547. }
  53548. if (combineArray === null) {
  53549. if (newAction instanceof BABYLON.Condition) {
  53550. condition = newAction;
  53551. newAction = action;
  53552. }
  53553. else {
  53554. condition = null;
  53555. if (action)
  53556. action.then(newAction);
  53557. else
  53558. actionManager.registerAction(newAction);
  53559. }
  53560. }
  53561. else {
  53562. combineArray.push(newAction);
  53563. }
  53564. for (var i = 0; i < parsedAction.children.length; i++)
  53565. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53566. };
  53567. // triggers
  53568. for (var i = 0; i < parsedActions.children.length; i++) {
  53569. var triggerParams;
  53570. var trigger = parsedActions.children[i];
  53571. if (trigger.properties.length > 0) {
  53572. var param = trigger.properties[0].value;
  53573. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53574. if (value._meshId) {
  53575. value.mesh = scene.getMeshByID(value._meshId);
  53576. }
  53577. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53578. }
  53579. else
  53580. triggerParams = ActionManager[trigger.name];
  53581. for (var j = 0; j < trigger.children.length; j++) {
  53582. if (!trigger.detached)
  53583. traverse(trigger.children[j], triggerParams, null, null);
  53584. }
  53585. }
  53586. };
  53587. /**
  53588. * Get a trigger name by index
  53589. * @param trigger defines the trigger index
  53590. * @returns a trigger name
  53591. */
  53592. ActionManager.GetTriggerName = function (trigger) {
  53593. switch (trigger) {
  53594. case 0: return "NothingTrigger";
  53595. case 1: return "OnPickTrigger";
  53596. case 2: return "OnLeftPickTrigger";
  53597. case 3: return "OnRightPickTrigger";
  53598. case 4: return "OnCenterPickTrigger";
  53599. case 5: return "OnPickDownTrigger";
  53600. case 6: return "OnPickUpTrigger";
  53601. case 7: return "OnLongPressTrigger";
  53602. case 8: return "OnPointerOverTrigger";
  53603. case 9: return "OnPointerOutTrigger";
  53604. case 10: return "OnEveryFrameTrigger";
  53605. case 11: return "OnIntersectionEnterTrigger";
  53606. case 12: return "OnIntersectionExitTrigger";
  53607. case 13: return "OnKeyDownTrigger";
  53608. case 14: return "OnKeyUpTrigger";
  53609. case 15: return "OnPickOutTrigger";
  53610. default: return "";
  53611. }
  53612. };
  53613. // Statics
  53614. ActionManager._NothingTrigger = 0;
  53615. ActionManager._OnPickTrigger = 1;
  53616. ActionManager._OnLeftPickTrigger = 2;
  53617. ActionManager._OnRightPickTrigger = 3;
  53618. ActionManager._OnCenterPickTrigger = 4;
  53619. ActionManager._OnPickDownTrigger = 5;
  53620. ActionManager._OnDoublePickTrigger = 6;
  53621. ActionManager._OnPickUpTrigger = 7;
  53622. ActionManager._OnLongPressTrigger = 8;
  53623. ActionManager._OnPointerOverTrigger = 9;
  53624. ActionManager._OnPointerOutTrigger = 10;
  53625. ActionManager._OnEveryFrameTrigger = 11;
  53626. ActionManager._OnIntersectionEnterTrigger = 12;
  53627. ActionManager._OnIntersectionExitTrigger = 13;
  53628. ActionManager._OnKeyDownTrigger = 14;
  53629. ActionManager._OnKeyUpTrigger = 15;
  53630. ActionManager._OnPickOutTrigger = 16;
  53631. /** Gets the list of active triggers */
  53632. ActionManager.Triggers = {};
  53633. return ActionManager;
  53634. }());
  53635. BABYLON.ActionManager = ActionManager;
  53636. })(BABYLON || (BABYLON = {}));
  53637. //# sourceMappingURL=babylon.actionManager.js.map
  53638. var BABYLON;
  53639. (function (BABYLON) {
  53640. var InterpolateValueAction = /** @class */ (function (_super) {
  53641. __extends(InterpolateValueAction, _super);
  53642. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53643. if (duration === void 0) { duration = 1000; }
  53644. var _this = _super.call(this, triggerOptions, condition) || this;
  53645. _this.propertyPath = propertyPath;
  53646. _this.value = value;
  53647. _this.duration = duration;
  53648. _this.stopOtherAnimations = stopOtherAnimations;
  53649. _this.onInterpolationDone = onInterpolationDone;
  53650. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53651. _this._target = _this._effectiveTarget = target;
  53652. return _this;
  53653. }
  53654. /** @hidden */
  53655. InterpolateValueAction.prototype._prepare = function () {
  53656. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53657. this._property = this._getProperty(this.propertyPath);
  53658. };
  53659. InterpolateValueAction.prototype.execute = function () {
  53660. var _this = this;
  53661. var scene = this._actionManager.getScene();
  53662. var keys = [
  53663. {
  53664. frame: 0,
  53665. value: this._effectiveTarget[this._property]
  53666. }, {
  53667. frame: 100,
  53668. value: this.value
  53669. }
  53670. ];
  53671. var dataType;
  53672. if (typeof this.value === "number") {
  53673. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53674. }
  53675. else if (this.value instanceof BABYLON.Color3) {
  53676. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53677. }
  53678. else if (this.value instanceof BABYLON.Vector3) {
  53679. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53680. }
  53681. else if (this.value instanceof BABYLON.Matrix) {
  53682. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53683. }
  53684. else if (this.value instanceof BABYLON.Quaternion) {
  53685. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53686. }
  53687. else {
  53688. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53689. return;
  53690. }
  53691. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53692. animation.setKeys(keys);
  53693. if (this.stopOtherAnimations) {
  53694. scene.stopAnimation(this._effectiveTarget);
  53695. }
  53696. var wrapper = function () {
  53697. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53698. if (_this.onInterpolationDone) {
  53699. _this.onInterpolationDone();
  53700. }
  53701. };
  53702. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53703. };
  53704. InterpolateValueAction.prototype.serialize = function (parent) {
  53705. return _super.prototype._serialize.call(this, {
  53706. name: "InterpolateValueAction",
  53707. properties: [
  53708. BABYLON.Action._GetTargetProperty(this._target),
  53709. { name: "propertyPath", value: this.propertyPath },
  53710. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53711. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53712. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53713. ]
  53714. }, parent);
  53715. };
  53716. return InterpolateValueAction;
  53717. }(BABYLON.Action));
  53718. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53719. })(BABYLON || (BABYLON = {}));
  53720. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53721. var BABYLON;
  53722. (function (BABYLON) {
  53723. var SwitchBooleanAction = /** @class */ (function (_super) {
  53724. __extends(SwitchBooleanAction, _super);
  53725. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53726. var _this = _super.call(this, triggerOptions, condition) || this;
  53727. _this.propertyPath = propertyPath;
  53728. _this._target = _this._effectiveTarget = target;
  53729. return _this;
  53730. }
  53731. /** @hidden */
  53732. SwitchBooleanAction.prototype._prepare = function () {
  53733. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53734. this._property = this._getProperty(this.propertyPath);
  53735. };
  53736. SwitchBooleanAction.prototype.execute = function () {
  53737. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53738. };
  53739. SwitchBooleanAction.prototype.serialize = function (parent) {
  53740. return _super.prototype._serialize.call(this, {
  53741. name: "SwitchBooleanAction",
  53742. properties: [
  53743. BABYLON.Action._GetTargetProperty(this._target),
  53744. { name: "propertyPath", value: this.propertyPath }
  53745. ]
  53746. }, parent);
  53747. };
  53748. return SwitchBooleanAction;
  53749. }(BABYLON.Action));
  53750. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53751. var SetStateAction = /** @class */ (function (_super) {
  53752. __extends(SetStateAction, _super);
  53753. function SetStateAction(triggerOptions, target, value, condition) {
  53754. var _this = _super.call(this, triggerOptions, condition) || this;
  53755. _this.value = value;
  53756. _this._target = target;
  53757. return _this;
  53758. }
  53759. SetStateAction.prototype.execute = function () {
  53760. this._target.state = this.value;
  53761. };
  53762. SetStateAction.prototype.serialize = function (parent) {
  53763. return _super.prototype._serialize.call(this, {
  53764. name: "SetStateAction",
  53765. properties: [
  53766. BABYLON.Action._GetTargetProperty(this._target),
  53767. { name: "value", value: this.value }
  53768. ]
  53769. }, parent);
  53770. };
  53771. return SetStateAction;
  53772. }(BABYLON.Action));
  53773. BABYLON.SetStateAction = SetStateAction;
  53774. var SetValueAction = /** @class */ (function (_super) {
  53775. __extends(SetValueAction, _super);
  53776. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53777. var _this = _super.call(this, triggerOptions, condition) || this;
  53778. _this.propertyPath = propertyPath;
  53779. _this.value = value;
  53780. _this._target = _this._effectiveTarget = target;
  53781. return _this;
  53782. }
  53783. /** @hidden */
  53784. SetValueAction.prototype._prepare = function () {
  53785. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53786. this._property = this._getProperty(this.propertyPath);
  53787. };
  53788. SetValueAction.prototype.execute = function () {
  53789. this._effectiveTarget[this._property] = this.value;
  53790. if (this._target.markAsDirty) {
  53791. this._target.markAsDirty(this._property);
  53792. }
  53793. };
  53794. SetValueAction.prototype.serialize = function (parent) {
  53795. return _super.prototype._serialize.call(this, {
  53796. name: "SetValueAction",
  53797. properties: [
  53798. BABYLON.Action._GetTargetProperty(this._target),
  53799. { name: "propertyPath", value: this.propertyPath },
  53800. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53801. ]
  53802. }, parent);
  53803. };
  53804. return SetValueAction;
  53805. }(BABYLON.Action));
  53806. BABYLON.SetValueAction = SetValueAction;
  53807. var IncrementValueAction = /** @class */ (function (_super) {
  53808. __extends(IncrementValueAction, _super);
  53809. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53810. var _this = _super.call(this, triggerOptions, condition) || this;
  53811. _this.propertyPath = propertyPath;
  53812. _this.value = value;
  53813. _this._target = _this._effectiveTarget = target;
  53814. return _this;
  53815. }
  53816. /** @hidden */
  53817. IncrementValueAction.prototype._prepare = function () {
  53818. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53819. this._property = this._getProperty(this.propertyPath);
  53820. if (typeof this._effectiveTarget[this._property] !== "number") {
  53821. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53822. }
  53823. };
  53824. IncrementValueAction.prototype.execute = function () {
  53825. this._effectiveTarget[this._property] += this.value;
  53826. if (this._target.markAsDirty) {
  53827. this._target.markAsDirty(this._property);
  53828. }
  53829. };
  53830. IncrementValueAction.prototype.serialize = function (parent) {
  53831. return _super.prototype._serialize.call(this, {
  53832. name: "IncrementValueAction",
  53833. properties: [
  53834. BABYLON.Action._GetTargetProperty(this._target),
  53835. { name: "propertyPath", value: this.propertyPath },
  53836. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53837. ]
  53838. }, parent);
  53839. };
  53840. return IncrementValueAction;
  53841. }(BABYLON.Action));
  53842. BABYLON.IncrementValueAction = IncrementValueAction;
  53843. var PlayAnimationAction = /** @class */ (function (_super) {
  53844. __extends(PlayAnimationAction, _super);
  53845. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53846. var _this = _super.call(this, triggerOptions, condition) || this;
  53847. _this.from = from;
  53848. _this.to = to;
  53849. _this.loop = loop;
  53850. _this._target = target;
  53851. return _this;
  53852. }
  53853. /** @hidden */
  53854. PlayAnimationAction.prototype._prepare = function () {
  53855. };
  53856. PlayAnimationAction.prototype.execute = function () {
  53857. var scene = this._actionManager.getScene();
  53858. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53859. };
  53860. PlayAnimationAction.prototype.serialize = function (parent) {
  53861. return _super.prototype._serialize.call(this, {
  53862. name: "PlayAnimationAction",
  53863. properties: [
  53864. BABYLON.Action._GetTargetProperty(this._target),
  53865. { name: "from", value: String(this.from) },
  53866. { name: "to", value: String(this.to) },
  53867. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53868. ]
  53869. }, parent);
  53870. };
  53871. return PlayAnimationAction;
  53872. }(BABYLON.Action));
  53873. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53874. var StopAnimationAction = /** @class */ (function (_super) {
  53875. __extends(StopAnimationAction, _super);
  53876. function StopAnimationAction(triggerOptions, target, condition) {
  53877. var _this = _super.call(this, triggerOptions, condition) || this;
  53878. _this._target = target;
  53879. return _this;
  53880. }
  53881. /** @hidden */
  53882. StopAnimationAction.prototype._prepare = function () {
  53883. };
  53884. StopAnimationAction.prototype.execute = function () {
  53885. var scene = this._actionManager.getScene();
  53886. scene.stopAnimation(this._target);
  53887. };
  53888. StopAnimationAction.prototype.serialize = function (parent) {
  53889. return _super.prototype._serialize.call(this, {
  53890. name: "StopAnimationAction",
  53891. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53892. }, parent);
  53893. };
  53894. return StopAnimationAction;
  53895. }(BABYLON.Action));
  53896. BABYLON.StopAnimationAction = StopAnimationAction;
  53897. var DoNothingAction = /** @class */ (function (_super) {
  53898. __extends(DoNothingAction, _super);
  53899. function DoNothingAction(triggerOptions, condition) {
  53900. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53901. return _super.call(this, triggerOptions, condition) || this;
  53902. }
  53903. DoNothingAction.prototype.execute = function () {
  53904. };
  53905. DoNothingAction.prototype.serialize = function (parent) {
  53906. return _super.prototype._serialize.call(this, {
  53907. name: "DoNothingAction",
  53908. properties: []
  53909. }, parent);
  53910. };
  53911. return DoNothingAction;
  53912. }(BABYLON.Action));
  53913. BABYLON.DoNothingAction = DoNothingAction;
  53914. var CombineAction = /** @class */ (function (_super) {
  53915. __extends(CombineAction, _super);
  53916. function CombineAction(triggerOptions, children, condition) {
  53917. var _this = _super.call(this, triggerOptions, condition) || this;
  53918. _this.children = children;
  53919. return _this;
  53920. }
  53921. /** @hidden */
  53922. CombineAction.prototype._prepare = function () {
  53923. for (var index = 0; index < this.children.length; index++) {
  53924. this.children[index]._actionManager = this._actionManager;
  53925. this.children[index]._prepare();
  53926. }
  53927. };
  53928. CombineAction.prototype.execute = function (evt) {
  53929. for (var index = 0; index < this.children.length; index++) {
  53930. this.children[index].execute(evt);
  53931. }
  53932. };
  53933. CombineAction.prototype.serialize = function (parent) {
  53934. var serializationObject = _super.prototype._serialize.call(this, {
  53935. name: "CombineAction",
  53936. properties: [],
  53937. combine: []
  53938. }, parent);
  53939. for (var i = 0; i < this.children.length; i++) {
  53940. serializationObject.combine.push(this.children[i].serialize(null));
  53941. }
  53942. return serializationObject;
  53943. };
  53944. return CombineAction;
  53945. }(BABYLON.Action));
  53946. BABYLON.CombineAction = CombineAction;
  53947. var ExecuteCodeAction = /** @class */ (function (_super) {
  53948. __extends(ExecuteCodeAction, _super);
  53949. function ExecuteCodeAction(triggerOptions, func, condition) {
  53950. var _this = _super.call(this, triggerOptions, condition) || this;
  53951. _this.func = func;
  53952. return _this;
  53953. }
  53954. ExecuteCodeAction.prototype.execute = function (evt) {
  53955. this.func(evt);
  53956. };
  53957. return ExecuteCodeAction;
  53958. }(BABYLON.Action));
  53959. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53960. var SetParentAction = /** @class */ (function (_super) {
  53961. __extends(SetParentAction, _super);
  53962. function SetParentAction(triggerOptions, target, parent, condition) {
  53963. var _this = _super.call(this, triggerOptions, condition) || this;
  53964. _this._target = target;
  53965. _this._parent = parent;
  53966. return _this;
  53967. }
  53968. /** @hidden */
  53969. SetParentAction.prototype._prepare = function () {
  53970. };
  53971. SetParentAction.prototype.execute = function () {
  53972. if (this._target.parent === this._parent) {
  53973. return;
  53974. }
  53975. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53976. invertParentWorldMatrix.invert();
  53977. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53978. this._target.parent = this._parent;
  53979. };
  53980. SetParentAction.prototype.serialize = function (parent) {
  53981. return _super.prototype._serialize.call(this, {
  53982. name: "SetParentAction",
  53983. properties: [
  53984. BABYLON.Action._GetTargetProperty(this._target),
  53985. BABYLON.Action._GetTargetProperty(this._parent),
  53986. ]
  53987. }, parent);
  53988. };
  53989. return SetParentAction;
  53990. }(BABYLON.Action));
  53991. BABYLON.SetParentAction = SetParentAction;
  53992. var PlaySoundAction = /** @class */ (function (_super) {
  53993. __extends(PlaySoundAction, _super);
  53994. function PlaySoundAction(triggerOptions, sound, condition) {
  53995. var _this = _super.call(this, triggerOptions, condition) || this;
  53996. _this._sound = sound;
  53997. return _this;
  53998. }
  53999. /** @hidden */
  54000. PlaySoundAction.prototype._prepare = function () {
  54001. };
  54002. PlaySoundAction.prototype.execute = function () {
  54003. if (this._sound !== undefined)
  54004. this._sound.play();
  54005. };
  54006. PlaySoundAction.prototype.serialize = function (parent) {
  54007. return _super.prototype._serialize.call(this, {
  54008. name: "PlaySoundAction",
  54009. properties: [{ name: "sound", value: this._sound.name }]
  54010. }, parent);
  54011. };
  54012. return PlaySoundAction;
  54013. }(BABYLON.Action));
  54014. BABYLON.PlaySoundAction = PlaySoundAction;
  54015. var StopSoundAction = /** @class */ (function (_super) {
  54016. __extends(StopSoundAction, _super);
  54017. function StopSoundAction(triggerOptions, sound, condition) {
  54018. var _this = _super.call(this, triggerOptions, condition) || this;
  54019. _this._sound = sound;
  54020. return _this;
  54021. }
  54022. /** @hidden */
  54023. StopSoundAction.prototype._prepare = function () {
  54024. };
  54025. StopSoundAction.prototype.execute = function () {
  54026. if (this._sound !== undefined)
  54027. this._sound.stop();
  54028. };
  54029. StopSoundAction.prototype.serialize = function (parent) {
  54030. return _super.prototype._serialize.call(this, {
  54031. name: "StopSoundAction",
  54032. properties: [{ name: "sound", value: this._sound.name }]
  54033. }, parent);
  54034. };
  54035. return StopSoundAction;
  54036. }(BABYLON.Action));
  54037. BABYLON.StopSoundAction = StopSoundAction;
  54038. })(BABYLON || (BABYLON = {}));
  54039. //# sourceMappingURL=babylon.directActions.js.map
  54040. var BABYLON;
  54041. (function (BABYLON) {
  54042. var SpriteManager = /** @class */ (function () {
  54043. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54044. if (epsilon === void 0) { epsilon = 0.01; }
  54045. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54046. this.name = name;
  54047. this.sprites = new Array();
  54048. this.renderingGroupId = 0;
  54049. this.layerMask = 0x0FFFFFFF;
  54050. this.fogEnabled = true;
  54051. this.isPickable = false;
  54052. /**
  54053. * An event triggered when the manager is disposed.
  54054. */
  54055. this.onDisposeObservable = new BABYLON.Observable();
  54056. this._vertexBuffers = {};
  54057. this._capacity = capacity;
  54058. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54059. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54060. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54061. if (cellSize.width && cellSize.height) {
  54062. this.cellWidth = cellSize.width;
  54063. this.cellHeight = cellSize.height;
  54064. }
  54065. else if (cellSize !== undefined) {
  54066. this.cellWidth = cellSize;
  54067. this.cellHeight = cellSize;
  54068. }
  54069. else {
  54070. return;
  54071. }
  54072. this._epsilon = epsilon;
  54073. this._scene = scene;
  54074. this._scene.spriteManagers.push(this);
  54075. var indices = [];
  54076. var index = 0;
  54077. for (var count = 0; count < capacity; count++) {
  54078. indices.push(index);
  54079. indices.push(index + 1);
  54080. indices.push(index + 2);
  54081. indices.push(index);
  54082. indices.push(index + 2);
  54083. indices.push(index + 3);
  54084. index += 4;
  54085. }
  54086. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54087. // VBO
  54088. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54089. this._vertexData = new Float32Array(capacity * 16 * 4);
  54090. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54091. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54092. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54093. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54094. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54095. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54096. this._vertexBuffers["options"] = options;
  54097. this._vertexBuffers["cellInfo"] = cellInfo;
  54098. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54099. // Effects
  54100. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54101. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54102. }
  54103. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54104. set: function (callback) {
  54105. if (this._onDisposeObserver) {
  54106. this.onDisposeObservable.remove(this._onDisposeObserver);
  54107. }
  54108. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54109. },
  54110. enumerable: true,
  54111. configurable: true
  54112. });
  54113. Object.defineProperty(SpriteManager.prototype, "texture", {
  54114. get: function () {
  54115. return this._spriteTexture;
  54116. },
  54117. set: function (value) {
  54118. this._spriteTexture = value;
  54119. },
  54120. enumerable: true,
  54121. configurable: true
  54122. });
  54123. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54124. var arrayOffset = index * 16;
  54125. if (offsetX === 0)
  54126. offsetX = this._epsilon;
  54127. else if (offsetX === 1)
  54128. offsetX = 1 - this._epsilon;
  54129. if (offsetY === 0)
  54130. offsetY = this._epsilon;
  54131. else if (offsetY === 1)
  54132. offsetY = 1 - this._epsilon;
  54133. this._vertexData[arrayOffset] = sprite.position.x;
  54134. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54135. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54136. this._vertexData[arrayOffset + 3] = sprite.angle;
  54137. this._vertexData[arrayOffset + 4] = sprite.width;
  54138. this._vertexData[arrayOffset + 5] = sprite.height;
  54139. this._vertexData[arrayOffset + 6] = offsetX;
  54140. this._vertexData[arrayOffset + 7] = offsetY;
  54141. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54142. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54143. var offset = (sprite.cellIndex / rowSize) >> 0;
  54144. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54145. this._vertexData[arrayOffset + 11] = offset;
  54146. // Color
  54147. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54148. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54149. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54150. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54151. };
  54152. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54153. var count = Math.min(this._capacity, this.sprites.length);
  54154. var min = BABYLON.Vector3.Zero();
  54155. var max = BABYLON.Vector3.Zero();
  54156. var distance = Number.MAX_VALUE;
  54157. var currentSprite = null;
  54158. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54159. var cameraView = camera.getViewMatrix();
  54160. for (var index = 0; index < count; index++) {
  54161. var sprite = this.sprites[index];
  54162. if (!sprite) {
  54163. continue;
  54164. }
  54165. if (predicate) {
  54166. if (!predicate(sprite)) {
  54167. continue;
  54168. }
  54169. }
  54170. else if (!sprite.isPickable) {
  54171. continue;
  54172. }
  54173. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54174. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54175. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54176. if (ray.intersectsBoxMinMax(min, max)) {
  54177. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54178. if (distance > currentDistance) {
  54179. distance = currentDistance;
  54180. currentSprite = sprite;
  54181. if (fastCheck) {
  54182. break;
  54183. }
  54184. }
  54185. }
  54186. }
  54187. if (currentSprite) {
  54188. var result = new BABYLON.PickingInfo();
  54189. result.hit = true;
  54190. result.pickedSprite = currentSprite;
  54191. result.distance = distance;
  54192. return result;
  54193. }
  54194. return null;
  54195. };
  54196. SpriteManager.prototype.render = function () {
  54197. // Check
  54198. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54199. return;
  54200. var engine = this._scene.getEngine();
  54201. var baseSize = this._spriteTexture.getBaseSize();
  54202. // Sprites
  54203. var deltaTime = engine.getDeltaTime();
  54204. var max = Math.min(this._capacity, this.sprites.length);
  54205. var rowSize = baseSize.width / this.cellWidth;
  54206. var offset = 0;
  54207. for (var index = 0; index < max; index++) {
  54208. var sprite = this.sprites[index];
  54209. if (!sprite || !sprite.isVisible) {
  54210. continue;
  54211. }
  54212. sprite._animate(deltaTime);
  54213. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54214. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54215. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54216. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54217. }
  54218. this._buffer.update(this._vertexData);
  54219. // Render
  54220. var effect = this._effectBase;
  54221. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54222. effect = this._effectFog;
  54223. }
  54224. engine.enableEffect(effect);
  54225. var viewMatrix = this._scene.getViewMatrix();
  54226. effect.setTexture("diffuseSampler", this._spriteTexture);
  54227. effect.setMatrix("view", viewMatrix);
  54228. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54229. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54230. // Fog
  54231. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54232. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54233. effect.setColor3("vFogColor", this._scene.fogColor);
  54234. }
  54235. // VBOs
  54236. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54237. // Draw order
  54238. engine.setDepthFunctionToLessOrEqual();
  54239. effect.setBool("alphaTest", true);
  54240. engine.setColorWrite(false);
  54241. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  54242. engine.setColorWrite(true);
  54243. effect.setBool("alphaTest", false);
  54244. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54245. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  54246. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54247. };
  54248. SpriteManager.prototype.dispose = function () {
  54249. if (this._buffer) {
  54250. this._buffer.dispose();
  54251. this._buffer = null;
  54252. }
  54253. if (this._indexBuffer) {
  54254. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54255. this._indexBuffer = null;
  54256. }
  54257. if (this._spriteTexture) {
  54258. this._spriteTexture.dispose();
  54259. this._spriteTexture = null;
  54260. }
  54261. // Remove from scene
  54262. var index = this._scene.spriteManagers.indexOf(this);
  54263. this._scene.spriteManagers.splice(index, 1);
  54264. // Callback
  54265. this.onDisposeObservable.notifyObservers(this);
  54266. this.onDisposeObservable.clear();
  54267. };
  54268. return SpriteManager;
  54269. }());
  54270. BABYLON.SpriteManager = SpriteManager;
  54271. })(BABYLON || (BABYLON = {}));
  54272. //# sourceMappingURL=babylon.spriteManager.js.map
  54273. var BABYLON;
  54274. (function (BABYLON) {
  54275. var Sprite = /** @class */ (function () {
  54276. function Sprite(name, manager) {
  54277. this.name = name;
  54278. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54279. this.width = 1.0;
  54280. this.height = 1.0;
  54281. this.angle = 0;
  54282. this.cellIndex = 0;
  54283. this.invertU = 0;
  54284. this.invertV = 0;
  54285. this.animations = new Array();
  54286. this.isPickable = false;
  54287. this._animationStarted = false;
  54288. this._loopAnimation = false;
  54289. this._fromIndex = 0;
  54290. this._toIndex = 0;
  54291. this._delay = 0;
  54292. this._direction = 1;
  54293. this._time = 0;
  54294. /**
  54295. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  54296. */
  54297. this.isVisible = true;
  54298. this._manager = manager;
  54299. this._manager.sprites.push(this);
  54300. this.position = BABYLON.Vector3.Zero();
  54301. }
  54302. Object.defineProperty(Sprite.prototype, "size", {
  54303. get: function () {
  54304. return this.width;
  54305. },
  54306. set: function (value) {
  54307. this.width = value;
  54308. this.height = value;
  54309. },
  54310. enumerable: true,
  54311. configurable: true
  54312. });
  54313. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54314. this._fromIndex = from;
  54315. this._toIndex = to;
  54316. this._loopAnimation = loop;
  54317. this._delay = delay;
  54318. this._animationStarted = true;
  54319. this._direction = from < to ? 1 : -1;
  54320. this.cellIndex = from;
  54321. this._time = 0;
  54322. this._onAnimationEnd = onAnimationEnd;
  54323. };
  54324. Sprite.prototype.stopAnimation = function () {
  54325. this._animationStarted = false;
  54326. };
  54327. /** @hidden */
  54328. Sprite.prototype._animate = function (deltaTime) {
  54329. if (!this._animationStarted)
  54330. return;
  54331. this._time += deltaTime;
  54332. if (this._time > this._delay) {
  54333. this._time = this._time % this._delay;
  54334. this.cellIndex += this._direction;
  54335. if (this.cellIndex > this._toIndex) {
  54336. if (this._loopAnimation) {
  54337. this.cellIndex = this._fromIndex;
  54338. }
  54339. else {
  54340. this.cellIndex = this._toIndex;
  54341. this._animationStarted = false;
  54342. if (this._onAnimationEnd) {
  54343. this._onAnimationEnd();
  54344. }
  54345. if (this.disposeWhenFinishedAnimating) {
  54346. this.dispose();
  54347. }
  54348. }
  54349. }
  54350. }
  54351. };
  54352. Sprite.prototype.dispose = function () {
  54353. for (var i = 0; i < this._manager.sprites.length; i++) {
  54354. if (this._manager.sprites[i] == this) {
  54355. this._manager.sprites.splice(i, 1);
  54356. }
  54357. }
  54358. };
  54359. return Sprite;
  54360. }());
  54361. BABYLON.Sprite = Sprite;
  54362. })(BABYLON || (BABYLON = {}));
  54363. //# sourceMappingURL=babylon.sprite.js.map
  54364. var BABYLON;
  54365. (function (BABYLON) {
  54366. var IntersectionInfo = /** @class */ (function () {
  54367. function IntersectionInfo(bu, bv, distance) {
  54368. this.bu = bu;
  54369. this.bv = bv;
  54370. this.distance = distance;
  54371. this.faceId = 0;
  54372. this.subMeshId = 0;
  54373. }
  54374. return IntersectionInfo;
  54375. }());
  54376. BABYLON.IntersectionInfo = IntersectionInfo;
  54377. /**
  54378. * Information about the result of picking within a scene
  54379. * See https://doc.babylonjs.com/babylon101/picking_collisions
  54380. */
  54381. var PickingInfo = /** @class */ (function () {
  54382. function PickingInfo() {
  54383. /**
  54384. * If the pick collided with an object
  54385. */
  54386. this.hit = false;
  54387. /**
  54388. * Distance away where the pick collided
  54389. */
  54390. this.distance = 0;
  54391. /**
  54392. * The location of pick collision
  54393. */
  54394. this.pickedPoint = null;
  54395. /**
  54396. * The mesh corresponding the the pick collision
  54397. */
  54398. this.pickedMesh = null;
  54399. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  54400. this.bu = 0;
  54401. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  54402. this.bv = 0;
  54403. /** The id of the face on the mesh that was picked */
  54404. this.faceId = -1;
  54405. /** Id of the the submesh that was picked */
  54406. this.subMeshId = 0;
  54407. /** If a sprite was picked, this will be the sprite the pick collided with */
  54408. this.pickedSprite = null;
  54409. /**
  54410. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  54411. */
  54412. this.originMesh = null;
  54413. /**
  54414. * The ray that was used to perform the picking.
  54415. */
  54416. this.ray = null;
  54417. }
  54418. /**
  54419. * Gets the normal correspodning to the face the pick collided with
  54420. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  54421. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  54422. * @returns The normal correspodning to the face the pick collided with
  54423. */
  54424. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54425. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54426. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54427. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54428. return null;
  54429. }
  54430. var indices = this.pickedMesh.getIndices();
  54431. if (!indices) {
  54432. return null;
  54433. }
  54434. var result;
  54435. if (useVerticesNormals) {
  54436. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54437. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54438. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54439. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54440. normal0 = normal0.scale(this.bu);
  54441. normal1 = normal1.scale(this.bv);
  54442. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54443. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54444. }
  54445. else {
  54446. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54447. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54448. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54449. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54450. var p1p2 = vertex1.subtract(vertex2);
  54451. var p3p2 = vertex3.subtract(vertex2);
  54452. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54453. }
  54454. if (useWorldCoordinates) {
  54455. var wm = this.pickedMesh.getWorldMatrix();
  54456. if (this.pickedMesh.nonUniformScaling) {
  54457. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  54458. wm = BABYLON.Tmp.Matrix[0];
  54459. wm.setTranslationFromFloats(0, 0, 0);
  54460. wm.invert();
  54461. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  54462. wm = BABYLON.Tmp.Matrix[1];
  54463. }
  54464. result = BABYLON.Vector3.TransformNormal(result, wm);
  54465. }
  54466. result.normalize();
  54467. return result;
  54468. };
  54469. /**
  54470. * Gets the texture coordinates of where the pick occured
  54471. * @returns the vector containing the coordnates of the texture
  54472. */
  54473. PickingInfo.prototype.getTextureCoordinates = function () {
  54474. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54475. return null;
  54476. }
  54477. var indices = this.pickedMesh.getIndices();
  54478. if (!indices) {
  54479. return null;
  54480. }
  54481. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54482. if (!uvs) {
  54483. return null;
  54484. }
  54485. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54486. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54487. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54488. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54489. uv1 = uv1.scale(this.bu);
  54490. uv2 = uv2.scale(this.bv);
  54491. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54492. };
  54493. return PickingInfo;
  54494. }());
  54495. BABYLON.PickingInfo = PickingInfo;
  54496. })(BABYLON || (BABYLON = {}));
  54497. //# sourceMappingURL=babylon.pickingInfo.js.map
  54498. var BABYLON;
  54499. (function (BABYLON) {
  54500. var Ray = /** @class */ (function () {
  54501. function Ray(origin, direction, length) {
  54502. if (length === void 0) { length = Number.MAX_VALUE; }
  54503. this.origin = origin;
  54504. this.direction = direction;
  54505. this.length = length;
  54506. }
  54507. // Methods
  54508. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54509. var d = 0.0;
  54510. var maxValue = Number.MAX_VALUE;
  54511. var inv;
  54512. var min;
  54513. var max;
  54514. var temp;
  54515. if (Math.abs(this.direction.x) < 0.0000001) {
  54516. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54517. return false;
  54518. }
  54519. }
  54520. else {
  54521. inv = 1.0 / this.direction.x;
  54522. min = (minimum.x - this.origin.x) * inv;
  54523. max = (maximum.x - this.origin.x) * inv;
  54524. if (max === -Infinity) {
  54525. max = Infinity;
  54526. }
  54527. if (min > max) {
  54528. temp = min;
  54529. min = max;
  54530. max = temp;
  54531. }
  54532. d = Math.max(min, d);
  54533. maxValue = Math.min(max, maxValue);
  54534. if (d > maxValue) {
  54535. return false;
  54536. }
  54537. }
  54538. if (Math.abs(this.direction.y) < 0.0000001) {
  54539. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54540. return false;
  54541. }
  54542. }
  54543. else {
  54544. inv = 1.0 / this.direction.y;
  54545. min = (minimum.y - this.origin.y) * inv;
  54546. max = (maximum.y - this.origin.y) * inv;
  54547. if (max === -Infinity) {
  54548. max = Infinity;
  54549. }
  54550. if (min > max) {
  54551. temp = min;
  54552. min = max;
  54553. max = temp;
  54554. }
  54555. d = Math.max(min, d);
  54556. maxValue = Math.min(max, maxValue);
  54557. if (d > maxValue) {
  54558. return false;
  54559. }
  54560. }
  54561. if (Math.abs(this.direction.z) < 0.0000001) {
  54562. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54563. return false;
  54564. }
  54565. }
  54566. else {
  54567. inv = 1.0 / this.direction.z;
  54568. min = (minimum.z - this.origin.z) * inv;
  54569. max = (maximum.z - this.origin.z) * inv;
  54570. if (max === -Infinity) {
  54571. max = Infinity;
  54572. }
  54573. if (min > max) {
  54574. temp = min;
  54575. min = max;
  54576. max = temp;
  54577. }
  54578. d = Math.max(min, d);
  54579. maxValue = Math.min(max, maxValue);
  54580. if (d > maxValue) {
  54581. return false;
  54582. }
  54583. }
  54584. return true;
  54585. };
  54586. Ray.prototype.intersectsBox = function (box) {
  54587. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54588. };
  54589. Ray.prototype.intersectsSphere = function (sphere) {
  54590. var x = sphere.center.x - this.origin.x;
  54591. var y = sphere.center.y - this.origin.y;
  54592. var z = sphere.center.z - this.origin.z;
  54593. var pyth = (x * x) + (y * y) + (z * z);
  54594. var rr = sphere.radius * sphere.radius;
  54595. if (pyth <= rr) {
  54596. return true;
  54597. }
  54598. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54599. if (dot < 0.0) {
  54600. return false;
  54601. }
  54602. var temp = pyth - (dot * dot);
  54603. return temp <= rr;
  54604. };
  54605. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54606. if (!this._edge1) {
  54607. this._edge1 = BABYLON.Vector3.Zero();
  54608. this._edge2 = BABYLON.Vector3.Zero();
  54609. this._pvec = BABYLON.Vector3.Zero();
  54610. this._tvec = BABYLON.Vector3.Zero();
  54611. this._qvec = BABYLON.Vector3.Zero();
  54612. }
  54613. vertex1.subtractToRef(vertex0, this._edge1);
  54614. vertex2.subtractToRef(vertex0, this._edge2);
  54615. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54616. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54617. if (det === 0) {
  54618. return null;
  54619. }
  54620. var invdet = 1 / det;
  54621. this.origin.subtractToRef(vertex0, this._tvec);
  54622. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54623. if (bu < 0 || bu > 1.0) {
  54624. return null;
  54625. }
  54626. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54627. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54628. if (bv < 0 || bu + bv > 1.0) {
  54629. return null;
  54630. }
  54631. //check if the distance is longer than the predefined length.
  54632. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54633. if (distance > this.length) {
  54634. return null;
  54635. }
  54636. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54637. };
  54638. Ray.prototype.intersectsPlane = function (plane) {
  54639. var distance;
  54640. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54641. if (Math.abs(result1) < 9.99999997475243E-07) {
  54642. return null;
  54643. }
  54644. else {
  54645. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54646. distance = (-plane.d - result2) / result1;
  54647. if (distance < 0.0) {
  54648. if (distance < -9.99999997475243E-07) {
  54649. return null;
  54650. }
  54651. else {
  54652. return 0;
  54653. }
  54654. }
  54655. return distance;
  54656. }
  54657. };
  54658. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54659. var tm = BABYLON.Tmp.Matrix[0];
  54660. mesh.getWorldMatrix().invertToRef(tm);
  54661. if (this._tmpRay) {
  54662. Ray.TransformToRef(this, tm, this._tmpRay);
  54663. }
  54664. else {
  54665. this._tmpRay = Ray.Transform(this, tm);
  54666. }
  54667. return mesh.intersects(this._tmpRay, fastCheck);
  54668. };
  54669. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54670. if (results) {
  54671. results.length = 0;
  54672. }
  54673. else {
  54674. results = [];
  54675. }
  54676. for (var i = 0; i < meshes.length; i++) {
  54677. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54678. if (pickInfo.hit) {
  54679. results.push(pickInfo);
  54680. }
  54681. }
  54682. results.sort(this._comparePickingInfo);
  54683. return results;
  54684. };
  54685. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54686. if (pickingInfoA.distance < pickingInfoB.distance) {
  54687. return -1;
  54688. }
  54689. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54690. return 1;
  54691. }
  54692. else {
  54693. return 0;
  54694. }
  54695. };
  54696. /**
  54697. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54698. * @param sega the first point of the segment to test the intersection against
  54699. * @param segb the second point of the segment to test the intersection against
  54700. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54701. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54702. */
  54703. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54704. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54705. var u = segb.subtract(sega);
  54706. var v = rsegb.subtract(this.origin);
  54707. var w = sega.subtract(this.origin);
  54708. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54709. var b = BABYLON.Vector3.Dot(u, v);
  54710. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54711. var d = BABYLON.Vector3.Dot(u, w);
  54712. var e = BABYLON.Vector3.Dot(v, w);
  54713. var D = a * c - b * b; // always >= 0
  54714. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54715. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54716. // compute the line parameters of the two closest points
  54717. if (D < Ray.smallnum) { // the lines are almost parallel
  54718. sN = 0.0; // force using point P0 on segment S1
  54719. sD = 1.0; // to prevent possible division by 0.0 later
  54720. tN = e;
  54721. tD = c;
  54722. }
  54723. else { // get the closest points on the infinite lines
  54724. sN = (b * e - c * d);
  54725. tN = (a * e - b * d);
  54726. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54727. sN = 0.0;
  54728. tN = e;
  54729. tD = c;
  54730. }
  54731. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54732. sN = sD;
  54733. tN = e + b;
  54734. tD = c;
  54735. }
  54736. }
  54737. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54738. tN = 0.0;
  54739. // recompute sc for this edge
  54740. if (-d < 0.0) {
  54741. sN = 0.0;
  54742. }
  54743. else if (-d > a)
  54744. sN = sD;
  54745. else {
  54746. sN = -d;
  54747. sD = a;
  54748. }
  54749. }
  54750. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54751. tN = tD;
  54752. // recompute sc for this edge
  54753. if ((-d + b) < 0.0) {
  54754. sN = 0;
  54755. }
  54756. else if ((-d + b) > a) {
  54757. sN = sD;
  54758. }
  54759. else {
  54760. sN = (-d + b);
  54761. sD = a;
  54762. }
  54763. }
  54764. // finally do the division to get sc and tc
  54765. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54766. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54767. // get the difference of the two closest points
  54768. var qtc = v.multiplyByFloats(tc, tc, tc);
  54769. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54770. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54771. if (isIntersected) {
  54772. return qtc.length();
  54773. }
  54774. return -1;
  54775. };
  54776. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54777. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54778. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54779. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54780. this.direction.normalize();
  54781. return this;
  54782. };
  54783. // Statics
  54784. Ray.Zero = function () {
  54785. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54786. };
  54787. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54788. var result = Ray.Zero();
  54789. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54790. };
  54791. /**
  54792. * 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
  54793. * transformed to the given world matrix.
  54794. * @param origin The origin point
  54795. * @param end The end point
  54796. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54797. */
  54798. Ray.CreateNewFromTo = function (origin, end, world) {
  54799. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54800. var direction = end.subtract(origin);
  54801. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54802. direction.normalize();
  54803. return Ray.Transform(new Ray(origin, direction, length), world);
  54804. };
  54805. Ray.Transform = function (ray, matrix) {
  54806. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54807. Ray.TransformToRef(ray, matrix, result);
  54808. return result;
  54809. };
  54810. Ray.TransformToRef = function (ray, matrix, result) {
  54811. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54812. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54813. result.length = ray.length;
  54814. var dir = result.direction;
  54815. var len = dir.length();
  54816. if (!(len === 0 || len === 1)) {
  54817. var num = 1.0 / len;
  54818. dir.x *= num;
  54819. dir.y *= num;
  54820. dir.z *= num;
  54821. result.length *= len;
  54822. }
  54823. };
  54824. Ray.smallnum = 0.00000001;
  54825. Ray.rayl = 10e8;
  54826. return Ray;
  54827. }());
  54828. BABYLON.Ray = Ray;
  54829. })(BABYLON || (BABYLON = {}));
  54830. //# sourceMappingURL=babylon.ray.js.map
  54831. var BABYLON;
  54832. (function (BABYLON) {
  54833. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54834. if (boxMin.x > sphereCenter.x + sphereRadius)
  54835. return false;
  54836. if (sphereCenter.x - sphereRadius > boxMax.x)
  54837. return false;
  54838. if (boxMin.y > sphereCenter.y + sphereRadius)
  54839. return false;
  54840. if (sphereCenter.y - sphereRadius > boxMax.y)
  54841. return false;
  54842. if (boxMin.z > sphereCenter.z + sphereRadius)
  54843. return false;
  54844. if (sphereCenter.z - sphereRadius > boxMax.z)
  54845. return false;
  54846. return true;
  54847. };
  54848. var getLowestRoot = (function () {
  54849. var result = { root: 0, found: false };
  54850. return function (a, b, c, maxR) {
  54851. result.root = 0;
  54852. result.found = false;
  54853. var determinant = b * b - 4.0 * a * c;
  54854. if (determinant < 0)
  54855. return result;
  54856. var sqrtD = Math.sqrt(determinant);
  54857. var r1 = (-b - sqrtD) / (2.0 * a);
  54858. var r2 = (-b + sqrtD) / (2.0 * a);
  54859. if (r1 > r2) {
  54860. var temp = r2;
  54861. r2 = r1;
  54862. r1 = temp;
  54863. }
  54864. if (r1 > 0 && r1 < maxR) {
  54865. result.root = r1;
  54866. result.found = true;
  54867. return result;
  54868. }
  54869. if (r2 > 0 && r2 < maxR) {
  54870. result.root = r2;
  54871. result.found = true;
  54872. return result;
  54873. }
  54874. return result;
  54875. };
  54876. })();
  54877. var Collider = /** @class */ (function () {
  54878. function Collider() {
  54879. this._collisionPoint = BABYLON.Vector3.Zero();
  54880. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54881. this._tempVector = BABYLON.Vector3.Zero();
  54882. this._tempVector2 = BABYLON.Vector3.Zero();
  54883. this._tempVector3 = BABYLON.Vector3.Zero();
  54884. this._tempVector4 = BABYLON.Vector3.Zero();
  54885. this._edge = BABYLON.Vector3.Zero();
  54886. this._baseToVertex = BABYLON.Vector3.Zero();
  54887. this._destinationPoint = BABYLON.Vector3.Zero();
  54888. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54889. this._displacementVector = BABYLON.Vector3.Zero();
  54890. /** @hidden */
  54891. this._radius = BABYLON.Vector3.One();
  54892. /** @hidden */
  54893. this._retry = 0;
  54894. /** @hidden */
  54895. this._basePointWorld = BABYLON.Vector3.Zero();
  54896. this._velocityWorld = BABYLON.Vector3.Zero();
  54897. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54898. this._collisionMask = -1;
  54899. }
  54900. Object.defineProperty(Collider.prototype, "collisionMask", {
  54901. get: function () {
  54902. return this._collisionMask;
  54903. },
  54904. set: function (mask) {
  54905. this._collisionMask = !isNaN(mask) ? mask : -1;
  54906. },
  54907. enumerable: true,
  54908. configurable: true
  54909. });
  54910. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54911. /**
  54912. * Gets the plane normal used to compute the sliding response (in local space)
  54913. */
  54914. get: function () {
  54915. return this._slidePlaneNormal;
  54916. },
  54917. enumerable: true,
  54918. configurable: true
  54919. });
  54920. // Methods
  54921. /** @hidden */
  54922. Collider.prototype._initialize = function (source, dir, e) {
  54923. this._velocity = dir;
  54924. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54925. this._basePoint = source;
  54926. source.multiplyToRef(this._radius, this._basePointWorld);
  54927. dir.multiplyToRef(this._radius, this._velocityWorld);
  54928. this._velocityWorldLength = this._velocityWorld.length();
  54929. this._epsilon = e;
  54930. this.collisionFound = false;
  54931. };
  54932. /** @hidden */
  54933. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54934. pa.subtractToRef(point, this._tempVector);
  54935. pb.subtractToRef(point, this._tempVector2);
  54936. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54937. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54938. if (d < 0)
  54939. return false;
  54940. pc.subtractToRef(point, this._tempVector3);
  54941. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54942. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54943. if (d < 0)
  54944. return false;
  54945. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54946. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54947. return d >= 0;
  54948. };
  54949. /** @hidden */
  54950. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54951. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54952. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54953. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54954. return false;
  54955. }
  54956. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54957. return false;
  54958. return true;
  54959. };
  54960. /** @hidden */
  54961. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54962. var t0;
  54963. var embeddedInPlane = false;
  54964. //defensive programming, actually not needed.
  54965. if (!trianglePlaneArray) {
  54966. trianglePlaneArray = [];
  54967. }
  54968. if (!trianglePlaneArray[faceIndex]) {
  54969. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54970. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54971. }
  54972. var trianglePlane = trianglePlaneArray[faceIndex];
  54973. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54974. return;
  54975. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54976. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54977. if (normalDotVelocity == 0) {
  54978. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54979. return;
  54980. embeddedInPlane = true;
  54981. t0 = 0;
  54982. }
  54983. else {
  54984. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54985. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54986. if (t0 > t1) {
  54987. var temp = t1;
  54988. t1 = t0;
  54989. t0 = temp;
  54990. }
  54991. if (t0 > 1.0 || t1 < 0.0)
  54992. return;
  54993. if (t0 < 0)
  54994. t0 = 0;
  54995. if (t0 > 1.0)
  54996. t0 = 1.0;
  54997. }
  54998. this._collisionPoint.copyFromFloats(0, 0, 0);
  54999. var found = false;
  55000. var t = 1.0;
  55001. if (!embeddedInPlane) {
  55002. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  55003. this._velocity.scaleToRef(t0, this._tempVector);
  55004. this._planeIntersectionPoint.addInPlace(this._tempVector);
  55005. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  55006. found = true;
  55007. t = t0;
  55008. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  55009. }
  55010. }
  55011. if (!found) {
  55012. var velocitySquaredLength = this._velocity.lengthSquared();
  55013. var a = velocitySquaredLength;
  55014. this._basePoint.subtractToRef(p1, this._tempVector);
  55015. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55016. var c = this._tempVector.lengthSquared() - 1.0;
  55017. var lowestRoot = getLowestRoot(a, b, c, t);
  55018. if (lowestRoot.found) {
  55019. t = lowestRoot.root;
  55020. found = true;
  55021. this._collisionPoint.copyFrom(p1);
  55022. }
  55023. this._basePoint.subtractToRef(p2, this._tempVector);
  55024. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55025. c = this._tempVector.lengthSquared() - 1.0;
  55026. lowestRoot = getLowestRoot(a, b, c, t);
  55027. if (lowestRoot.found) {
  55028. t = lowestRoot.root;
  55029. found = true;
  55030. this._collisionPoint.copyFrom(p2);
  55031. }
  55032. this._basePoint.subtractToRef(p3, this._tempVector);
  55033. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55034. c = this._tempVector.lengthSquared() - 1.0;
  55035. lowestRoot = getLowestRoot(a, b, c, t);
  55036. if (lowestRoot.found) {
  55037. t = lowestRoot.root;
  55038. found = true;
  55039. this._collisionPoint.copyFrom(p3);
  55040. }
  55041. p2.subtractToRef(p1, this._edge);
  55042. p1.subtractToRef(this._basePoint, this._baseToVertex);
  55043. var edgeSquaredLength = this._edge.lengthSquared();
  55044. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55045. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55046. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55047. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55048. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55049. lowestRoot = getLowestRoot(a, b, c, t);
  55050. if (lowestRoot.found) {
  55051. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55052. if (f >= 0.0 && f <= 1.0) {
  55053. t = lowestRoot.root;
  55054. found = true;
  55055. this._edge.scaleInPlace(f);
  55056. p1.addToRef(this._edge, this._collisionPoint);
  55057. }
  55058. }
  55059. p3.subtractToRef(p2, this._edge);
  55060. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55061. edgeSquaredLength = this._edge.lengthSquared();
  55062. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55063. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55064. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55065. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55066. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55067. lowestRoot = getLowestRoot(a, b, c, t);
  55068. if (lowestRoot.found) {
  55069. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55070. if (f >= 0.0 && f <= 1.0) {
  55071. t = lowestRoot.root;
  55072. found = true;
  55073. this._edge.scaleInPlace(f);
  55074. p2.addToRef(this._edge, this._collisionPoint);
  55075. }
  55076. }
  55077. p1.subtractToRef(p3, this._edge);
  55078. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55079. edgeSquaredLength = this._edge.lengthSquared();
  55080. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55081. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55082. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55083. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55084. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55085. lowestRoot = getLowestRoot(a, b, c, t);
  55086. if (lowestRoot.found) {
  55087. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55088. if (f >= 0.0 && f <= 1.0) {
  55089. t = lowestRoot.root;
  55090. found = true;
  55091. this._edge.scaleInPlace(f);
  55092. p3.addToRef(this._edge, this._collisionPoint);
  55093. }
  55094. }
  55095. }
  55096. if (found) {
  55097. var distToCollision = t * this._velocity.length();
  55098. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55099. if (!this.intersectionPoint) {
  55100. this.intersectionPoint = this._collisionPoint.clone();
  55101. }
  55102. else {
  55103. this.intersectionPoint.copyFrom(this._collisionPoint);
  55104. }
  55105. this._nearestDistance = distToCollision;
  55106. this.collisionFound = true;
  55107. }
  55108. }
  55109. };
  55110. /** @hidden */
  55111. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55112. for (var i = indexStart; i < indexEnd; i += 3) {
  55113. var p1 = pts[indices[i] - decal];
  55114. var p2 = pts[indices[i + 1] - decal];
  55115. var p3 = pts[indices[i + 2] - decal];
  55116. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55117. }
  55118. };
  55119. /** @hidden */
  55120. Collider.prototype._getResponse = function (pos, vel) {
  55121. pos.addToRef(vel, this._destinationPoint);
  55122. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55123. this._basePoint.addToRef(vel, pos);
  55124. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55125. this._slidePlaneNormal.normalize();
  55126. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55127. pos.addInPlace(this._displacementVector);
  55128. this.intersectionPoint.addInPlace(this._displacementVector);
  55129. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55130. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55131. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55132. };
  55133. return Collider;
  55134. }());
  55135. BABYLON.Collider = Collider;
  55136. })(BABYLON || (BABYLON = {}));
  55137. //# sourceMappingURL=babylon.collider.js.map
  55138. var BABYLON;
  55139. (function (BABYLON) {
  55140. //WebWorker code will be inserted to this variable.
  55141. BABYLON.CollisionWorker = "";
  55142. /** Defines supported task for worker process */
  55143. var WorkerTaskType;
  55144. (function (WorkerTaskType) {
  55145. /** Initialization */
  55146. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55147. /** Update of geometry */
  55148. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55149. /** Evaluate collision */
  55150. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55151. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55152. /** Defines kind of replies returned by worker */
  55153. var WorkerReplyType;
  55154. (function (WorkerReplyType) {
  55155. /** Success */
  55156. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55157. /** Unkown error */
  55158. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55159. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55160. var CollisionCoordinatorWorker = /** @class */ (function () {
  55161. function CollisionCoordinatorWorker() {
  55162. var _this = this;
  55163. this._scaledPosition = BABYLON.Vector3.Zero();
  55164. this._scaledVelocity = BABYLON.Vector3.Zero();
  55165. this.onMeshUpdated = function (transformNode) {
  55166. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55167. };
  55168. this.onGeometryUpdated = function (geometry) {
  55169. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55170. };
  55171. this._afterRender = function () {
  55172. if (!_this._init)
  55173. return;
  55174. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55175. return;
  55176. }
  55177. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55178. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55179. if (_this._runningUpdated > 4) {
  55180. return;
  55181. }
  55182. ++_this._runningUpdated;
  55183. var payload = {
  55184. updatedMeshes: _this._addUpdateMeshesList,
  55185. updatedGeometries: _this._addUpdateGeometriesList,
  55186. removedGeometries: _this._toRemoveGeometryArray,
  55187. removedMeshes: _this._toRemoveMeshesArray
  55188. };
  55189. var message = {
  55190. payload: payload,
  55191. taskType: WorkerTaskType.UPDATE
  55192. };
  55193. var serializable = [];
  55194. for (var id in payload.updatedGeometries) {
  55195. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55196. //prepare transferables
  55197. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55198. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55199. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55200. }
  55201. }
  55202. _this._worker.postMessage(message, serializable);
  55203. _this._addUpdateMeshesList = {};
  55204. _this._addUpdateGeometriesList = {};
  55205. _this._toRemoveGeometryArray = [];
  55206. _this._toRemoveMeshesArray = [];
  55207. };
  55208. this._onMessageFromWorker = function (e) {
  55209. var returnData = e.data;
  55210. if (returnData.error != WorkerReplyType.SUCCESS) {
  55211. //TODO what errors can be returned from the worker?
  55212. BABYLON.Tools.Warn("error returned from worker!");
  55213. return;
  55214. }
  55215. switch (returnData.taskType) {
  55216. case WorkerTaskType.INIT:
  55217. _this._init = true;
  55218. //Update the worked with ALL of the scene's current state
  55219. _this._scene.meshes.forEach(function (mesh) {
  55220. _this.onMeshAdded(mesh);
  55221. });
  55222. _this._scene.getGeometries().forEach(function (geometry) {
  55223. _this.onGeometryAdded(geometry);
  55224. });
  55225. break;
  55226. case WorkerTaskType.UPDATE:
  55227. _this._runningUpdated--;
  55228. break;
  55229. case WorkerTaskType.COLLIDE:
  55230. var returnPayload = returnData.payload;
  55231. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55232. return;
  55233. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55234. if (callback) {
  55235. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55236. if (mesh) {
  55237. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55238. }
  55239. }
  55240. //cleanup
  55241. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55242. break;
  55243. }
  55244. };
  55245. this._collisionsCallbackArray = [];
  55246. this._init = false;
  55247. this._runningUpdated = 0;
  55248. this._addUpdateMeshesList = {};
  55249. this._addUpdateGeometriesList = {};
  55250. this._toRemoveGeometryArray = [];
  55251. this._toRemoveMeshesArray = [];
  55252. }
  55253. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55254. if (!this._init)
  55255. return;
  55256. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55257. return;
  55258. position.divideToRef(collider._radius, this._scaledPosition);
  55259. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55260. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55261. var payload = {
  55262. collider: {
  55263. position: this._scaledPosition.asArray(),
  55264. velocity: this._scaledVelocity.asArray(),
  55265. radius: collider._radius.asArray()
  55266. },
  55267. collisionId: collisionIndex,
  55268. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55269. maximumRetry: maximumRetry
  55270. };
  55271. var message = {
  55272. payload: payload,
  55273. taskType: WorkerTaskType.COLLIDE
  55274. };
  55275. this._worker.postMessage(message);
  55276. };
  55277. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55278. this._scene = scene;
  55279. this._scene.registerAfterRender(this._afterRender);
  55280. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55281. this._worker = new Worker(workerUrl);
  55282. this._worker.onmessage = this._onMessageFromWorker;
  55283. var message = {
  55284. payload: {},
  55285. taskType: WorkerTaskType.INIT
  55286. };
  55287. this._worker.postMessage(message);
  55288. };
  55289. CollisionCoordinatorWorker.prototype.destroy = function () {
  55290. this._scene.unregisterAfterRender(this._afterRender);
  55291. this._worker.terminate();
  55292. };
  55293. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55294. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55295. this.onMeshUpdated(mesh);
  55296. };
  55297. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55298. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55299. };
  55300. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55301. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55302. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55303. this.onGeometryUpdated(geometry);
  55304. };
  55305. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55306. this._toRemoveGeometryArray.push(geometry.id);
  55307. };
  55308. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55309. var submeshes = [];
  55310. if (mesh.subMeshes) {
  55311. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55312. var boundingInfo = sm.getBoundingInfo();
  55313. return {
  55314. position: idx,
  55315. verticesStart: sm.verticesStart,
  55316. verticesCount: sm.verticesCount,
  55317. indexStart: sm.indexStart,
  55318. indexCount: sm.indexCount,
  55319. hasMaterial: !!sm.getMaterial(),
  55320. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55321. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55322. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55323. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55324. };
  55325. });
  55326. }
  55327. var geometryId = null;
  55328. if (mesh instanceof BABYLON.Mesh) {
  55329. var geometry = mesh.geometry;
  55330. geometryId = geometry ? geometry.id : null;
  55331. }
  55332. else if (mesh instanceof BABYLON.InstancedMesh) {
  55333. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55334. geometryId = geometry ? geometry.id : null;
  55335. }
  55336. var boundingInfo = mesh.getBoundingInfo();
  55337. return {
  55338. uniqueId: mesh.uniqueId,
  55339. id: mesh.id,
  55340. name: mesh.name,
  55341. geometryId: geometryId,
  55342. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55343. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55344. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55345. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55346. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55347. subMeshes: submeshes,
  55348. checkCollisions: mesh.checkCollisions
  55349. };
  55350. };
  55351. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55352. return {
  55353. id: geometry.id,
  55354. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55355. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55356. indices: new Uint32Array(geometry.getIndices() || []),
  55357. };
  55358. };
  55359. return CollisionCoordinatorWorker;
  55360. }());
  55361. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55362. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55363. function CollisionCoordinatorLegacy() {
  55364. this._scaledPosition = BABYLON.Vector3.Zero();
  55365. this._scaledVelocity = BABYLON.Vector3.Zero();
  55366. this._finalPosition = BABYLON.Vector3.Zero();
  55367. }
  55368. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55369. position.divideToRef(collider._radius, this._scaledPosition);
  55370. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55371. collider.collidedMesh = null;
  55372. collider._retry = 0;
  55373. collider._initialVelocity = this._scaledVelocity;
  55374. collider._initialPosition = this._scaledPosition;
  55375. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55376. this._finalPosition.multiplyInPlace(collider._radius);
  55377. //run the callback
  55378. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55379. };
  55380. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55381. this._scene = scene;
  55382. };
  55383. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55384. //Legacy need no destruction method.
  55385. };
  55386. //No update in legacy mode
  55387. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55388. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55389. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55390. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55391. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55392. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55393. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55394. if (excludedMesh === void 0) { excludedMesh = null; }
  55395. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55396. if (collider._retry >= maximumRetry) {
  55397. finalPosition.copyFrom(position);
  55398. return;
  55399. }
  55400. // Check if this is a mesh else camera or -1
  55401. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55402. collider._initialize(position, velocity, closeDistance);
  55403. // Check all meshes
  55404. for (var index = 0; index < this._scene.meshes.length; index++) {
  55405. var mesh = this._scene.meshes[index];
  55406. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55407. mesh._checkCollision(collider);
  55408. }
  55409. }
  55410. if (!collider.collisionFound) {
  55411. position.addToRef(velocity, finalPosition);
  55412. return;
  55413. }
  55414. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55415. collider._getResponse(position, velocity);
  55416. }
  55417. if (velocity.length() <= closeDistance) {
  55418. finalPosition.copyFrom(position);
  55419. return;
  55420. }
  55421. collider._retry++;
  55422. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55423. };
  55424. return CollisionCoordinatorLegacy;
  55425. }());
  55426. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55427. })(BABYLON || (BABYLON = {}));
  55428. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55429. var BABYLON;
  55430. (function (BABYLON) {
  55431. /**
  55432. * A particle represents one of the element emitted by a particle system.
  55433. * This is mainly define by its coordinates, direction, velocity and age.
  55434. */
  55435. var Particle = /** @class */ (function () {
  55436. /**
  55437. * Creates a new instance Particle
  55438. * @param particleSystem the particle system the particle belongs to
  55439. */
  55440. function Particle(
  55441. /**
  55442. * particleSystem the particle system the particle belongs to.
  55443. */
  55444. particleSystem) {
  55445. this.particleSystem = particleSystem;
  55446. /**
  55447. * The world position of the particle in the scene.
  55448. */
  55449. this.position = BABYLON.Vector3.Zero();
  55450. /**
  55451. * The world direction of the particle in the scene.
  55452. */
  55453. this.direction = BABYLON.Vector3.Zero();
  55454. /**
  55455. * The color of the particle.
  55456. */
  55457. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55458. /**
  55459. * The color change of the particle per step.
  55460. */
  55461. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55462. /**
  55463. * Defines how long will the life of the particle be.
  55464. */
  55465. this.lifeTime = 1.0;
  55466. /**
  55467. * The current age of the particle.
  55468. */
  55469. this.age = 0;
  55470. /**
  55471. * The current size of the particle.
  55472. */
  55473. this.size = 0;
  55474. /**
  55475. * The current scale of the particle.
  55476. */
  55477. this.scale = new BABYLON.Vector2(1, 1);
  55478. /**
  55479. * The current angle of the particle.
  55480. */
  55481. this.angle = 0;
  55482. /**
  55483. * Defines how fast is the angle changing.
  55484. */
  55485. this.angularSpeed = 0;
  55486. /**
  55487. * Defines the cell index used by the particle to be rendered from a sprite.
  55488. */
  55489. this.cellIndex = 0;
  55490. /** @hidden */
  55491. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  55492. /** @hidden */
  55493. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  55494. /** @hidden */
  55495. this._currentSize1 = 0;
  55496. /** @hidden */
  55497. this._currentSize2 = 0;
  55498. /** @hidden */
  55499. this._currentAngularSpeed1 = 0;
  55500. /** @hidden */
  55501. this._currentAngularSpeed2 = 0;
  55502. /** @hidden */
  55503. this._currentVelocity1 = 0;
  55504. /** @hidden */
  55505. this._currentVelocity2 = 0;
  55506. /** @hidden */
  55507. this._currentLimitVelocity1 = 0;
  55508. /** @hidden */
  55509. this._currentLimitVelocity2 = 0;
  55510. if (!this.particleSystem.isAnimationSheetEnabled) {
  55511. return;
  55512. }
  55513. this.updateCellInfoFromSystem();
  55514. }
  55515. Particle.prototype.updateCellInfoFromSystem = function () {
  55516. this.cellIndex = this.particleSystem.startSpriteCellID;
  55517. };
  55518. /**
  55519. * Defines how the sprite cell index is updated for the particle
  55520. */
  55521. Particle.prototype.updateCellIndex = function () {
  55522. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  55523. var ratio = BABYLON.Scalar.Clamp(((this.age * this.particleSystem.spriteCellChangeSpeed) % this.lifeTime) / this.lifeTime);
  55524. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  55525. };
  55526. /**
  55527. * Copy the properties of particle to another one.
  55528. * @param other the particle to copy the information to.
  55529. */
  55530. Particle.prototype.copyTo = function (other) {
  55531. other.position.copyFrom(this.position);
  55532. if (this._initialDirection) {
  55533. if (other._initialDirection) {
  55534. other._initialDirection.copyFrom(this._initialDirection);
  55535. }
  55536. else {
  55537. other._initialDirection = this._initialDirection.clone();
  55538. }
  55539. }
  55540. else {
  55541. other._initialDirection = null;
  55542. }
  55543. other.direction.copyFrom(this.direction);
  55544. other.color.copyFrom(this.color);
  55545. other.colorStep.copyFrom(this.colorStep);
  55546. other.lifeTime = this.lifeTime;
  55547. other.age = this.age;
  55548. other.size = this.size;
  55549. other.scale.copyFrom(this.scale);
  55550. other.angle = this.angle;
  55551. other.angularSpeed = this.angularSpeed;
  55552. other.particleSystem = this.particleSystem;
  55553. other.cellIndex = this.cellIndex;
  55554. if (this._currentColorGradient) {
  55555. other._currentColorGradient = this._currentColorGradient;
  55556. other._currentColor1.copyFrom(this._currentColor1);
  55557. other._currentColor2.copyFrom(this._currentColor2);
  55558. }
  55559. if (this._currentSizeGradient) {
  55560. other._currentSizeGradient = this._currentSizeGradient;
  55561. other._currentSize1 = this._currentSize1;
  55562. other._currentSize2 = this._currentSize2;
  55563. }
  55564. if (this._currentAngularSpeedGradient) {
  55565. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  55566. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  55567. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  55568. }
  55569. if (this._currentVelocityGradient) {
  55570. other._currentVelocityGradient = this._currentVelocityGradient;
  55571. other._currentVelocity1 = this._currentVelocity1;
  55572. other._currentVelocity2 = this._currentVelocity2;
  55573. }
  55574. if (this._currentLimitVelocityGradient) {
  55575. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  55576. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  55577. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  55578. }
  55579. if (this.particleSystem.isAnimationSheetEnabled) {
  55580. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  55581. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  55582. }
  55583. };
  55584. return Particle;
  55585. }());
  55586. BABYLON.Particle = Particle;
  55587. })(BABYLON || (BABYLON = {}));
  55588. //# sourceMappingURL=babylon.particle.js.map
  55589. var BABYLON;
  55590. (function (BABYLON) {
  55591. /**
  55592. * This represents the base class for particle system in Babylon.
  55593. * 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.
  55594. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55595. * @example https://doc.babylonjs.com/babylon101/particles
  55596. */
  55597. var BaseParticleSystem = /** @class */ (function () {
  55598. /**
  55599. * Instantiates a particle system.
  55600. * 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.
  55601. * @param name The name of the particle system
  55602. */
  55603. function BaseParticleSystem(name) {
  55604. /**
  55605. * List of animations used by the particle system.
  55606. */
  55607. this.animations = [];
  55608. /**
  55609. * The rendering group used by the Particle system to chose when to render.
  55610. */
  55611. this.renderingGroupId = 0;
  55612. /**
  55613. * The emitter represents the Mesh or position we are attaching the particle system to.
  55614. */
  55615. this.emitter = null;
  55616. /**
  55617. * The maximum number of particles to emit per frame
  55618. */
  55619. this.emitRate = 10;
  55620. /**
  55621. * If you want to launch only a few particles at once, that can be done, as well.
  55622. */
  55623. this.manualEmitCount = -1;
  55624. /**
  55625. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55626. */
  55627. this.updateSpeed = 0.01;
  55628. /**
  55629. * The amount of time the particle system is running (depends of the overall update speed).
  55630. */
  55631. this.targetStopDuration = 0;
  55632. /**
  55633. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55634. */
  55635. this.disposeOnStop = false;
  55636. /**
  55637. * Minimum power of emitting particles.
  55638. */
  55639. this.minEmitPower = 1;
  55640. /**
  55641. * Maximum power of emitting particles.
  55642. */
  55643. this.maxEmitPower = 1;
  55644. /**
  55645. * Minimum life time of emitting particles.
  55646. */
  55647. this.minLifeTime = 1;
  55648. /**
  55649. * Maximum life time of emitting particles.
  55650. */
  55651. this.maxLifeTime = 1;
  55652. /**
  55653. * Minimum Size of emitting particles.
  55654. */
  55655. this.minSize = 1;
  55656. /**
  55657. * Maximum Size of emitting particles.
  55658. */
  55659. this.maxSize = 1;
  55660. /**
  55661. * Minimum scale of emitting particles on X axis.
  55662. */
  55663. this.minScaleX = 1;
  55664. /**
  55665. * Maximum scale of emitting particles on X axis.
  55666. */
  55667. this.maxScaleX = 1;
  55668. /**
  55669. * Minimum scale of emitting particles on Y axis.
  55670. */
  55671. this.minScaleY = 1;
  55672. /**
  55673. * Maximum scale of emitting particles on Y axis.
  55674. */
  55675. this.maxScaleY = 1;
  55676. /**
  55677. * Gets or sets the minimal initial rotation in radians.
  55678. */
  55679. this.minInitialRotation = 0;
  55680. /**
  55681. * Gets or sets the maximal initial rotation in radians.
  55682. */
  55683. this.maxInitialRotation = 0;
  55684. /**
  55685. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55686. */
  55687. this.minAngularSpeed = 0;
  55688. /**
  55689. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55690. */
  55691. this.maxAngularSpeed = 0;
  55692. /**
  55693. * The layer mask we are rendering the particles through.
  55694. */
  55695. this.layerMask = 0x0FFFFFFF;
  55696. /**
  55697. * This can help using your own shader to render the particle system.
  55698. * The according effect will be created
  55699. */
  55700. this.customShader = null;
  55701. /**
  55702. * By default particle system starts as soon as they are created. This prevents the
  55703. * automatic start to happen and let you decide when to start emitting particles.
  55704. */
  55705. this.preventAutoStart = false;
  55706. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  55707. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  55708. /**
  55709. * Callback triggered when the particle animation is ending.
  55710. */
  55711. this.onAnimationEnd = null;
  55712. /**
  55713. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55714. */
  55715. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  55716. /**
  55717. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55718. * to override the particles.
  55719. */
  55720. this.forceDepthWrite = false;
  55721. /** 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 */
  55722. this.preWarmCycles = 0;
  55723. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  55724. this.preWarmStepOffset = 1;
  55725. /**
  55726. * 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)
  55727. */
  55728. this.spriteCellChangeSpeed = 1;
  55729. /**
  55730. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  55731. */
  55732. this.startSpriteCellID = 0;
  55733. /**
  55734. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  55735. */
  55736. this.endSpriteCellID = 0;
  55737. /**
  55738. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  55739. */
  55740. this.spriteCellWidth = 0;
  55741. /**
  55742. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  55743. */
  55744. this.spriteCellHeight = 0;
  55745. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  55746. this.translationPivot = new BABYLON.Vector2(0, 0);
  55747. /**
  55748. * You can use gravity if you want to give an orientation to your particles.
  55749. */
  55750. this.gravity = BABYLON.Vector3.Zero();
  55751. this._colorGradients = null;
  55752. this._sizeGradients = null;
  55753. this._lifeTimeGradients = null;
  55754. this._angularSpeedGradients = null;
  55755. this._velocityGradients = null;
  55756. this._limitVelocityGradients = null;
  55757. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  55758. this.limitVelocityDamping = 0.4;
  55759. /**
  55760. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55761. */
  55762. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55763. /**
  55764. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55765. */
  55766. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55767. /**
  55768. * Color the particle will have at the end of its lifetime
  55769. */
  55770. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55771. /**
  55772. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  55773. */
  55774. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55775. /**
  55776. * Gets or sets the billboard mode to use when isBillboardBased = true.
  55777. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  55778. */
  55779. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  55780. this._isBillboardBased = true;
  55781. /**
  55782. * Local cache of defines for image processing.
  55783. */
  55784. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  55785. this.id = name;
  55786. this.name = name;
  55787. }
  55788. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  55789. /**
  55790. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  55791. */
  55792. get: function () {
  55793. return this._isAnimationSheetEnabled;
  55794. },
  55795. set: function (value) {
  55796. if (this._isAnimationSheetEnabled == value) {
  55797. return;
  55798. }
  55799. this._isAnimationSheetEnabled = value;
  55800. this._reset();
  55801. },
  55802. enumerable: true,
  55803. configurable: true
  55804. });
  55805. /**
  55806. * Gets the current list of limit velocity gradients.
  55807. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  55808. * @returns the list of limit velocity gradients
  55809. */
  55810. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  55811. return this._limitVelocityGradients;
  55812. };
  55813. /**
  55814. * Gets the current list of color gradients.
  55815. * You must use addColorGradient and removeColorGradient to udpate this list
  55816. * @returns the list of color gradients
  55817. */
  55818. BaseParticleSystem.prototype.getColorGradients = function () {
  55819. return this._colorGradients;
  55820. };
  55821. /**
  55822. * Gets the current list of size gradients.
  55823. * You must use addSizeGradient and removeSizeGradient to udpate this list
  55824. * @returns the list of size gradients
  55825. */
  55826. BaseParticleSystem.prototype.getSizeGradients = function () {
  55827. return this._sizeGradients;
  55828. };
  55829. /**
  55830. * Gets the current list of life time gradients.
  55831. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  55832. * @returns the list of life time gradients
  55833. */
  55834. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  55835. return this._lifeTimeGradients;
  55836. };
  55837. /**
  55838. * Gets the current list of angular speed gradients.
  55839. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  55840. * @returns the list of angular speed gradients
  55841. */
  55842. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  55843. return this._angularSpeedGradients;
  55844. };
  55845. /**
  55846. * Gets the current list of velocity gradients.
  55847. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  55848. * @returns the list of velocity gradients
  55849. */
  55850. BaseParticleSystem.prototype.getVelocityGradients = function () {
  55851. return this._velocityGradients;
  55852. };
  55853. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  55854. /**
  55855. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55856. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55857. */
  55858. get: function () {
  55859. if (this.particleEmitterType.direction1) {
  55860. return this.particleEmitterType.direction1;
  55861. }
  55862. return BABYLON.Vector3.Zero();
  55863. },
  55864. set: function (value) {
  55865. if (this.particleEmitterType.direction1) {
  55866. this.particleEmitterType.direction1 = value;
  55867. }
  55868. },
  55869. enumerable: true,
  55870. configurable: true
  55871. });
  55872. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  55873. /**
  55874. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55875. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55876. */
  55877. get: function () {
  55878. if (this.particleEmitterType.direction2) {
  55879. return this.particleEmitterType.direction2;
  55880. }
  55881. return BABYLON.Vector3.Zero();
  55882. },
  55883. set: function (value) {
  55884. if (this.particleEmitterType.direction2) {
  55885. this.particleEmitterType.direction2 = value;
  55886. }
  55887. },
  55888. enumerable: true,
  55889. configurable: true
  55890. });
  55891. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  55892. /**
  55893. * 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.
  55894. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55895. */
  55896. get: function () {
  55897. if (this.particleEmitterType.minEmitBox) {
  55898. return this.particleEmitterType.minEmitBox;
  55899. }
  55900. return BABYLON.Vector3.Zero();
  55901. },
  55902. set: function (value) {
  55903. if (this.particleEmitterType.minEmitBox) {
  55904. this.particleEmitterType.minEmitBox = value;
  55905. }
  55906. },
  55907. enumerable: true,
  55908. configurable: true
  55909. });
  55910. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  55911. /**
  55912. * 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.
  55913. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55914. */
  55915. get: function () {
  55916. if (this.particleEmitterType.maxEmitBox) {
  55917. return this.particleEmitterType.maxEmitBox;
  55918. }
  55919. return BABYLON.Vector3.Zero();
  55920. },
  55921. set: function (value) {
  55922. if (this.particleEmitterType.maxEmitBox) {
  55923. this.particleEmitterType.maxEmitBox = value;
  55924. }
  55925. },
  55926. enumerable: true,
  55927. configurable: true
  55928. });
  55929. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  55930. /**
  55931. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55932. */
  55933. get: function () {
  55934. return this._isBillboardBased;
  55935. },
  55936. set: function (value) {
  55937. if (this._isBillboardBased === value) {
  55938. return;
  55939. }
  55940. this._isBillboardBased = value;
  55941. this._reset();
  55942. },
  55943. enumerable: true,
  55944. configurable: true
  55945. });
  55946. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  55947. /**
  55948. * Gets the image processing configuration used either in this material.
  55949. */
  55950. get: function () {
  55951. return this._imageProcessingConfiguration;
  55952. },
  55953. /**
  55954. * Sets the Default image processing configuration used either in the this material.
  55955. *
  55956. * If sets to null, the scene one is in use.
  55957. */
  55958. set: function (value) {
  55959. this._attachImageProcessingConfiguration(value);
  55960. },
  55961. enumerable: true,
  55962. configurable: true
  55963. });
  55964. /**
  55965. * Attaches a new image processing configuration to the Standard Material.
  55966. * @param configuration
  55967. */
  55968. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  55969. if (configuration === this._imageProcessingConfiguration) {
  55970. return;
  55971. }
  55972. // Pick the scene configuration if needed.
  55973. if (!configuration) {
  55974. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  55975. }
  55976. else {
  55977. this._imageProcessingConfiguration = configuration;
  55978. }
  55979. };
  55980. /** @hidden */
  55981. BaseParticleSystem.prototype._reset = function () {
  55982. };
  55983. /**
  55984. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  55985. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  55986. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  55987. * @returns the emitter
  55988. */
  55989. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  55990. var particleEmitter = new BABYLON.PointParticleEmitter();
  55991. particleEmitter.direction1 = direction1;
  55992. particleEmitter.direction2 = direction2;
  55993. this.particleEmitterType = particleEmitter;
  55994. return particleEmitter;
  55995. };
  55996. /**
  55997. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  55998. * @param radius The radius of the hemisphere to emit from
  55999. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  56000. * @returns the emitter
  56001. */
  56002. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  56003. if (radius === void 0) { radius = 1; }
  56004. if (radiusRange === void 0) { radiusRange = 1; }
  56005. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  56006. this.particleEmitterType = particleEmitter;
  56007. return particleEmitter;
  56008. };
  56009. /**
  56010. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  56011. * @param radius The radius of the sphere to emit from
  56012. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  56013. * @returns the emitter
  56014. */
  56015. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  56016. if (radius === void 0) { radius = 1; }
  56017. if (radiusRange === void 0) { radiusRange = 1; }
  56018. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  56019. this.particleEmitterType = particleEmitter;
  56020. return particleEmitter;
  56021. };
  56022. /**
  56023. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  56024. * @param radius The radius of the sphere to emit from
  56025. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56026. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56027. * @returns the emitter
  56028. */
  56029. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56030. if (radius === void 0) { radius = 1; }
  56031. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56032. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56033. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56034. this.particleEmitterType = particleEmitter;
  56035. return particleEmitter;
  56036. };
  56037. /**
  56038. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  56039. * @param radius The radius of the cone to emit from
  56040. * @param angle The base angle of the cone
  56041. * @returns the emitter
  56042. */
  56043. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56044. if (radius === void 0) { radius = 1; }
  56045. if (angle === void 0) { angle = Math.PI / 4; }
  56046. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56047. this.particleEmitterType = particleEmitter;
  56048. return particleEmitter;
  56049. };
  56050. /**
  56051. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56052. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56053. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56054. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56055. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56056. * @returns the emitter
  56057. */
  56058. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56059. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56060. this.particleEmitterType = particleEmitter;
  56061. this.direction1 = direction1;
  56062. this.direction2 = direction2;
  56063. this.minEmitBox = minEmitBox;
  56064. this.maxEmitBox = maxEmitBox;
  56065. return particleEmitter;
  56066. };
  56067. /**
  56068. * Source color is added to the destination color without alpha affecting the result.
  56069. */
  56070. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  56071. /**
  56072. * Blend current color and particle color using particle’s alpha.
  56073. */
  56074. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  56075. /**
  56076. * Add current color and particle color multiplied by particle’s alpha.
  56077. */
  56078. BaseParticleSystem.BLENDMODE_ADD = 2;
  56079. return BaseParticleSystem;
  56080. }());
  56081. BABYLON.BaseParticleSystem = BaseParticleSystem;
  56082. })(BABYLON || (BABYLON = {}));
  56083. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  56084. var BABYLON;
  56085. (function (BABYLON) {
  56086. /**
  56087. * This represents a particle system in Babylon.
  56088. * 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.
  56089. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  56090. * @example https://doc.babylonjs.com/babylon101/particles
  56091. */
  56092. var ParticleSystem = /** @class */ (function (_super) {
  56093. __extends(ParticleSystem, _super);
  56094. /**
  56095. * Instantiates a particle system.
  56096. * 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.
  56097. * @param name The name of the particle system
  56098. * @param capacity The max number of particles alive at the same time
  56099. * @param scene The scene the particle system belongs to
  56100. * @param customEffect a custom effect used to change the way particles are rendered by default
  56101. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  56102. * @param epsilon Offset used to render the particles
  56103. */
  56104. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  56105. if (customEffect === void 0) { customEffect = null; }
  56106. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56107. if (epsilon === void 0) { epsilon = 0.01; }
  56108. var _this = _super.call(this, name) || this;
  56109. /**
  56110. * An event triggered when the system is disposed
  56111. */
  56112. _this.onDisposeObservable = new BABYLON.Observable();
  56113. _this._particles = new Array();
  56114. _this._stockParticles = new Array();
  56115. _this._newPartsExcess = 0;
  56116. _this._vertexBuffers = {};
  56117. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  56118. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  56119. _this._scaledDirection = BABYLON.Vector3.Zero();
  56120. _this._scaledGravity = BABYLON.Vector3.Zero();
  56121. _this._currentRenderId = -1;
  56122. _this._useInstancing = false;
  56123. _this._started = false;
  56124. _this._stopped = false;
  56125. _this._actualFrame = 0;
  56126. // start of sub system methods
  56127. /**
  56128. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  56129. * Its lifetime will start back at 0.
  56130. */
  56131. _this.recycleParticle = function (particle) {
  56132. var lastParticle = _this._particles.pop();
  56133. if (lastParticle !== particle) {
  56134. lastParticle.copyTo(particle);
  56135. }
  56136. _this._stockParticles.push(lastParticle);
  56137. };
  56138. _this._createParticle = function () {
  56139. var particle;
  56140. if (_this._stockParticles.length !== 0) {
  56141. particle = _this._stockParticles.pop();
  56142. particle.age = 0;
  56143. particle._currentColorGradient = null;
  56144. particle.cellIndex = _this.startSpriteCellID;
  56145. }
  56146. else {
  56147. particle = new BABYLON.Particle(_this);
  56148. }
  56149. return particle;
  56150. };
  56151. _this._emitFromParticle = function (particle) {
  56152. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  56153. return;
  56154. }
  56155. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  56156. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  56157. subSystem._rootParticleSystem = _this;
  56158. _this.activeSubSystems.push(subSystem);
  56159. subSystem.start();
  56160. };
  56161. _this._capacity = capacity;
  56162. _this._epsilon = epsilon;
  56163. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  56164. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56165. // Setup the default processing configuration to the scene.
  56166. _this._attachImageProcessingConfiguration(null);
  56167. _this._customEffect = customEffect;
  56168. _this._scene.particleSystems.push(_this);
  56169. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  56170. _this._createIndexBuffer();
  56171. _this._createVertexBuffers();
  56172. // Default emitter type
  56173. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56174. _this.updateFunction = function (particles) {
  56175. var noiseTextureData = null;
  56176. var noiseTextureSize = null;
  56177. if (_this.noiseTexture) { // We need to get texture data back to CPU
  56178. noiseTextureData = (_this.noiseTexture.readPixels());
  56179. noiseTextureSize = _this.noiseTexture.getSize();
  56180. }
  56181. var _loop_1 = function () {
  56182. particle = particles[index];
  56183. particle.age += _this._scaledUpdateSpeed;
  56184. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  56185. _this._emitFromParticle(particle);
  56186. _this.recycleParticle(particle);
  56187. index--;
  56188. return "continue";
  56189. }
  56190. else {
  56191. var ratio = particle.age / particle.lifeTime;
  56192. // Color
  56193. if (_this._colorGradients && _this._colorGradients.length > 0) {
  56194. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  56195. if (currentGradient !== particle._currentColorGradient) {
  56196. particle._currentColor1.copyFrom(particle._currentColor2);
  56197. nextGradient.getColorToRef(particle._currentColor2);
  56198. particle._currentColorGradient = currentGradient;
  56199. }
  56200. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  56201. });
  56202. }
  56203. else {
  56204. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  56205. particle.color.addInPlace(_this._scaledColorStep);
  56206. if (particle.color.a < 0) {
  56207. particle.color.a = 0;
  56208. }
  56209. }
  56210. // Angular speed
  56211. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  56212. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  56213. if (currentGradient !== particle._currentAngularSpeedGradient) {
  56214. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  56215. particle._currentAngularSpeed2 = nextGradient.getFactor();
  56216. particle._currentAngularSpeedGradient = currentGradient;
  56217. }
  56218. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  56219. });
  56220. }
  56221. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  56222. // Direction
  56223. var directionScale_1 = _this._scaledUpdateSpeed;
  56224. /// Velocity
  56225. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  56226. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  56227. if (currentGradient !== particle._currentVelocityGradient) {
  56228. particle._currentVelocity1 = particle._currentVelocity2;
  56229. particle._currentVelocity2 = nextGradient.getFactor();
  56230. particle._currentVelocityGradient = currentGradient;
  56231. }
  56232. directionScale_1 *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  56233. });
  56234. }
  56235. particle.direction.scaleToRef(directionScale_1, _this._scaledDirection);
  56236. /// Limit velocity
  56237. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  56238. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  56239. if (currentGradient !== particle._currentLimitVelocityGradient) {
  56240. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  56241. particle._currentLimitVelocity2 = nextGradient.getFactor();
  56242. particle._currentLimitVelocityGradient = currentGradient;
  56243. }
  56244. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  56245. var currentVelocity = particle.direction.length();
  56246. if (currentVelocity > limitVelocity) {
  56247. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  56248. }
  56249. });
  56250. }
  56251. particle.position.addInPlace(_this._scaledDirection);
  56252. // Noise
  56253. if (noiseTextureData && noiseTextureSize) {
  56254. var localPosition = BABYLON.Tmp.Vector3[0];
  56255. var emitterPosition = BABYLON.Tmp.Vector3[1];
  56256. _this._emitterWorldMatrix.getTranslationToRef(emitterPosition);
  56257. particle.position.subtractToRef(emitterPosition, localPosition);
  56258. var fetchedColorR = _this._fetchR(localPosition.y, localPosition.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56259. var fetchedColorG = _this._fetchR(localPosition.x + 0.33, localPosition.z + 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56260. var fetchedColorB = _this._fetchR(localPosition.x - 0.33, localPosition.y - 0.33, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  56261. var force = BABYLON.Tmp.Vector3[0];
  56262. var scaledForce = BABYLON.Tmp.Vector3[1];
  56263. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  56264. force.scaleToRef(_this._scaledUpdateSpeed, scaledForce);
  56265. particle.direction.addInPlace(scaledForce);
  56266. }
  56267. // Gravity
  56268. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  56269. particle.direction.addInPlace(_this._scaledGravity);
  56270. // Size
  56271. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  56272. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  56273. if (currentGradient !== particle._currentSizeGradient) {
  56274. particle._currentSize1 = particle._currentSize2;
  56275. particle._currentSize2 = nextGradient.getFactor();
  56276. particle._currentSizeGradient = currentGradient;
  56277. }
  56278. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  56279. });
  56280. }
  56281. if (_this._isAnimationSheetEnabled) {
  56282. particle.updateCellIndex();
  56283. }
  56284. }
  56285. };
  56286. var particle;
  56287. for (var index = 0; index < particles.length; index++) {
  56288. _loop_1();
  56289. }
  56290. };
  56291. return _this;
  56292. }
  56293. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  56294. /**
  56295. * Sets a callback that will be triggered when the system is disposed
  56296. */
  56297. set: function (callback) {
  56298. if (this._onDisposeObserver) {
  56299. this.onDisposeObservable.remove(this._onDisposeObserver);
  56300. }
  56301. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56302. },
  56303. enumerable: true,
  56304. configurable: true
  56305. });
  56306. /**
  56307. * Get hosting scene
  56308. * @returns the scene
  56309. */
  56310. ParticleSystem.prototype.getScene = function () {
  56311. return this._scene;
  56312. };
  56313. Object.defineProperty(ParticleSystem.prototype, "particles", {
  56314. //end of Sub-emitter
  56315. /**
  56316. * Gets the current list of active particles
  56317. */
  56318. get: function () {
  56319. return this._particles;
  56320. },
  56321. enumerable: true,
  56322. configurable: true
  56323. });
  56324. /**
  56325. * Returns the string "ParticleSystem"
  56326. * @returns a string containing the class name
  56327. */
  56328. ParticleSystem.prototype.getClassName = function () {
  56329. return "ParticleSystem";
  56330. };
  56331. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  56332. var newGradient = new BABYLON.FactorGradient();
  56333. newGradient.gradient = gradient;
  56334. newGradient.factor1 = factor;
  56335. newGradient.factor2 = factor2;
  56336. factorGradients.push(newGradient);
  56337. factorGradients.sort(function (a, b) {
  56338. if (a.gradient < b.gradient) {
  56339. return -1;
  56340. }
  56341. else if (a.gradient > b.gradient) {
  56342. return 1;
  56343. }
  56344. return 0;
  56345. });
  56346. };
  56347. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  56348. if (!factorGradients) {
  56349. return;
  56350. }
  56351. var index = 0;
  56352. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  56353. var factorGradient = factorGradients_1[_i];
  56354. if (factorGradient.gradient === gradient) {
  56355. factorGradients.splice(index, 1);
  56356. break;
  56357. }
  56358. index++;
  56359. }
  56360. };
  56361. /**
  56362. * Adds a new life time gradient
  56363. * @param gradient defines the gradient to use (between 0 and 1)
  56364. * @param factor defines the life time factor to affect to the specified gradient
  56365. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56366. * @returns the current particle system
  56367. */
  56368. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  56369. if (!this._lifeTimeGradients) {
  56370. this._lifeTimeGradients = [];
  56371. }
  56372. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  56373. return this;
  56374. };
  56375. /**
  56376. * Remove a specific life time gradient
  56377. * @param gradient defines the gradient to remove
  56378. * @returns the current particle system
  56379. */
  56380. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  56381. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  56382. return this;
  56383. };
  56384. /**
  56385. * Adds a new size gradient
  56386. * @param gradient defines the gradient to use (between 0 and 1)
  56387. * @param factor defines the size factor to affect to the specified gradient
  56388. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56389. * @returns the current particle system
  56390. */
  56391. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  56392. if (!this._sizeGradients) {
  56393. this._sizeGradients = [];
  56394. }
  56395. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  56396. return this;
  56397. };
  56398. /**
  56399. * Remove a specific size gradient
  56400. * @param gradient defines the gradient to remove
  56401. * @returns the current particle system
  56402. */
  56403. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  56404. this._removeFactorGradient(this._sizeGradients, gradient);
  56405. return this;
  56406. };
  56407. /**
  56408. * Adds a new angular speed gradient
  56409. * @param gradient defines the gradient to use (between 0 and 1)
  56410. * @param factor defines the angular speed to affect to the specified gradient
  56411. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56412. * @returns the current particle system
  56413. */
  56414. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  56415. if (!this._angularSpeedGradients) {
  56416. this._angularSpeedGradients = [];
  56417. }
  56418. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  56419. return this;
  56420. };
  56421. /**
  56422. * Remove a specific angular speed gradient
  56423. * @param gradient defines the gradient to remove
  56424. * @returns the current particle system
  56425. */
  56426. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  56427. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  56428. return this;
  56429. };
  56430. /**
  56431. * Adds a new velocity gradient
  56432. * @param gradient defines the gradient to use (between 0 and 1)
  56433. * @param factor defines the velocity to affect to the specified gradient
  56434. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56435. * @returns the current particle system
  56436. */
  56437. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  56438. if (!this._velocityGradients) {
  56439. this._velocityGradients = [];
  56440. }
  56441. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  56442. return this;
  56443. };
  56444. /**
  56445. * Remove a specific velocity gradient
  56446. * @param gradient defines the gradient to remove
  56447. * @returns the current particle system
  56448. */
  56449. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  56450. this._removeFactorGradient(this._velocityGradients, gradient);
  56451. return this;
  56452. };
  56453. /**
  56454. * Adds a new limit velocity gradient
  56455. * @param gradient defines the gradient to use (between 0 and 1)
  56456. * @param factor defines the limit velocity value to affect to the specified gradient
  56457. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  56458. * @returns the current particle system
  56459. */
  56460. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  56461. if (!this._limitVelocityGradients) {
  56462. this._limitVelocityGradients = [];
  56463. }
  56464. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  56465. return this;
  56466. };
  56467. /**
  56468. * Remove a specific limit velocity gradient
  56469. * @param gradient defines the gradient to remove
  56470. * @returns the current particle system
  56471. */
  56472. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  56473. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  56474. return this;
  56475. };
  56476. /**
  56477. * Adds a new color gradient
  56478. * @param gradient defines the gradient to use (between 0 and 1)
  56479. * @param color defines the color to affect to the specified gradient
  56480. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  56481. */
  56482. ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {
  56483. if (!this._colorGradients) {
  56484. this._colorGradients = [];
  56485. }
  56486. var colorGradient = new BABYLON.ColorGradient();
  56487. colorGradient.gradient = gradient;
  56488. colorGradient.color1 = color;
  56489. colorGradient.color2 = color2;
  56490. this._colorGradients.push(colorGradient);
  56491. this._colorGradients.sort(function (a, b) {
  56492. if (a.gradient < b.gradient) {
  56493. return -1;
  56494. }
  56495. else if (a.gradient > b.gradient) {
  56496. return 1;
  56497. }
  56498. return 0;
  56499. });
  56500. return this;
  56501. };
  56502. /**
  56503. * Remove a specific color gradient
  56504. * @param gradient defines the gradient to remove
  56505. */
  56506. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  56507. if (!this._colorGradients) {
  56508. return this;
  56509. }
  56510. var index = 0;
  56511. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  56512. var colorGradient = _a[_i];
  56513. if (colorGradient.gradient === gradient) {
  56514. this._colorGradients.splice(index, 1);
  56515. break;
  56516. }
  56517. index++;
  56518. }
  56519. return this;
  56520. };
  56521. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  56522. u = Math.abs(u) * 0.5 + 0.5;
  56523. v = Math.abs(v) * 0.5 + 0.5;
  56524. var wrappedU = ((u * width) % width) | 0;
  56525. var wrappedV = ((v * height) % height) | 0;
  56526. var position = (wrappedU + wrappedV * width) * 4;
  56527. return pixels[position] / 255;
  56528. };
  56529. ParticleSystem.prototype._reset = function () {
  56530. this._resetEffect();
  56531. };
  56532. ParticleSystem.prototype._resetEffect = function () {
  56533. if (this._vertexBuffer) {
  56534. this._vertexBuffer.dispose();
  56535. this._vertexBuffer = null;
  56536. }
  56537. if (this._spriteBuffer) {
  56538. this._spriteBuffer.dispose();
  56539. this._spriteBuffer = null;
  56540. }
  56541. this._createVertexBuffers();
  56542. };
  56543. ParticleSystem.prototype._createVertexBuffers = function () {
  56544. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  56545. if (this._isAnimationSheetEnabled) {
  56546. this._vertexBufferSize += 1;
  56547. }
  56548. if (!this._isBillboardBased) {
  56549. this._vertexBufferSize += 3;
  56550. }
  56551. var engine = this._scene.getEngine();
  56552. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  56553. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  56554. var dataOffset = 0;
  56555. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  56556. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56557. dataOffset += 3;
  56558. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  56559. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56560. dataOffset += 4;
  56561. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  56562. this._vertexBuffers["angle"] = options;
  56563. dataOffset += 1;
  56564. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  56565. this._vertexBuffers["size"] = size;
  56566. dataOffset += 2;
  56567. if (this._isAnimationSheetEnabled) {
  56568. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  56569. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  56570. dataOffset += 1;
  56571. }
  56572. if (!this._isBillboardBased) {
  56573. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  56574. this._vertexBuffers["direction"] = directionBuffer;
  56575. dataOffset += 3;
  56576. }
  56577. var offsets;
  56578. if (this._useInstancing) {
  56579. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  56580. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  56581. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  56582. }
  56583. else {
  56584. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  56585. dataOffset += 2;
  56586. }
  56587. this._vertexBuffers["offset"] = offsets;
  56588. };
  56589. ParticleSystem.prototype._createIndexBuffer = function () {
  56590. if (this._useInstancing) {
  56591. return;
  56592. }
  56593. var indices = [];
  56594. var index = 0;
  56595. for (var count = 0; count < this._capacity; count++) {
  56596. indices.push(index);
  56597. indices.push(index + 1);
  56598. indices.push(index + 2);
  56599. indices.push(index);
  56600. indices.push(index + 2);
  56601. indices.push(index + 3);
  56602. index += 4;
  56603. }
  56604. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  56605. };
  56606. /**
  56607. * Gets the maximum number of particles active at the same time.
  56608. * @returns The max number of active particles.
  56609. */
  56610. ParticleSystem.prototype.getCapacity = function () {
  56611. return this._capacity;
  56612. };
  56613. /**
  56614. * Gets whether there are still active particles in the system.
  56615. * @returns True if it is alive, otherwise false.
  56616. */
  56617. ParticleSystem.prototype.isAlive = function () {
  56618. return this._alive;
  56619. };
  56620. /**
  56621. * Gets whether the system has been started.
  56622. * @returns True if it has been started, otherwise false.
  56623. */
  56624. ParticleSystem.prototype.isStarted = function () {
  56625. return this._started;
  56626. };
  56627. /**
  56628. * Starts the particle system and begins to emit
  56629. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  56630. */
  56631. ParticleSystem.prototype.start = function (delay) {
  56632. var _this = this;
  56633. if (delay === void 0) { delay = 0; }
  56634. if (delay) {
  56635. setTimeout(function () {
  56636. _this.start(0);
  56637. }, delay);
  56638. return;
  56639. }
  56640. this._started = true;
  56641. this._stopped = false;
  56642. this._actualFrame = 0;
  56643. if (this.subEmitters && this.subEmitters.length != 0) {
  56644. this.activeSubSystems = new Array();
  56645. }
  56646. if (this.preWarmCycles) {
  56647. for (var index = 0; index < this.preWarmCycles; index++) {
  56648. this.animate(true);
  56649. }
  56650. }
  56651. };
  56652. /**
  56653. * Stops the particle system.
  56654. * @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.
  56655. */
  56656. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  56657. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  56658. this._stopped = true;
  56659. if (stopSubEmitters) {
  56660. this._stopSubEmitters();
  56661. }
  56662. };
  56663. // animation sheet
  56664. /**
  56665. * Remove all active particles
  56666. */
  56667. ParticleSystem.prototype.reset = function () {
  56668. this._stockParticles = [];
  56669. this._particles = [];
  56670. };
  56671. /**
  56672. * @hidden (for internal use only)
  56673. */
  56674. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  56675. var offset = index * this._vertexBufferSize;
  56676. this._vertexData[offset++] = particle.position.x;
  56677. this._vertexData[offset++] = particle.position.y;
  56678. this._vertexData[offset++] = particle.position.z;
  56679. this._vertexData[offset++] = particle.color.r;
  56680. this._vertexData[offset++] = particle.color.g;
  56681. this._vertexData[offset++] = particle.color.b;
  56682. this._vertexData[offset++] = particle.color.a;
  56683. this._vertexData[offset++] = particle.angle;
  56684. this._vertexData[offset++] = particle.scale.x * particle.size;
  56685. this._vertexData[offset++] = particle.scale.y * particle.size;
  56686. if (this._isAnimationSheetEnabled) {
  56687. this._vertexData[offset++] = particle.cellIndex;
  56688. }
  56689. if (!this._isBillboardBased) {
  56690. if (particle._initialDirection) {
  56691. this._vertexData[offset++] = particle._initialDirection.x;
  56692. this._vertexData[offset++] = particle._initialDirection.y;
  56693. this._vertexData[offset++] = particle._initialDirection.z;
  56694. }
  56695. else {
  56696. this._vertexData[offset++] = particle.direction.x;
  56697. this._vertexData[offset++] = particle.direction.y;
  56698. this._vertexData[offset++] = particle.direction.z;
  56699. }
  56700. }
  56701. if (!this._useInstancing) {
  56702. if (this._isAnimationSheetEnabled) {
  56703. if (offsetX === 0)
  56704. offsetX = this._epsilon;
  56705. else if (offsetX === 1)
  56706. offsetX = 1 - this._epsilon;
  56707. if (offsetY === 0)
  56708. offsetY = this._epsilon;
  56709. else if (offsetY === 1)
  56710. offsetY = 1 - this._epsilon;
  56711. }
  56712. this._vertexData[offset++] = offsetX;
  56713. this._vertexData[offset++] = offsetY;
  56714. }
  56715. };
  56716. ParticleSystem.prototype._stopSubEmitters = function () {
  56717. if (!this.activeSubSystems) {
  56718. return;
  56719. }
  56720. this.activeSubSystems.forEach(function (subSystem) {
  56721. subSystem.stop(true);
  56722. });
  56723. this.activeSubSystems = new Array();
  56724. };
  56725. ParticleSystem.prototype._removeFromRoot = function () {
  56726. if (!this._rootParticleSystem) {
  56727. return;
  56728. }
  56729. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56730. if (index !== -1) {
  56731. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56732. }
  56733. };
  56734. // End of sub system methods
  56735. ParticleSystem.prototype._update = function (newParticles) {
  56736. // Update current
  56737. this._alive = this._particles.length > 0;
  56738. if (this.emitter.position) {
  56739. var emitterMesh = this.emitter;
  56740. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  56741. }
  56742. else {
  56743. var emitterPosition = this.emitter;
  56744. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56745. }
  56746. this.updateFunction(this._particles);
  56747. // Add new ones
  56748. var particle;
  56749. var _loop_2 = function () {
  56750. if (this_1._particles.length === this_1._capacity) {
  56751. return "break";
  56752. }
  56753. particle = this_1._createParticle();
  56754. this_1._particles.push(particle);
  56755. // Emitter
  56756. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  56757. if (this_1.startPositionFunction) {
  56758. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  56759. }
  56760. else {
  56761. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  56762. }
  56763. if (this_1.startDirectionFunction) {
  56764. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  56765. }
  56766. else {
  56767. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  56768. }
  56769. if (emitPower === 0) {
  56770. if (!particle._initialDirection) {
  56771. particle._initialDirection = particle.direction.clone();
  56772. }
  56773. else {
  56774. particle._initialDirection.copyFrom(particle.direction);
  56775. }
  56776. }
  56777. else {
  56778. particle._initialDirection = null;
  56779. }
  56780. particle.direction.scaleInPlace(emitPower);
  56781. // Life time
  56782. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  56783. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  56784. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  56785. var factorGradient1 = currentGradient;
  56786. var factorGradient2 = nextGradient;
  56787. var lifeTime1 = factorGradient1.getFactor();
  56788. var lifeTime2 = factorGradient2.getFactor();
  56789. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  56790. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  56791. });
  56792. }
  56793. else {
  56794. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  56795. }
  56796. // Size
  56797. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  56798. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  56799. }
  56800. else {
  56801. particle._currentSizeGradient = this_1._sizeGradients[0];
  56802. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  56803. particle.size = particle._currentSize1;
  56804. if (this_1._sizeGradients.length > 1) {
  56805. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  56806. }
  56807. else {
  56808. particle._currentSize2 = particle._currentSize1;
  56809. }
  56810. }
  56811. // Size and scale
  56812. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  56813. // Angle
  56814. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  56815. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  56816. }
  56817. else {
  56818. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  56819. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  56820. particle._currentAngularSpeed1 = particle.angularSpeed;
  56821. if (this_1._angularSpeedGradients.length > 1) {
  56822. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  56823. }
  56824. else {
  56825. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  56826. }
  56827. }
  56828. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  56829. // Velocity
  56830. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  56831. particle._currentVelocityGradient = this_1._velocityGradients[0];
  56832. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  56833. if (this_1._velocityGradients.length > 1) {
  56834. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  56835. }
  56836. else {
  56837. particle._currentVelocity2 = particle._currentVelocity1;
  56838. }
  56839. }
  56840. // Limit velocity
  56841. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  56842. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  56843. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  56844. if (this_1._limitVelocityGradients.length > 1) {
  56845. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  56846. }
  56847. else {
  56848. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  56849. }
  56850. }
  56851. // Color
  56852. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  56853. step = BABYLON.Scalar.RandomRange(0, 1.0);
  56854. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  56855. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  56856. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  56857. }
  56858. else {
  56859. particle._currentColorGradient = this_1._colorGradients[0];
  56860. particle._currentColorGradient.getColorToRef(particle.color);
  56861. particle._currentColor1.copyFrom(particle.color);
  56862. if (this_1._colorGradients.length > 1) {
  56863. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  56864. }
  56865. else {
  56866. particle._currentColor2.copyFrom(particle.color);
  56867. }
  56868. }
  56869. // Sheet
  56870. if (this_1._isAnimationSheetEnabled) {
  56871. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  56872. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  56873. }
  56874. };
  56875. var this_1 = this, step;
  56876. for (var index = 0; index < newParticles; index++) {
  56877. var state_1 = _loop_2();
  56878. if (state_1 === "break")
  56879. break;
  56880. }
  56881. };
  56882. /** @hidden */
  56883. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased) {
  56884. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56885. if (isBillboardBased === void 0) { isBillboardBased = false; }
  56886. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  56887. if (isAnimationSheetEnabled) {
  56888. attributeNamesOrOptions.push("cellIndex");
  56889. }
  56890. if (!isBillboardBased) {
  56891. attributeNamesOrOptions.push("direction");
  56892. }
  56893. return attributeNamesOrOptions;
  56894. };
  56895. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  56896. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56897. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  56898. if (isAnimationSheetEnabled) {
  56899. effectCreationOption.push("particlesInfos");
  56900. }
  56901. return effectCreationOption;
  56902. };
  56903. ParticleSystem.prototype._getEffect = function () {
  56904. if (this._customEffect) {
  56905. return this._customEffect;
  56906. }
  56907. ;
  56908. var defines = [];
  56909. if (this._scene.clipPlane) {
  56910. defines.push("#define CLIPPLANE");
  56911. }
  56912. if (this._scene.clipPlane2) {
  56913. defines.push("#define CLIPPLANE2");
  56914. }
  56915. if (this._scene.clipPlane3) {
  56916. defines.push("#define CLIPPLANE3");
  56917. }
  56918. if (this._scene.clipPlane4) {
  56919. defines.push("#define CLIPPLANE4");
  56920. }
  56921. if (this._isAnimationSheetEnabled) {
  56922. defines.push("#define ANIMATESHEET");
  56923. }
  56924. if (this._isBillboardBased) {
  56925. defines.push("#define BILLBOARD");
  56926. switch (this.billboardMode) {
  56927. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  56928. defines.push("#define BILLBOARDY");
  56929. break;
  56930. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  56931. default:
  56932. break;
  56933. }
  56934. }
  56935. if (this._imageProcessingConfiguration) {
  56936. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  56937. defines.push(this._imageProcessingConfigurationDefines.toString());
  56938. }
  56939. // Effect
  56940. var join = defines.join("\n");
  56941. if (this._cachedDefines !== join) {
  56942. this._cachedDefines = join;
  56943. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased);
  56944. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  56945. var samplers = ["diffuseSampler"];
  56946. if (BABYLON.ImageProcessingConfiguration) {
  56947. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  56948. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  56949. }
  56950. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56951. }
  56952. return this._effect;
  56953. };
  56954. /**
  56955. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56956. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  56957. */
  56958. ParticleSystem.prototype.animate = function (preWarmOnly) {
  56959. if (preWarmOnly === void 0) { preWarmOnly = false; }
  56960. if (!this._started)
  56961. return;
  56962. if (!preWarmOnly) {
  56963. var effect = this._getEffect();
  56964. // Check
  56965. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56966. return;
  56967. if (this._currentRenderId === this._scene.getRenderId()) {
  56968. return;
  56969. }
  56970. this._currentRenderId = this._scene.getRenderId();
  56971. }
  56972. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  56973. // determine the number of particles we need to create
  56974. var newParticles;
  56975. if (this.manualEmitCount > -1) {
  56976. newParticles = this.manualEmitCount;
  56977. this._newPartsExcess = 0;
  56978. this.manualEmitCount = 0;
  56979. }
  56980. else {
  56981. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56982. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56983. }
  56984. if (this._newPartsExcess > 1.0) {
  56985. newParticles += this._newPartsExcess >> 0;
  56986. this._newPartsExcess -= this._newPartsExcess >> 0;
  56987. }
  56988. this._alive = false;
  56989. if (!this._stopped) {
  56990. this._actualFrame += this._scaledUpdateSpeed;
  56991. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56992. this.stop();
  56993. }
  56994. else {
  56995. newParticles = 0;
  56996. }
  56997. this._update(newParticles);
  56998. // Stopped?
  56999. if (this._stopped) {
  57000. if (!this._alive) {
  57001. this._started = false;
  57002. if (this.onAnimationEnd) {
  57003. this.onAnimationEnd();
  57004. }
  57005. if (this.disposeOnStop) {
  57006. this._scene._toBeDisposed.push(this);
  57007. }
  57008. }
  57009. }
  57010. if (!preWarmOnly) {
  57011. // Update VBO
  57012. var offset = 0;
  57013. for (var index = 0; index < this._particles.length; index++) {
  57014. var particle = this._particles[index];
  57015. this._appendParticleVertices(offset, particle);
  57016. offset += this._useInstancing ? 1 : 4;
  57017. }
  57018. if (this._vertexBuffer) {
  57019. this._vertexBuffer.update(this._vertexData);
  57020. }
  57021. }
  57022. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  57023. this.stop();
  57024. }
  57025. };
  57026. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  57027. this._appendParticleVertex(offset++, particle, 0, 0);
  57028. if (!this._useInstancing) {
  57029. this._appendParticleVertex(offset++, particle, 1, 0);
  57030. this._appendParticleVertex(offset++, particle, 1, 1);
  57031. this._appendParticleVertex(offset++, particle, 0, 1);
  57032. }
  57033. };
  57034. /**
  57035. * Rebuilds the particle system.
  57036. */
  57037. ParticleSystem.prototype.rebuild = function () {
  57038. this._createIndexBuffer();
  57039. if (this._vertexBuffer) {
  57040. this._vertexBuffer._rebuild();
  57041. }
  57042. };
  57043. /**
  57044. * Is this system ready to be used/rendered
  57045. * @return true if the system is ready
  57046. */
  57047. ParticleSystem.prototype.isReady = function () {
  57048. var effect = this._getEffect();
  57049. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57050. return false;
  57051. }
  57052. return true;
  57053. };
  57054. /**
  57055. * Renders the particle system in its current state.
  57056. * @returns the current number of particles
  57057. */
  57058. ParticleSystem.prototype.render = function () {
  57059. var effect = this._getEffect();
  57060. // Check
  57061. if (!this.isReady() || !this._particles.length) {
  57062. return 0;
  57063. }
  57064. var engine = this._scene.getEngine();
  57065. // Render
  57066. engine.enableEffect(effect);
  57067. engine.setState(false);
  57068. var viewMatrix = this._scene.getViewMatrix();
  57069. effect.setTexture("diffuseSampler", this.particleTexture);
  57070. effect.setMatrix("view", viewMatrix);
  57071. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  57072. if (this._isAnimationSheetEnabled && this.particleTexture) {
  57073. var baseSize = this.particleTexture.getBaseSize();
  57074. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  57075. }
  57076. effect.setVector2("translationPivot", this.translationPivot);
  57077. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  57078. if (this._isBillboardBased) {
  57079. var camera = this._scene.activeCamera;
  57080. effect.setVector3("eyePosition", camera.globalPosition);
  57081. }
  57082. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  57083. var invView = viewMatrix.clone();
  57084. invView.invert();
  57085. effect.setMatrix("invView", invView);
  57086. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  57087. }
  57088. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  57089. // image processing
  57090. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  57091. this._imageProcessingConfiguration.bind(effect);
  57092. }
  57093. // Draw order
  57094. switch (this.blendMode) {
  57095. case ParticleSystem.BLENDMODE_ADD:
  57096. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  57097. break;
  57098. case ParticleSystem.BLENDMODE_ONEONE:
  57099. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57100. break;
  57101. case ParticleSystem.BLENDMODE_STANDARD:
  57102. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57103. break;
  57104. }
  57105. if (this.forceDepthWrite) {
  57106. engine.setDepthWrite(true);
  57107. }
  57108. if (this._useInstancing) {
  57109. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  57110. engine.unbindInstanceAttributes();
  57111. }
  57112. else {
  57113. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  57114. }
  57115. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57116. return this._particles.length;
  57117. };
  57118. /**
  57119. * Disposes the particle system and free the associated resources
  57120. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57121. */
  57122. ParticleSystem.prototype.dispose = function (disposeTexture) {
  57123. if (disposeTexture === void 0) { disposeTexture = true; }
  57124. if (this._vertexBuffer) {
  57125. this._vertexBuffer.dispose();
  57126. this._vertexBuffer = null;
  57127. }
  57128. if (this._spriteBuffer) {
  57129. this._spriteBuffer.dispose();
  57130. this._spriteBuffer = null;
  57131. }
  57132. if (this._indexBuffer) {
  57133. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  57134. this._indexBuffer = null;
  57135. }
  57136. if (disposeTexture && this.particleTexture) {
  57137. this.particleTexture.dispose();
  57138. this.particleTexture = null;
  57139. }
  57140. if (disposeTexture && this.noiseTexture) {
  57141. this.noiseTexture.dispose();
  57142. this.noiseTexture = null;
  57143. }
  57144. this._removeFromRoot();
  57145. // Remove from scene
  57146. var index = this._scene.particleSystems.indexOf(this);
  57147. if (index > -1) {
  57148. this._scene.particleSystems.splice(index, 1);
  57149. }
  57150. // Callback
  57151. this.onDisposeObservable.notifyObservers(this);
  57152. this.onDisposeObservable.clear();
  57153. };
  57154. // Clone
  57155. /**
  57156. * Clones the particle system.
  57157. * @param name The name of the cloned object
  57158. * @param newEmitter The new emitter to use
  57159. * @returns the cloned particle system
  57160. */
  57161. ParticleSystem.prototype.clone = function (name, newEmitter) {
  57162. var custom = null;
  57163. var program = null;
  57164. if (this.customShader != null) {
  57165. program = this.customShader;
  57166. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57167. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57168. }
  57169. else if (this._customEffect) {
  57170. custom = this._customEffect;
  57171. }
  57172. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  57173. result.customShader = program;
  57174. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  57175. if (newEmitter === undefined) {
  57176. newEmitter = this.emitter;
  57177. }
  57178. result.emitter = newEmitter;
  57179. if (this.particleTexture) {
  57180. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57181. }
  57182. if (!this.preventAutoStart) {
  57183. result.start();
  57184. }
  57185. return result;
  57186. };
  57187. /**
  57188. * Serializes the particle system to a JSON object.
  57189. * @returns the JSON object
  57190. */
  57191. ParticleSystem.prototype.serialize = function () {
  57192. var serializationObject = {};
  57193. ParticleSystem._Serialize(serializationObject, this);
  57194. serializationObject.textureMask = this.textureMask.asArray();
  57195. serializationObject.customShader = this.customShader;
  57196. serializationObject.preventAutoStart = this.preventAutoStart;
  57197. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  57198. return serializationObject;
  57199. };
  57200. /** @hidden */
  57201. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  57202. serializationObject.name = particleSystem.name;
  57203. serializationObject.id = particleSystem.id;
  57204. serializationObject.capacity = particleSystem.getCapacity();
  57205. // Emitter
  57206. if (particleSystem.emitter.position) {
  57207. var emitterMesh = particleSystem.emitter;
  57208. serializationObject.emitterId = emitterMesh.id;
  57209. }
  57210. else {
  57211. var emitterPosition = particleSystem.emitter;
  57212. serializationObject.emitter = emitterPosition.asArray();
  57213. }
  57214. // Emitter
  57215. if (particleSystem.particleEmitterType) {
  57216. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  57217. }
  57218. if (particleSystem.particleTexture) {
  57219. serializationObject.textureName = particleSystem.particleTexture.name;
  57220. }
  57221. // Animations
  57222. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  57223. // Particle system
  57224. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  57225. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  57226. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  57227. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  57228. serializationObject.minSize = particleSystem.minSize;
  57229. serializationObject.maxSize = particleSystem.maxSize;
  57230. serializationObject.minScaleX = particleSystem.minScaleX;
  57231. serializationObject.maxScaleX = particleSystem.maxScaleX;
  57232. serializationObject.minScaleY = particleSystem.minScaleY;
  57233. serializationObject.maxScaleY = particleSystem.maxScaleY;
  57234. serializationObject.minEmitPower = particleSystem.minEmitPower;
  57235. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  57236. serializationObject.minLifeTime = particleSystem.minLifeTime;
  57237. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  57238. serializationObject.emitRate = particleSystem.emitRate;
  57239. serializationObject.gravity = particleSystem.gravity.asArray();
  57240. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  57241. serializationObject.color1 = particleSystem.color1.asArray();
  57242. serializationObject.color2 = particleSystem.color2.asArray();
  57243. serializationObject.colorDead = particleSystem.colorDead.asArray();
  57244. serializationObject.updateSpeed = particleSystem.updateSpeed;
  57245. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  57246. serializationObject.blendMode = particleSystem.blendMode;
  57247. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  57248. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  57249. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  57250. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  57251. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  57252. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  57253. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  57254. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  57255. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  57256. var colorGradients = particleSystem.getColorGradients();
  57257. if (colorGradients) {
  57258. serializationObject.colorGradients = [];
  57259. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  57260. var colorGradient = colorGradients_1[_i];
  57261. var serializedGradient = {
  57262. gradient: colorGradient.gradient,
  57263. color1: colorGradient.color1.asArray()
  57264. };
  57265. if (colorGradient.color2) {
  57266. serializedGradient.color2 = colorGradient.color2.asArray();
  57267. }
  57268. serializationObject.colorGradients.push(serializedGradient);
  57269. }
  57270. }
  57271. var sizeGradients = particleSystem.getSizeGradients();
  57272. if (sizeGradients) {
  57273. serializationObject.sizeGradients = [];
  57274. for (var _a = 0, sizeGradients_1 = sizeGradients; _a < sizeGradients_1.length; _a++) {
  57275. var sizeGradient = sizeGradients_1[_a];
  57276. var serializedGradient = {
  57277. gradient: sizeGradient.gradient,
  57278. factor1: sizeGradient.factor1
  57279. };
  57280. if (sizeGradient.factor2 !== undefined) {
  57281. serializedGradient.factor2 = sizeGradient.factor2;
  57282. }
  57283. serializationObject.sizeGradients.push(serializedGradient);
  57284. }
  57285. }
  57286. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  57287. if (angularSpeedGradients) {
  57288. serializationObject.angularSpeedGradients = [];
  57289. for (var _b = 0, angularSpeedGradients_1 = angularSpeedGradients; _b < angularSpeedGradients_1.length; _b++) {
  57290. var angularSpeedGradient = angularSpeedGradients_1[_b];
  57291. var serializedGradient = {
  57292. gradient: angularSpeedGradient.gradient,
  57293. factor1: angularSpeedGradient.factor1
  57294. };
  57295. if (angularSpeedGradient.factor2 !== undefined) {
  57296. serializedGradient.factor2 = angularSpeedGradient.factor2;
  57297. }
  57298. serializationObject.angularSpeedGradients.push(serializedGradient);
  57299. }
  57300. }
  57301. var velocityGradients = particleSystem.getVelocityGradients();
  57302. if (velocityGradients) {
  57303. serializationObject.velocityGradients = [];
  57304. for (var _c = 0, velocityGradients_1 = velocityGradients; _c < velocityGradients_1.length; _c++) {
  57305. var velocityGradient = velocityGradients_1[_c];
  57306. var serializedGradient = {
  57307. gradient: velocityGradient.gradient,
  57308. factor1: velocityGradient.factor1
  57309. };
  57310. if (velocityGradient.factor2 !== undefined) {
  57311. serializedGradient.factor2 = velocityGradient.factor2;
  57312. }
  57313. serializationObject.velocityGradients.push(serializedGradient);
  57314. }
  57315. }
  57316. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  57317. if (limitVelocityGradients) {
  57318. serializationObject.limitVelocityGradients = [];
  57319. for (var _d = 0, limitVelocityGradients_1 = limitVelocityGradients; _d < limitVelocityGradients_1.length; _d++) {
  57320. var limitVelocityGradient = limitVelocityGradients_1[_d];
  57321. var serializedGradient = {
  57322. gradient: limitVelocityGradient.gradient,
  57323. factor1: limitVelocityGradient.factor1
  57324. };
  57325. if (limitVelocityGradient.factor2 !== undefined) {
  57326. serializedGradient.factor2 = limitVelocityGradient.factor2;
  57327. }
  57328. serializationObject.limitVelocityGradients.push(serializedGradient);
  57329. }
  57330. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  57331. }
  57332. if (particleSystem.noiseTexture && particleSystem.noiseTexture instanceof BABYLON.ProceduralTexture) {
  57333. var noiseTexture = particleSystem.noiseTexture;
  57334. serializationObject.noiseTexture = noiseTexture.serialize();
  57335. }
  57336. };
  57337. /** @hidden */
  57338. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  57339. // Texture
  57340. if (parsedParticleSystem.textureName) {
  57341. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57342. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57343. }
  57344. // Emitter
  57345. if (parsedParticleSystem.emitterId === undefined) {
  57346. particleSystem.emitter = BABYLON.Vector3.Zero();
  57347. }
  57348. else if (parsedParticleSystem.emitterId) {
  57349. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57350. }
  57351. else {
  57352. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57353. }
  57354. // Misc.
  57355. if (parsedParticleSystem.renderingGroupId !== undefined) {
  57356. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  57357. }
  57358. if (parsedParticleSystem.isBillboardBased !== undefined) {
  57359. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  57360. }
  57361. // Animations
  57362. if (parsedParticleSystem.animations) {
  57363. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57364. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57365. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57366. }
  57367. }
  57368. if (parsedParticleSystem.autoAnimate) {
  57369. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  57370. }
  57371. // Particle system
  57372. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  57373. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  57374. particleSystem.minSize = parsedParticleSystem.minSize;
  57375. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57376. if (parsedParticleSystem.minScaleX) {
  57377. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  57378. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  57379. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  57380. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  57381. }
  57382. if (parsedParticleSystem.preWarmCycles !== undefined) {
  57383. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  57384. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  57385. }
  57386. if (parsedParticleSystem.minInitialRotation !== undefined) {
  57387. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  57388. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  57389. }
  57390. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57391. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57392. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57393. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57394. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57395. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57396. if (parsedParticleSystem.noiseStrength) {
  57397. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  57398. }
  57399. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57400. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57401. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57402. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57403. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57404. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57405. if (parsedParticleSystem.colorGradients) {
  57406. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  57407. var colorGradient = _a[_i];
  57408. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  57409. }
  57410. }
  57411. if (parsedParticleSystem.sizeGradients) {
  57412. for (var _b = 0, _c = parsedParticleSystem.sizeGradients; _b < _c.length; _b++) {
  57413. var sizeGradient = _c[_b];
  57414. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  57415. }
  57416. }
  57417. if (parsedParticleSystem.angularSpeedGradients) {
  57418. for (var _d = 0, _e = parsedParticleSystem.angularSpeedGradients; _d < _e.length; _d++) {
  57419. var angularSpeedGradient = _e[_d];
  57420. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  57421. }
  57422. }
  57423. if (parsedParticleSystem.velocityGradients) {
  57424. for (var _f = 0, _g = parsedParticleSystem.velocityGradients; _f < _g.length; _f++) {
  57425. var velocityGradient = _g[_f];
  57426. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  57427. }
  57428. }
  57429. if (parsedParticleSystem.limitVelocityGradients) {
  57430. for (var _h = 0, _j = parsedParticleSystem.limitVelocityGradients; _h < _j.length; _h++) {
  57431. var limitVelocityGradient = _j[_h];
  57432. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  57433. }
  57434. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  57435. }
  57436. if (parsedParticleSystem.noiseTexture) {
  57437. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  57438. }
  57439. // Emitter
  57440. var emitterType;
  57441. if (parsedParticleSystem.particleEmitterType) {
  57442. switch (parsedParticleSystem.particleEmitterType.type) {
  57443. case "SphereParticleEmitter":
  57444. emitterType = new BABYLON.SphereParticleEmitter();
  57445. break;
  57446. case "SphereDirectedParticleEmitter":
  57447. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  57448. break;
  57449. case "ConeEmitter":
  57450. case "ConeParticleEmitter":
  57451. emitterType = new BABYLON.ConeParticleEmitter();
  57452. break;
  57453. case "BoxEmitter":
  57454. case "BoxParticleEmitter":
  57455. default:
  57456. emitterType = new BABYLON.BoxParticleEmitter();
  57457. break;
  57458. }
  57459. emitterType.parse(parsedParticleSystem.particleEmitterType);
  57460. }
  57461. else {
  57462. emitterType = new BABYLON.BoxParticleEmitter();
  57463. emitterType.parse(parsedParticleSystem);
  57464. }
  57465. particleSystem.particleEmitterType = emitterType;
  57466. // Animation sheet
  57467. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  57468. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  57469. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  57470. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  57471. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  57472. };
  57473. /**
  57474. * Parses a JSON object to create a particle system.
  57475. * @param parsedParticleSystem The JSON object to parse
  57476. * @param scene The scene to create the particle system in
  57477. * @param rootUrl The root url to use to load external dependencies like texture
  57478. * @returns the Parsed particle system
  57479. */
  57480. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57481. var name = parsedParticleSystem.name;
  57482. var custom = null;
  57483. var program = null;
  57484. if (parsedParticleSystem.customShader) {
  57485. program = parsedParticleSystem.customShader;
  57486. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  57487. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  57488. }
  57489. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  57490. particleSystem.customShader = program;
  57491. if (parsedParticleSystem.id) {
  57492. particleSystem.id = parsedParticleSystem.id;
  57493. }
  57494. // Auto start
  57495. if (parsedParticleSystem.preventAutoStart) {
  57496. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  57497. }
  57498. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  57499. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  57500. if (!particleSystem.preventAutoStart) {
  57501. particleSystem.start();
  57502. }
  57503. return particleSystem;
  57504. };
  57505. return ParticleSystem;
  57506. }(BABYLON.BaseParticleSystem));
  57507. BABYLON.ParticleSystem = ParticleSystem;
  57508. })(BABYLON || (BABYLON = {}));
  57509. //# sourceMappingURL=babylon.particleSystem.js.map
  57510. var BABYLON;
  57511. (function (BABYLON) {
  57512. /**
  57513. * Particle emitter emitting particles from the inside of a box.
  57514. * It emits the particles randomly between 2 given directions.
  57515. */
  57516. var BoxParticleEmitter = /** @class */ (function () {
  57517. /**
  57518. * Creates a new instance BoxParticleEmitter
  57519. */
  57520. function BoxParticleEmitter() {
  57521. /**
  57522. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57523. */
  57524. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  57525. /**
  57526. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57527. */
  57528. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  57529. /**
  57530. * 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.
  57531. */
  57532. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  57533. /**
  57534. * 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.
  57535. */
  57536. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  57537. }
  57538. /**
  57539. * Called by the particle System when the direction is computed for the created particle.
  57540. * @param worldMatrix is the world matrix of the particle system
  57541. * @param directionToUpdate is the direction vector to update with the result
  57542. * @param particle is the particle we are computed the direction for
  57543. */
  57544. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57545. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57546. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57547. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57548. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  57549. };
  57550. /**
  57551. * Called by the particle System when the position is computed for the created particle.
  57552. * @param worldMatrix is the world matrix of the particle system
  57553. * @param positionToUpdate is the position vector to update with the result
  57554. * @param particle is the particle we are computed the position for
  57555. */
  57556. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57557. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  57558. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  57559. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  57560. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57561. };
  57562. /**
  57563. * Clones the current emitter and returns a copy of it
  57564. * @returns the new emitter
  57565. */
  57566. BoxParticleEmitter.prototype.clone = function () {
  57567. var newOne = new BoxParticleEmitter();
  57568. BABYLON.Tools.DeepCopy(this, newOne);
  57569. return newOne;
  57570. };
  57571. /**
  57572. * Called by the GPUParticleSystem to setup the update shader
  57573. * @param effect defines the update shader
  57574. */
  57575. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  57576. effect.setVector3("direction1", this.direction1);
  57577. effect.setVector3("direction2", this.direction2);
  57578. effect.setVector3("minEmitBox", this.minEmitBox);
  57579. effect.setVector3("maxEmitBox", this.maxEmitBox);
  57580. };
  57581. /**
  57582. * Returns a string to use to update the GPU particles update shader
  57583. * @returns a string containng the defines string
  57584. */
  57585. BoxParticleEmitter.prototype.getEffectDefines = function () {
  57586. return "#define BOXEMITTER";
  57587. };
  57588. /**
  57589. * Returns the string "BoxParticleEmitter"
  57590. * @returns a string containing the class name
  57591. */
  57592. BoxParticleEmitter.prototype.getClassName = function () {
  57593. return "BoxParticleEmitter";
  57594. };
  57595. /**
  57596. * Serializes the particle system to a JSON object.
  57597. * @returns the JSON object
  57598. */
  57599. BoxParticleEmitter.prototype.serialize = function () {
  57600. var serializationObject = {};
  57601. serializationObject.type = this.getClassName();
  57602. serializationObject.direction1 = this.direction1.asArray();
  57603. serializationObject.direction2 = this.direction2.asArray();
  57604. serializationObject.minEmitBox = this.minEmitBox.asArray();
  57605. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  57606. return serializationObject;
  57607. };
  57608. /**
  57609. * Parse properties from a JSON object
  57610. * @param serializationObject defines the JSON object
  57611. */
  57612. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  57613. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  57614. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  57615. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  57616. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  57617. };
  57618. return BoxParticleEmitter;
  57619. }());
  57620. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  57621. })(BABYLON || (BABYLON = {}));
  57622. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  57623. var BABYLON;
  57624. (function (BABYLON) {
  57625. /**
  57626. * Particle emitter emitting particles from the inside of a cone.
  57627. * It emits the particles alongside the cone volume from the base to the particle.
  57628. * The emission direction might be randomized.
  57629. */
  57630. var ConeParticleEmitter = /** @class */ (function () {
  57631. /**
  57632. * Creates a new instance ConeParticleEmitter
  57633. * @param radius the radius of the emission cone (1 by default)
  57634. * @param angles the cone base angle (PI by default)
  57635. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  57636. */
  57637. function ConeParticleEmitter(radius, angle,
  57638. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  57639. directionRandomizer) {
  57640. if (radius === void 0) { radius = 1; }
  57641. if (angle === void 0) { angle = Math.PI; }
  57642. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57643. this.directionRandomizer = directionRandomizer;
  57644. /**
  57645. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  57646. */
  57647. this.radiusRange = 1;
  57648. /**
  57649. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  57650. */
  57651. this.heightRange = 1;
  57652. /**
  57653. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  57654. */
  57655. this.emitFromSpawnPointOnly = false;
  57656. this.angle = angle;
  57657. this.radius = radius;
  57658. }
  57659. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  57660. /**
  57661. * Gets or sets the radius of the emission cone
  57662. */
  57663. get: function () {
  57664. return this._radius;
  57665. },
  57666. set: function (value) {
  57667. this._radius = value;
  57668. this._buildHeight();
  57669. },
  57670. enumerable: true,
  57671. configurable: true
  57672. });
  57673. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  57674. /**
  57675. * Gets or sets the angle of the emission cone
  57676. */
  57677. get: function () {
  57678. return this._angle;
  57679. },
  57680. set: function (value) {
  57681. this._angle = value;
  57682. this._buildHeight();
  57683. },
  57684. enumerable: true,
  57685. configurable: true
  57686. });
  57687. ConeParticleEmitter.prototype._buildHeight = function () {
  57688. if (this._angle !== 0) {
  57689. this._height = this._radius / Math.tan(this._angle / 2);
  57690. }
  57691. else {
  57692. this._height = 1;
  57693. }
  57694. };
  57695. /**
  57696. * Called by the particle System when the direction is computed for the created particle.
  57697. * @param worldMatrix is the world matrix of the particle system
  57698. * @param directionToUpdate is the direction vector to update with the result
  57699. * @param particle is the particle we are computed the direction for
  57700. */
  57701. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57702. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  57703. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  57704. }
  57705. else {
  57706. // measure the direction Vector from the emitter to the particle.
  57707. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57708. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57709. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57710. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57711. direction.x += randX;
  57712. direction.y += randY;
  57713. direction.z += randZ;
  57714. direction.normalize();
  57715. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  57716. }
  57717. };
  57718. /**
  57719. * Called by the particle System when the position is computed for the created particle.
  57720. * @param worldMatrix is the world matrix of the particle system
  57721. * @param positionToUpdate is the position vector to update with the result
  57722. * @param particle is the particle we are computed the position for
  57723. */
  57724. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57725. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  57726. var h;
  57727. if (!this.emitFromSpawnPointOnly) {
  57728. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  57729. // Better distribution in a cone at normal angles.
  57730. h = 1 - h * h;
  57731. }
  57732. else {
  57733. h = 0.0001;
  57734. }
  57735. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  57736. radius = radius * h;
  57737. var randX = radius * Math.sin(s);
  57738. var randZ = radius * Math.cos(s);
  57739. var randY = h * this._height;
  57740. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57741. };
  57742. /**
  57743. * Clones the current emitter and returns a copy of it
  57744. * @returns the new emitter
  57745. */
  57746. ConeParticleEmitter.prototype.clone = function () {
  57747. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  57748. BABYLON.Tools.DeepCopy(this, newOne);
  57749. return newOne;
  57750. };
  57751. /**
  57752. * Called by the GPUParticleSystem to setup the update shader
  57753. * @param effect defines the update shader
  57754. */
  57755. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  57756. effect.setFloat2("radius", this._radius, this.radiusRange);
  57757. effect.setFloat("coneAngle", this._angle);
  57758. effect.setFloat2("height", this._height, this.heightRange);
  57759. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57760. };
  57761. /**
  57762. * Returns a string to use to update the GPU particles update shader
  57763. * @returns a string containng the defines string
  57764. */
  57765. ConeParticleEmitter.prototype.getEffectDefines = function () {
  57766. var defines = "#define CONEEMITTER";
  57767. if (this.emitFromSpawnPointOnly) {
  57768. defines += "\n#define CONEEMITTERSPAWNPOINT";
  57769. }
  57770. return defines;
  57771. };
  57772. /**
  57773. * Returns the string "ConeParticleEmitter"
  57774. * @returns a string containing the class name
  57775. */
  57776. ConeParticleEmitter.prototype.getClassName = function () {
  57777. return "ConeParticleEmitter";
  57778. };
  57779. /**
  57780. * Serializes the particle system to a JSON object.
  57781. * @returns the JSON object
  57782. */
  57783. ConeParticleEmitter.prototype.serialize = function () {
  57784. var serializationObject = {};
  57785. serializationObject.type = this.getClassName();
  57786. serializationObject.radius = this._radius;
  57787. serializationObject.angle = this._angle;
  57788. serializationObject.directionRandomizer = this.directionRandomizer;
  57789. return serializationObject;
  57790. };
  57791. /**
  57792. * Parse properties from a JSON object
  57793. * @param serializationObject defines the JSON object
  57794. */
  57795. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  57796. this.radius = serializationObject.radius;
  57797. this.angle = serializationObject.angle;
  57798. this.directionRandomizer = serializationObject.directionRandomizer;
  57799. };
  57800. return ConeParticleEmitter;
  57801. }());
  57802. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  57803. })(BABYLON || (BABYLON = {}));
  57804. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  57805. var BABYLON;
  57806. (function (BABYLON) {
  57807. /**
  57808. * Particle emitter emitting particles from the inside of a sphere.
  57809. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  57810. */
  57811. var SphereParticleEmitter = /** @class */ (function () {
  57812. /**
  57813. * Creates a new instance SphereParticleEmitter
  57814. * @param radius the radius of the emission sphere (1 by default)
  57815. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  57816. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57817. */
  57818. function SphereParticleEmitter(
  57819. /**
  57820. * The radius of the emission sphere.
  57821. */
  57822. radius,
  57823. /**
  57824. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  57825. */
  57826. radiusRange,
  57827. /**
  57828. * How much to randomize the particle direction [0-1].
  57829. */
  57830. directionRandomizer) {
  57831. if (radius === void 0) { radius = 1; }
  57832. if (radiusRange === void 0) { radiusRange = 1; }
  57833. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57834. this.radius = radius;
  57835. this.radiusRange = radiusRange;
  57836. this.directionRandomizer = directionRandomizer;
  57837. }
  57838. /**
  57839. * Called by the particle System when the direction is computed for the created particle.
  57840. * @param worldMatrix is the world matrix of the particle system
  57841. * @param directionToUpdate is the direction vector to update with the result
  57842. * @param particle is the particle we are computed the direction for
  57843. */
  57844. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57845. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57846. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57847. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57848. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57849. direction.x += randX;
  57850. direction.y += randY;
  57851. direction.z += randZ;
  57852. direction.normalize();
  57853. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  57854. };
  57855. /**
  57856. * Called by the particle System when the position is computed for the created particle.
  57857. * @param worldMatrix is the world matrix of the particle system
  57858. * @param positionToUpdate is the position vector to update with the result
  57859. * @param particle is the particle we are computed the position for
  57860. */
  57861. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57862. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  57863. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  57864. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  57865. var theta = Math.acos(2 * v - 1);
  57866. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  57867. var randY = randRadius * Math.cos(theta);
  57868. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  57869. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57870. };
  57871. /**
  57872. * Clones the current emitter and returns a copy of it
  57873. * @returns the new emitter
  57874. */
  57875. SphereParticleEmitter.prototype.clone = function () {
  57876. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  57877. BABYLON.Tools.DeepCopy(this, newOne);
  57878. return newOne;
  57879. };
  57880. /**
  57881. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57882. * @param effect defines the update shader
  57883. */
  57884. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  57885. effect.setFloat("radius", this.radius);
  57886. effect.setFloat("radiusRange", this.radiusRange);
  57887. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57888. };
  57889. /**
  57890. * Returns a string to use to update the GPU particles update shader
  57891. * @returns a string containng the defines string
  57892. */
  57893. SphereParticleEmitter.prototype.getEffectDefines = function () {
  57894. return "#define SPHEREEMITTER";
  57895. };
  57896. /**
  57897. * Returns the string "SphereParticleEmitter"
  57898. * @returns a string containing the class name
  57899. */
  57900. SphereParticleEmitter.prototype.getClassName = function () {
  57901. return "SphereParticleEmitter";
  57902. };
  57903. /**
  57904. * Serializes the particle system to a JSON object.
  57905. * @returns the JSON object
  57906. */
  57907. SphereParticleEmitter.prototype.serialize = function () {
  57908. var serializationObject = {};
  57909. serializationObject.type = this.getClassName();
  57910. serializationObject.radius = this.radius;
  57911. serializationObject.radiusRange = this.radiusRange;
  57912. serializationObject.directionRandomizer = this.directionRandomizer;
  57913. return serializationObject;
  57914. };
  57915. /**
  57916. * Parse properties from a JSON object
  57917. * @param serializationObject defines the JSON object
  57918. */
  57919. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  57920. this.radius = serializationObject.radius;
  57921. this.radiusRange = serializationObject.radiusRange;
  57922. this.directionRandomizer = serializationObject.directionRandomizer;
  57923. };
  57924. return SphereParticleEmitter;
  57925. }());
  57926. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  57927. /**
  57928. * Particle emitter emitting particles from the inside of a sphere.
  57929. * It emits the particles randomly between two vectors.
  57930. */
  57931. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  57932. __extends(SphereDirectedParticleEmitter, _super);
  57933. /**
  57934. * Creates a new instance SphereDirectedParticleEmitter
  57935. * @param radius the radius of the emission sphere (1 by default)
  57936. * @param direction1 the min limit of the emission direction (up vector by default)
  57937. * @param direction2 the max limit of the emission direction (up vector by default)
  57938. */
  57939. function SphereDirectedParticleEmitter(radius,
  57940. /**
  57941. * The min limit of the emission direction.
  57942. */
  57943. direction1,
  57944. /**
  57945. * The max limit of the emission direction.
  57946. */
  57947. direction2) {
  57948. if (radius === void 0) { radius = 1; }
  57949. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  57950. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  57951. var _this = _super.call(this, radius) || this;
  57952. _this.direction1 = direction1;
  57953. _this.direction2 = direction2;
  57954. return _this;
  57955. }
  57956. /**
  57957. * Called by the particle System when the direction is computed for the created particle.
  57958. * @param worldMatrix is the world matrix of the particle system
  57959. * @param directionToUpdate is the direction vector to update with the result
  57960. * @param particle is the particle we are computed the direction for
  57961. */
  57962. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57963. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57964. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57965. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57966. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  57967. };
  57968. /**
  57969. * Clones the current emitter and returns a copy of it
  57970. * @returns the new emitter
  57971. */
  57972. SphereDirectedParticleEmitter.prototype.clone = function () {
  57973. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  57974. BABYLON.Tools.DeepCopy(this, newOne);
  57975. return newOne;
  57976. };
  57977. /**
  57978. * Called by the GPUParticleSystem to setup the update shader
  57979. * @param effect defines the update shader
  57980. */
  57981. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  57982. effect.setFloat("radius", this.radius);
  57983. effect.setFloat("radiusRange", this.radiusRange);
  57984. effect.setVector3("direction1", this.direction1);
  57985. effect.setVector3("direction2", this.direction2);
  57986. };
  57987. /**
  57988. * Returns a string to use to update the GPU particles update shader
  57989. * @returns a string containng the defines string
  57990. */
  57991. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  57992. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  57993. };
  57994. /**
  57995. * Returns the string "SphereDirectedParticleEmitter"
  57996. * @returns a string containing the class name
  57997. */
  57998. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57999. return "SphereDirectedParticleEmitter";
  58000. };
  58001. /**
  58002. * Serializes the particle system to a JSON object.
  58003. * @returns the JSON object
  58004. */
  58005. SphereDirectedParticleEmitter.prototype.serialize = function () {
  58006. var serializationObject = _super.prototype.serialize.call(this);
  58007. serializationObject.direction1 = this.direction1.asArray();
  58008. serializationObject.direction2 = this.direction2.asArray();
  58009. return serializationObject;
  58010. };
  58011. /**
  58012. * Parse properties from a JSON object
  58013. * @param serializationObject defines the JSON object
  58014. */
  58015. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  58016. _super.prototype.parse.call(this, serializationObject);
  58017. this.direction1.copyFrom(serializationObject.direction1);
  58018. this.direction2.copyFrom(serializationObject.direction2);
  58019. };
  58020. return SphereDirectedParticleEmitter;
  58021. }(SphereParticleEmitter));
  58022. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  58023. })(BABYLON || (BABYLON = {}));
  58024. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  58025. var BABYLON;
  58026. (function (BABYLON) {
  58027. /**
  58028. * Particle emitter emitting particles from the inside of a hemisphere.
  58029. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  58030. */
  58031. var HemisphericParticleEmitter = /** @class */ (function () {
  58032. /**
  58033. * Creates a new instance HemisphericParticleEmitter
  58034. * @param radius the radius of the emission hemisphere (1 by default)
  58035. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58036. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  58037. */
  58038. function HemisphericParticleEmitter(
  58039. /**
  58040. * The radius of the emission hemisphere.
  58041. */
  58042. radius,
  58043. /**
  58044. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  58045. */
  58046. radiusRange,
  58047. /**
  58048. * How much to randomize the particle direction [0-1].
  58049. */
  58050. directionRandomizer) {
  58051. if (radius === void 0) { radius = 1; }
  58052. if (radiusRange === void 0) { radiusRange = 1; }
  58053. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58054. this.radius = radius;
  58055. this.radiusRange = radiusRange;
  58056. this.directionRandomizer = directionRandomizer;
  58057. }
  58058. /**
  58059. * Called by the particle System when the direction is computed for the created particle.
  58060. * @param worldMatrix is the world matrix of the particle system
  58061. * @param directionToUpdate is the direction vector to update with the result
  58062. * @param particle is the particle we are computed the direction for
  58063. */
  58064. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58065. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  58066. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58067. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58068. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  58069. direction.x += randX;
  58070. direction.y += randY;
  58071. direction.z += randZ;
  58072. direction.normalize();
  58073. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  58074. };
  58075. /**
  58076. * Called by the particle System when the position is computed for the created particle.
  58077. * @param worldMatrix is the world matrix of the particle system
  58078. * @param positionToUpdate is the position vector to update with the result
  58079. * @param particle is the particle we are computed the position for
  58080. */
  58081. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58082. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  58083. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  58084. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  58085. var theta = Math.acos(2 * v - 1);
  58086. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  58087. var randY = randRadius * Math.cos(theta);
  58088. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  58089. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  58090. };
  58091. /**
  58092. * Clones the current emitter and returns a copy of it
  58093. * @returns the new emitter
  58094. */
  58095. HemisphericParticleEmitter.prototype.clone = function () {
  58096. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  58097. BABYLON.Tools.DeepCopy(this, newOne);
  58098. return newOne;
  58099. };
  58100. /**
  58101. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  58102. * @param effect defines the update shader
  58103. */
  58104. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  58105. effect.setFloat("radius", this.radius);
  58106. effect.setFloat("radiusRange", this.radiusRange);
  58107. effect.setFloat("directionRandomizer", this.directionRandomizer);
  58108. };
  58109. /**
  58110. * Returns a string to use to update the GPU particles update shader
  58111. * @returns a string containng the defines string
  58112. */
  58113. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  58114. return "#define HEMISPHERICEMITTER";
  58115. };
  58116. /**
  58117. * Returns the string "HemisphericParticleEmitter"
  58118. * @returns a string containing the class name
  58119. */
  58120. HemisphericParticleEmitter.prototype.getClassName = function () {
  58121. return "HemisphericParticleEmitter";
  58122. };
  58123. /**
  58124. * Serializes the particle system to a JSON object.
  58125. * @returns the JSON object
  58126. */
  58127. HemisphericParticleEmitter.prototype.serialize = function () {
  58128. var serializationObject = {};
  58129. serializationObject.type = this.getClassName();
  58130. serializationObject.radius = this.radius;
  58131. serializationObject.radiusRange = this.radiusRange;
  58132. serializationObject.directionRandomizer = this.directionRandomizer;
  58133. return serializationObject;
  58134. };
  58135. /**
  58136. * Parse properties from a JSON object
  58137. * @param serializationObject defines the JSON object
  58138. */
  58139. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  58140. this.radius = serializationObject.radius;
  58141. this.radiusRange = serializationObject.radiusRange;
  58142. this.directionRandomizer = serializationObject.directionRandomizer;
  58143. };
  58144. return HemisphericParticleEmitter;
  58145. }());
  58146. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  58147. })(BABYLON || (BABYLON = {}));
  58148. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  58149. var BABYLON;
  58150. (function (BABYLON) {
  58151. /**
  58152. * Particle emitter emitting particles from a point.
  58153. * It emits the particles randomly between 2 given directions.
  58154. */
  58155. var PointParticleEmitter = /** @class */ (function () {
  58156. /**
  58157. * Creates a new instance PointParticleEmitter
  58158. */
  58159. function PointParticleEmitter() {
  58160. /**
  58161. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58162. */
  58163. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  58164. /**
  58165. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58166. */
  58167. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  58168. }
  58169. /**
  58170. * Called by the particle System when the direction is computed for the created particle.
  58171. * @param worldMatrix is the world matrix of the particle system
  58172. * @param directionToUpdate is the direction vector to update with the result
  58173. * @param particle is the particle we are computed the direction for
  58174. */
  58175. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  58176. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  58177. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  58178. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  58179. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  58180. };
  58181. /**
  58182. * Called by the particle System when the position is computed for the created particle.
  58183. * @param worldMatrix is the world matrix of the particle system
  58184. * @param positionToUpdate is the position vector to update with the result
  58185. * @param particle is the particle we are computed the position for
  58186. */
  58187. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  58188. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  58189. };
  58190. /**
  58191. * Clones the current emitter and returns a copy of it
  58192. * @returns the new emitter
  58193. */
  58194. PointParticleEmitter.prototype.clone = function () {
  58195. var newOne = new PointParticleEmitter();
  58196. BABYLON.Tools.DeepCopy(this, newOne);
  58197. return newOne;
  58198. };
  58199. /**
  58200. * Called by the GPUParticleSystem to setup the update shader
  58201. * @param effect defines the update shader
  58202. */
  58203. PointParticleEmitter.prototype.applyToShader = function (effect) {
  58204. effect.setVector3("direction1", this.direction1);
  58205. effect.setVector3("direction2", this.direction2);
  58206. };
  58207. /**
  58208. * Returns a string to use to update the GPU particles update shader
  58209. * @returns a string containng the defines string
  58210. */
  58211. PointParticleEmitter.prototype.getEffectDefines = function () {
  58212. return "#define POINTEMITTER";
  58213. };
  58214. /**
  58215. * Returns the string "PointParticleEmitter"
  58216. * @returns a string containing the class name
  58217. */
  58218. PointParticleEmitter.prototype.getClassName = function () {
  58219. return "PointParticleEmitter";
  58220. };
  58221. /**
  58222. * Serializes the particle system to a JSON object.
  58223. * @returns the JSON object
  58224. */
  58225. PointParticleEmitter.prototype.serialize = function () {
  58226. var serializationObject = {};
  58227. serializationObject.type = this.getClassName();
  58228. serializationObject.direction1 = this.direction1.asArray();
  58229. serializationObject.direction2 = this.direction2.asArray();
  58230. return serializationObject;
  58231. };
  58232. /**
  58233. * Parse properties from a JSON object
  58234. * @param serializationObject defines the JSON object
  58235. */
  58236. PointParticleEmitter.prototype.parse = function (serializationObject) {
  58237. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  58238. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  58239. };
  58240. return PointParticleEmitter;
  58241. }());
  58242. BABYLON.PointParticleEmitter = PointParticleEmitter;
  58243. })(BABYLON || (BABYLON = {}));
  58244. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  58245. var BABYLON;
  58246. (function (BABYLON) {
  58247. // Adds the parsers to the scene parsers.
  58248. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  58249. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  58250. if (!individualParser) {
  58251. return;
  58252. }
  58253. // Particles Systems
  58254. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  58255. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  58256. var parsedParticleSystem = parsedData.particleSystems[index];
  58257. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  58258. }
  58259. }
  58260. });
  58261. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  58262. if (parsedParticleSystem.activeParticleCount) {
  58263. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  58264. return ps;
  58265. }
  58266. else {
  58267. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  58268. return ps;
  58269. }
  58270. });
  58271. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  58272. if (uniformsNames === void 0) { uniformsNames = []; }
  58273. if (samplers === void 0) { samplers = []; }
  58274. if (defines === void 0) { defines = ""; }
  58275. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  58276. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  58277. if (defines.indexOf(" BILLBOARD") === -1) {
  58278. defines += "\n#define BILLBOARD\n";
  58279. }
  58280. if (samplers.indexOf("diffuseSampler") === -1) {
  58281. samplers.push("diffuseSampler");
  58282. }
  58283. return this.createEffect({
  58284. vertex: "particles",
  58285. fragmentElement: fragmentName
  58286. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  58287. };
  58288. })(BABYLON || (BABYLON = {}));
  58289. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  58290. var BABYLON;
  58291. (function (BABYLON) {
  58292. var ShaderMaterial = /** @class */ (function (_super) {
  58293. __extends(ShaderMaterial, _super);
  58294. function ShaderMaterial(name, scene, shaderPath, options) {
  58295. var _this = _super.call(this, name, scene) || this;
  58296. _this._textures = {};
  58297. _this._textureArrays = {};
  58298. _this._floats = {};
  58299. _this._ints = {};
  58300. _this._floatsArrays = {};
  58301. _this._colors3 = {};
  58302. _this._colors3Arrays = {};
  58303. _this._colors4 = {};
  58304. _this._vectors2 = {};
  58305. _this._vectors3 = {};
  58306. _this._vectors4 = {};
  58307. _this._matrices = {};
  58308. _this._matrices3x3 = {};
  58309. _this._matrices2x2 = {};
  58310. _this._vectors2Arrays = {};
  58311. _this._vectors3Arrays = {};
  58312. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  58313. _this._shaderPath = shaderPath;
  58314. options.needAlphaBlending = options.needAlphaBlending || false;
  58315. options.needAlphaTesting = options.needAlphaTesting || false;
  58316. options.attributes = options.attributes || ["position", "normal", "uv"];
  58317. options.uniforms = options.uniforms || ["worldViewProjection"];
  58318. options.uniformBuffers = options.uniformBuffers || [];
  58319. options.samplers = options.samplers || [];
  58320. options.defines = options.defines || [];
  58321. _this._options = options;
  58322. return _this;
  58323. }
  58324. ShaderMaterial.prototype.getClassName = function () {
  58325. return "ShaderMaterial";
  58326. };
  58327. ShaderMaterial.prototype.needAlphaBlending = function () {
  58328. return this._options.needAlphaBlending;
  58329. };
  58330. ShaderMaterial.prototype.needAlphaTesting = function () {
  58331. return this._options.needAlphaTesting;
  58332. };
  58333. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  58334. if (this._options.uniforms.indexOf(uniformName) === -1) {
  58335. this._options.uniforms.push(uniformName);
  58336. }
  58337. };
  58338. ShaderMaterial.prototype.setTexture = function (name, texture) {
  58339. if (this._options.samplers.indexOf(name) === -1) {
  58340. this._options.samplers.push(name);
  58341. }
  58342. this._textures[name] = texture;
  58343. return this;
  58344. };
  58345. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  58346. if (this._options.samplers.indexOf(name) === -1) {
  58347. this._options.samplers.push(name);
  58348. }
  58349. this._checkUniform(name);
  58350. this._textureArrays[name] = textures;
  58351. return this;
  58352. };
  58353. ShaderMaterial.prototype.setFloat = function (name, value) {
  58354. this._checkUniform(name);
  58355. this._floats[name] = value;
  58356. return this;
  58357. };
  58358. ShaderMaterial.prototype.setInt = function (name, value) {
  58359. this._checkUniform(name);
  58360. this._ints[name] = value;
  58361. return this;
  58362. };
  58363. ShaderMaterial.prototype.setFloats = function (name, value) {
  58364. this._checkUniform(name);
  58365. this._floatsArrays[name] = value;
  58366. return this;
  58367. };
  58368. ShaderMaterial.prototype.setColor3 = function (name, value) {
  58369. this._checkUniform(name);
  58370. this._colors3[name] = value;
  58371. return this;
  58372. };
  58373. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  58374. this._checkUniform(name);
  58375. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  58376. color.toArray(arr, arr.length);
  58377. return arr;
  58378. }, []);
  58379. return this;
  58380. };
  58381. ShaderMaterial.prototype.setColor4 = function (name, value) {
  58382. this._checkUniform(name);
  58383. this._colors4[name] = value;
  58384. return this;
  58385. };
  58386. ShaderMaterial.prototype.setVector2 = function (name, value) {
  58387. this._checkUniform(name);
  58388. this._vectors2[name] = value;
  58389. return this;
  58390. };
  58391. ShaderMaterial.prototype.setVector3 = function (name, value) {
  58392. this._checkUniform(name);
  58393. this._vectors3[name] = value;
  58394. return this;
  58395. };
  58396. ShaderMaterial.prototype.setVector4 = function (name, value) {
  58397. this._checkUniform(name);
  58398. this._vectors4[name] = value;
  58399. return this;
  58400. };
  58401. ShaderMaterial.prototype.setMatrix = function (name, value) {
  58402. this._checkUniform(name);
  58403. this._matrices[name] = value;
  58404. return this;
  58405. };
  58406. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  58407. this._checkUniform(name);
  58408. this._matrices3x3[name] = value;
  58409. return this;
  58410. };
  58411. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  58412. this._checkUniform(name);
  58413. this._matrices2x2[name] = value;
  58414. return this;
  58415. };
  58416. ShaderMaterial.prototype.setArray2 = function (name, value) {
  58417. this._checkUniform(name);
  58418. this._vectors2Arrays[name] = value;
  58419. return this;
  58420. };
  58421. ShaderMaterial.prototype.setArray3 = function (name, value) {
  58422. this._checkUniform(name);
  58423. this._vectors3Arrays[name] = value;
  58424. return this;
  58425. };
  58426. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  58427. if (!mesh) {
  58428. return true;
  58429. }
  58430. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  58431. return false;
  58432. }
  58433. return false;
  58434. };
  58435. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  58436. var scene = this.getScene();
  58437. var engine = scene.getEngine();
  58438. if (!this.checkReadyOnEveryCall) {
  58439. if (this._renderId === scene.getRenderId()) {
  58440. if (this._checkCache(scene, mesh, useInstances)) {
  58441. return true;
  58442. }
  58443. }
  58444. }
  58445. // Instances
  58446. var defines = [];
  58447. var attribs = [];
  58448. var fallbacks = new BABYLON.EffectFallbacks();
  58449. if (useInstances) {
  58450. defines.push("#define INSTANCES");
  58451. }
  58452. for (var index = 0; index < this._options.defines.length; index++) {
  58453. defines.push(this._options.defines[index]);
  58454. }
  58455. for (var index = 0; index < this._options.attributes.length; index++) {
  58456. attribs.push(this._options.attributes[index]);
  58457. }
  58458. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  58459. attribs.push(BABYLON.VertexBuffer.ColorKind);
  58460. defines.push("#define VERTEXCOLOR");
  58461. }
  58462. // Bones
  58463. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  58464. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58465. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58466. if (mesh.numBoneInfluencers > 4) {
  58467. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58468. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58469. }
  58470. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58471. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  58472. fallbacks.addCPUSkinningFallback(0, mesh);
  58473. if (this._options.uniforms.indexOf("mBones") === -1) {
  58474. this._options.uniforms.push("mBones");
  58475. }
  58476. }
  58477. else {
  58478. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58479. }
  58480. // Textures
  58481. for (var name in this._textures) {
  58482. if (!this._textures[name].isReady()) {
  58483. return false;
  58484. }
  58485. }
  58486. // Alpha test
  58487. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  58488. defines.push("#define ALPHATEST");
  58489. }
  58490. var previousEffect = this._effect;
  58491. var join = defines.join("\n");
  58492. this._effect = engine.createEffect(this._shaderPath, {
  58493. attributes: attribs,
  58494. uniformsNames: this._options.uniforms,
  58495. uniformBuffersNames: this._options.uniformBuffers,
  58496. samplers: this._options.samplers,
  58497. defines: join,
  58498. fallbacks: fallbacks,
  58499. onCompiled: this.onCompiled,
  58500. onError: this.onError
  58501. }, engine);
  58502. if (!this._effect.isReady()) {
  58503. return false;
  58504. }
  58505. if (previousEffect !== this._effect) {
  58506. scene.resetCachedMaterial();
  58507. }
  58508. this._renderId = scene.getRenderId();
  58509. return true;
  58510. };
  58511. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  58512. var scene = this.getScene();
  58513. if (!this._effect) {
  58514. return;
  58515. }
  58516. if (this._options.uniforms.indexOf("world") !== -1) {
  58517. this._effect.setMatrix("world", world);
  58518. }
  58519. if (this._options.uniforms.indexOf("worldView") !== -1) {
  58520. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  58521. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  58522. }
  58523. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  58524. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  58525. }
  58526. };
  58527. ShaderMaterial.prototype.bind = function (world, mesh) {
  58528. // Std values
  58529. this.bindOnlyWorldMatrix(world);
  58530. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  58531. if (this._options.uniforms.indexOf("view") !== -1) {
  58532. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  58533. }
  58534. if (this._options.uniforms.indexOf("projection") !== -1) {
  58535. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  58536. }
  58537. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  58538. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  58539. }
  58540. // Bones
  58541. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  58542. var name;
  58543. // Texture
  58544. for (name in this._textures) {
  58545. this._effect.setTexture(name, this._textures[name]);
  58546. }
  58547. // Texture arrays
  58548. for (name in this._textureArrays) {
  58549. this._effect.setTextureArray(name, this._textureArrays[name]);
  58550. }
  58551. // Int
  58552. for (name in this._ints) {
  58553. this._effect.setInt(name, this._ints[name]);
  58554. }
  58555. // Float
  58556. for (name in this._floats) {
  58557. this._effect.setFloat(name, this._floats[name]);
  58558. }
  58559. // Floats
  58560. for (name in this._floatsArrays) {
  58561. this._effect.setArray(name, this._floatsArrays[name]);
  58562. }
  58563. // Color3
  58564. for (name in this._colors3) {
  58565. this._effect.setColor3(name, this._colors3[name]);
  58566. }
  58567. for (name in this._colors3Arrays) {
  58568. this._effect.setArray3(name, this._colors3Arrays[name]);
  58569. }
  58570. // Color4
  58571. for (name in this._colors4) {
  58572. var color = this._colors4[name];
  58573. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  58574. }
  58575. // Vector2
  58576. for (name in this._vectors2) {
  58577. this._effect.setVector2(name, this._vectors2[name]);
  58578. }
  58579. // Vector3
  58580. for (name in this._vectors3) {
  58581. this._effect.setVector3(name, this._vectors3[name]);
  58582. }
  58583. // Vector4
  58584. for (name in this._vectors4) {
  58585. this._effect.setVector4(name, this._vectors4[name]);
  58586. }
  58587. // Matrix
  58588. for (name in this._matrices) {
  58589. this._effect.setMatrix(name, this._matrices[name]);
  58590. }
  58591. // Matrix 3x3
  58592. for (name in this._matrices3x3) {
  58593. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  58594. }
  58595. // Matrix 2x2
  58596. for (name in this._matrices2x2) {
  58597. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  58598. }
  58599. // Vector2Array
  58600. for (name in this._vectors2Arrays) {
  58601. this._effect.setArray2(name, this._vectors2Arrays[name]);
  58602. }
  58603. // Vector3Array
  58604. for (name in this._vectors3Arrays) {
  58605. this._effect.setArray3(name, this._vectors3Arrays[name]);
  58606. }
  58607. }
  58608. this._afterBind(mesh);
  58609. };
  58610. ShaderMaterial.prototype.getActiveTextures = function () {
  58611. var activeTextures = _super.prototype.getActiveTextures.call(this);
  58612. for (var name in this._textures) {
  58613. activeTextures.push(this._textures[name]);
  58614. }
  58615. for (var name in this._textureArrays) {
  58616. var array = this._textureArrays[name];
  58617. for (var index = 0; index < array.length; index++) {
  58618. activeTextures.push(array[index]);
  58619. }
  58620. }
  58621. return activeTextures;
  58622. };
  58623. ShaderMaterial.prototype.hasTexture = function (texture) {
  58624. if (_super.prototype.hasTexture.call(this, texture)) {
  58625. return true;
  58626. }
  58627. for (var name in this._textures) {
  58628. if (this._textures[name] === texture) {
  58629. return true;
  58630. }
  58631. }
  58632. for (var name in this._textureArrays) {
  58633. var array = this._textureArrays[name];
  58634. for (var index = 0; index < array.length; index++) {
  58635. if (array[index] === texture) {
  58636. return true;
  58637. }
  58638. }
  58639. }
  58640. return false;
  58641. };
  58642. ShaderMaterial.prototype.clone = function (name) {
  58643. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  58644. return newShaderMaterial;
  58645. };
  58646. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  58647. if (forceDisposeTextures) {
  58648. var name;
  58649. for (name in this._textures) {
  58650. this._textures[name].dispose();
  58651. }
  58652. for (name in this._textureArrays) {
  58653. var array = this._textureArrays[name];
  58654. for (var index = 0; index < array.length; index++) {
  58655. array[index].dispose();
  58656. }
  58657. }
  58658. }
  58659. this._textures = {};
  58660. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  58661. };
  58662. ShaderMaterial.prototype.serialize = function () {
  58663. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58664. serializationObject.customType = "BABYLON.ShaderMaterial";
  58665. serializationObject.options = this._options;
  58666. serializationObject.shaderPath = this._shaderPath;
  58667. var name;
  58668. // Texture
  58669. serializationObject.textures = {};
  58670. for (name in this._textures) {
  58671. serializationObject.textures[name] = this._textures[name].serialize();
  58672. }
  58673. // Texture arrays
  58674. serializationObject.textureArrays = {};
  58675. for (name in this._textureArrays) {
  58676. serializationObject.textureArrays[name] = [];
  58677. var array = this._textureArrays[name];
  58678. for (var index = 0; index < array.length; index++) {
  58679. serializationObject.textureArrays[name].push(array[index].serialize());
  58680. }
  58681. }
  58682. // Float
  58683. serializationObject.floats = {};
  58684. for (name in this._floats) {
  58685. serializationObject.floats[name] = this._floats[name];
  58686. }
  58687. // Float s
  58688. serializationObject.FloatArrays = {};
  58689. for (name in this._floatsArrays) {
  58690. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  58691. }
  58692. // Color3
  58693. serializationObject.colors3 = {};
  58694. for (name in this._colors3) {
  58695. serializationObject.colors3[name] = this._colors3[name].asArray();
  58696. }
  58697. // Color3 array
  58698. serializationObject.colors3Arrays = {};
  58699. for (name in this._colors3Arrays) {
  58700. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  58701. }
  58702. // Color4
  58703. serializationObject.colors4 = {};
  58704. for (name in this._colors4) {
  58705. serializationObject.colors4[name] = this._colors4[name].asArray();
  58706. }
  58707. // Vector2
  58708. serializationObject.vectors2 = {};
  58709. for (name in this._vectors2) {
  58710. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  58711. }
  58712. // Vector3
  58713. serializationObject.vectors3 = {};
  58714. for (name in this._vectors3) {
  58715. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  58716. }
  58717. // Vector4
  58718. serializationObject.vectors4 = {};
  58719. for (name in this._vectors4) {
  58720. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  58721. }
  58722. // Matrix
  58723. serializationObject.matrices = {};
  58724. for (name in this._matrices) {
  58725. serializationObject.matrices[name] = this._matrices[name].asArray();
  58726. }
  58727. // Matrix 3x3
  58728. serializationObject.matrices3x3 = {};
  58729. for (name in this._matrices3x3) {
  58730. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  58731. }
  58732. // Matrix 2x2
  58733. serializationObject.matrices2x2 = {};
  58734. for (name in this._matrices2x2) {
  58735. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  58736. }
  58737. // Vector2Array
  58738. serializationObject.vectors2Arrays = {};
  58739. for (name in this._vectors2Arrays) {
  58740. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  58741. }
  58742. // Vector3Array
  58743. serializationObject.vectors3Arrays = {};
  58744. for (name in this._vectors3Arrays) {
  58745. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  58746. }
  58747. return serializationObject;
  58748. };
  58749. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  58750. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  58751. var name;
  58752. // Texture
  58753. for (name in source.textures) {
  58754. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  58755. }
  58756. // Texture arrays
  58757. for (name in source.textureArrays) {
  58758. var array = source.textureArrays[name];
  58759. var textureArray = new Array();
  58760. for (var index = 0; index < array.length; index++) {
  58761. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  58762. }
  58763. material.setTextureArray(name, textureArray);
  58764. }
  58765. // Float
  58766. for (name in source.floats) {
  58767. material.setFloat(name, source.floats[name]);
  58768. }
  58769. // Float s
  58770. for (name in source.floatsArrays) {
  58771. material.setFloats(name, source.floatsArrays[name]);
  58772. }
  58773. // Color3
  58774. for (name in source.colors3) {
  58775. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  58776. }
  58777. // Color3 arrays
  58778. for (name in source.colors3Arrays) {
  58779. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  58780. if (i % 3 === 0) {
  58781. arr.push([num]);
  58782. }
  58783. else {
  58784. arr[arr.length - 1].push(num);
  58785. }
  58786. return arr;
  58787. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  58788. material.setColor3Array(name, colors);
  58789. }
  58790. // Color4
  58791. for (name in source.colors4) {
  58792. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  58793. }
  58794. // Vector2
  58795. for (name in source.vectors2) {
  58796. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  58797. }
  58798. // Vector3
  58799. for (name in source.vectors3) {
  58800. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  58801. }
  58802. // Vector4
  58803. for (name in source.vectors4) {
  58804. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  58805. }
  58806. // Matrix
  58807. for (name in source.matrices) {
  58808. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  58809. }
  58810. // Matrix 3x3
  58811. for (name in source.matrices3x3) {
  58812. material.setMatrix3x3(name, source.matrices3x3[name]);
  58813. }
  58814. // Matrix 2x2
  58815. for (name in source.matrices2x2) {
  58816. material.setMatrix2x2(name, source.matrices2x2[name]);
  58817. }
  58818. // Vector2Array
  58819. for (name in source.vectors2Arrays) {
  58820. material.setArray2(name, source.vectors2Arrays[name]);
  58821. }
  58822. // Vector3Array
  58823. for (name in source.vectors3Arrays) {
  58824. material.setArray3(name, source.vectors3Arrays[name]);
  58825. }
  58826. return material;
  58827. };
  58828. return ShaderMaterial;
  58829. }(BABYLON.Material));
  58830. BABYLON.ShaderMaterial = ShaderMaterial;
  58831. })(BABYLON || (BABYLON = {}));
  58832. //# sourceMappingURL=babylon.shaderMaterial.js.map
  58833. var BABYLON;
  58834. (function (BABYLON) {
  58835. var GroundMesh = /** @class */ (function (_super) {
  58836. __extends(GroundMesh, _super);
  58837. function GroundMesh(name, scene) {
  58838. var _this = _super.call(this, name, scene) || this;
  58839. _this.generateOctree = false;
  58840. return _this;
  58841. }
  58842. GroundMesh.prototype.getClassName = function () {
  58843. return "GroundMesh";
  58844. };
  58845. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  58846. get: function () {
  58847. return Math.min(this._subdivisionsX, this._subdivisionsY);
  58848. },
  58849. enumerable: true,
  58850. configurable: true
  58851. });
  58852. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  58853. get: function () {
  58854. return this._subdivisionsX;
  58855. },
  58856. enumerable: true,
  58857. configurable: true
  58858. });
  58859. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  58860. get: function () {
  58861. return this._subdivisionsY;
  58862. },
  58863. enumerable: true,
  58864. configurable: true
  58865. });
  58866. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  58867. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  58868. this._subdivisionsX = chunksCount;
  58869. this._subdivisionsY = chunksCount;
  58870. this.subdivide(chunksCount);
  58871. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  58872. };
  58873. /**
  58874. * Returns a height (y) value in the Worl system :
  58875. * the ground altitude at the coordinates (x, z) expressed in the World system.
  58876. * Returns the ground y position if (x, z) are outside the ground surface.
  58877. */
  58878. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  58879. var world = this.getWorldMatrix();
  58880. var invMat = BABYLON.Tmp.Matrix[5];
  58881. world.invertToRef(invMat);
  58882. var tmpVect = BABYLON.Tmp.Vector3[8];
  58883. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  58884. x = tmpVect.x;
  58885. z = tmpVect.z;
  58886. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  58887. return this.position.y;
  58888. }
  58889. if (!this._heightQuads || this._heightQuads.length == 0) {
  58890. this._initHeightQuads();
  58891. this._computeHeightQuads();
  58892. }
  58893. var facet = this._getFacetAt(x, z);
  58894. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  58895. // return y in the World system
  58896. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  58897. return tmpVect.y;
  58898. };
  58899. /**
  58900. * Returns a normalized vector (Vector3) orthogonal to the ground
  58901. * at the ground coordinates (x, z) expressed in the World system.
  58902. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  58903. */
  58904. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  58905. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  58906. this.getNormalAtCoordinatesToRef(x, z, normal);
  58907. return normal;
  58908. };
  58909. /**
  58910. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  58911. * at the ground coordinates (x, z) expressed in the World system.
  58912. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  58913. * Returns the GroundMesh.
  58914. */
  58915. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  58916. var world = this.getWorldMatrix();
  58917. var tmpMat = BABYLON.Tmp.Matrix[5];
  58918. world.invertToRef(tmpMat);
  58919. var tmpVect = BABYLON.Tmp.Vector3[8];
  58920. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  58921. x = tmpVect.x;
  58922. z = tmpVect.z;
  58923. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  58924. return this;
  58925. }
  58926. if (!this._heightQuads || this._heightQuads.length == 0) {
  58927. this._initHeightQuads();
  58928. this._computeHeightQuads();
  58929. }
  58930. var facet = this._getFacetAt(x, z);
  58931. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  58932. return this;
  58933. };
  58934. /**
  58935. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  58936. * if the ground has been updated.
  58937. * This can be used in the render loop.
  58938. * Returns the GroundMesh.
  58939. */
  58940. GroundMesh.prototype.updateCoordinateHeights = function () {
  58941. if (!this._heightQuads || this._heightQuads.length == 0) {
  58942. this._initHeightQuads();
  58943. }
  58944. this._computeHeightQuads();
  58945. return this;
  58946. };
  58947. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  58948. GroundMesh.prototype._getFacetAt = function (x, z) {
  58949. // retrieve col and row from x, z coordinates in the ground local system
  58950. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  58951. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  58952. var quad = this._heightQuads[row * this._subdivisionsX + col];
  58953. var facet;
  58954. if (z < quad.slope.x * x + quad.slope.y) {
  58955. facet = quad.facet1;
  58956. }
  58957. else {
  58958. facet = quad.facet2;
  58959. }
  58960. return facet;
  58961. };
  58962. // Creates and populates the heightMap array with "facet" elements :
  58963. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  58964. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  58965. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  58966. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  58967. // Returns the GroundMesh.
  58968. GroundMesh.prototype._initHeightQuads = function () {
  58969. var subdivisionsX = this._subdivisionsX;
  58970. var subdivisionsY = this._subdivisionsY;
  58971. this._heightQuads = new Array();
  58972. for (var row = 0; row < subdivisionsY; row++) {
  58973. for (var col = 0; col < subdivisionsX; col++) {
  58974. 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) };
  58975. this._heightQuads[row * subdivisionsX + col] = quad;
  58976. }
  58977. }
  58978. return this;
  58979. };
  58980. // Compute each quad element values and update the the heightMap array :
  58981. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  58982. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  58983. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  58984. // Returns the GroundMesh.
  58985. GroundMesh.prototype._computeHeightQuads = function () {
  58986. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58987. if (!positions) {
  58988. return this;
  58989. }
  58990. var v1 = BABYLON.Tmp.Vector3[3];
  58991. var v2 = BABYLON.Tmp.Vector3[2];
  58992. var v3 = BABYLON.Tmp.Vector3[1];
  58993. var v4 = BABYLON.Tmp.Vector3[0];
  58994. var v1v2 = BABYLON.Tmp.Vector3[4];
  58995. var v1v3 = BABYLON.Tmp.Vector3[5];
  58996. var v1v4 = BABYLON.Tmp.Vector3[6];
  58997. var norm1 = BABYLON.Tmp.Vector3[7];
  58998. var norm2 = BABYLON.Tmp.Vector3[8];
  58999. var i = 0;
  59000. var j = 0;
  59001. var k = 0;
  59002. var cd = 0; // 2D slope coefficient : z = cd * x + h
  59003. var h = 0;
  59004. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  59005. var d2 = 0;
  59006. var subdivisionsX = this._subdivisionsX;
  59007. var subdivisionsY = this._subdivisionsY;
  59008. for (var row = 0; row < subdivisionsY; row++) {
  59009. for (var col = 0; col < subdivisionsX; col++) {
  59010. i = col * 3;
  59011. j = row * (subdivisionsX + 1) * 3;
  59012. k = (row + 1) * (subdivisionsX + 1) * 3;
  59013. v1.x = positions[j + i];
  59014. v1.y = positions[j + i + 1];
  59015. v1.z = positions[j + i + 2];
  59016. v2.x = positions[j + i + 3];
  59017. v2.y = positions[j + i + 4];
  59018. v2.z = positions[j + i + 5];
  59019. v3.x = positions[k + i];
  59020. v3.y = positions[k + i + 1];
  59021. v3.z = positions[k + i + 2];
  59022. v4.x = positions[k + i + 3];
  59023. v4.y = positions[k + i + 4];
  59024. v4.z = positions[k + i + 5];
  59025. // 2D slope V1V4
  59026. cd = (v4.z - v1.z) / (v4.x - v1.x);
  59027. h = v1.z - cd * v1.x; // v1 belongs to the slope
  59028. // facet equations :
  59029. // we compute each facet normal vector
  59030. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  59031. // we compute the value d by applying the equation to v1 which belongs to the plane
  59032. // then we store the facet equation in a Vector4
  59033. v2.subtractToRef(v1, v1v2);
  59034. v3.subtractToRef(v1, v1v3);
  59035. v4.subtractToRef(v1, v1v4);
  59036. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  59037. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  59038. norm1.normalize();
  59039. norm2.normalize();
  59040. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  59041. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  59042. var quad = this._heightQuads[row * subdivisionsX + col];
  59043. quad.slope.copyFromFloats(cd, h);
  59044. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  59045. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  59046. }
  59047. }
  59048. return this;
  59049. };
  59050. GroundMesh.prototype.serialize = function (serializationObject) {
  59051. _super.prototype.serialize.call(this, serializationObject);
  59052. serializationObject.subdivisionsX = this._subdivisionsX;
  59053. serializationObject.subdivisionsY = this._subdivisionsY;
  59054. serializationObject.minX = this._minX;
  59055. serializationObject.maxX = this._maxX;
  59056. serializationObject.minZ = this._minZ;
  59057. serializationObject.maxZ = this._maxZ;
  59058. serializationObject.width = this._width;
  59059. serializationObject.height = this._height;
  59060. };
  59061. GroundMesh.Parse = function (parsedMesh, scene) {
  59062. var result = new GroundMesh(parsedMesh.name, scene);
  59063. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  59064. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  59065. result._minX = parsedMesh.minX;
  59066. result._maxX = parsedMesh.maxX;
  59067. result._minZ = parsedMesh.minZ;
  59068. result._maxZ = parsedMesh.maxZ;
  59069. result._width = parsedMesh.width;
  59070. result._height = parsedMesh.height;
  59071. return result;
  59072. };
  59073. return GroundMesh;
  59074. }(BABYLON.Mesh));
  59075. BABYLON.GroundMesh = GroundMesh;
  59076. })(BABYLON || (BABYLON = {}));
  59077. //# sourceMappingURL=babylon.groundMesh.js.map
  59078. var BABYLON;
  59079. (function (BABYLON) {
  59080. /**
  59081. * Creates an instance based on a source mesh.
  59082. */
  59083. var InstancedMesh = /** @class */ (function (_super) {
  59084. __extends(InstancedMesh, _super);
  59085. function InstancedMesh(name, source) {
  59086. var _this = _super.call(this, name, source.getScene()) || this;
  59087. source.instances.push(_this);
  59088. _this._sourceMesh = source;
  59089. _this.position.copyFrom(source.position);
  59090. _this.rotation.copyFrom(source.rotation);
  59091. _this.scaling.copyFrom(source.scaling);
  59092. if (source.rotationQuaternion) {
  59093. _this.rotationQuaternion = source.rotationQuaternion.clone();
  59094. }
  59095. _this.infiniteDistance = source.infiniteDistance;
  59096. _this.setPivotMatrix(source.getPivotMatrix());
  59097. _this.refreshBoundingInfo();
  59098. _this._syncSubMeshes();
  59099. return _this;
  59100. }
  59101. /**
  59102. * Returns the string "InstancedMesh".
  59103. */
  59104. InstancedMesh.prototype.getClassName = function () {
  59105. return "InstancedMesh";
  59106. };
  59107. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  59108. // Methods
  59109. get: function () {
  59110. return this._sourceMesh.receiveShadows;
  59111. },
  59112. enumerable: true,
  59113. configurable: true
  59114. });
  59115. Object.defineProperty(InstancedMesh.prototype, "material", {
  59116. get: function () {
  59117. return this._sourceMesh.material;
  59118. },
  59119. enumerable: true,
  59120. configurable: true
  59121. });
  59122. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  59123. get: function () {
  59124. return this._sourceMesh.visibility;
  59125. },
  59126. enumerable: true,
  59127. configurable: true
  59128. });
  59129. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  59130. get: function () {
  59131. return this._sourceMesh.skeleton;
  59132. },
  59133. enumerable: true,
  59134. configurable: true
  59135. });
  59136. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  59137. get: function () {
  59138. return this._sourceMesh.renderingGroupId;
  59139. },
  59140. set: function (value) {
  59141. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  59142. return;
  59143. }
  59144. //no-op with warning
  59145. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  59146. },
  59147. enumerable: true,
  59148. configurable: true
  59149. });
  59150. /**
  59151. * Returns the total number of vertices (integer).
  59152. */
  59153. InstancedMesh.prototype.getTotalVertices = function () {
  59154. return this._sourceMesh.getTotalVertices();
  59155. };
  59156. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  59157. get: function () {
  59158. return this._sourceMesh;
  59159. },
  59160. enumerable: true,
  59161. configurable: true
  59162. });
  59163. /**
  59164. * Is this node ready to be used/rendered
  59165. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  59166. * @return {boolean} is it ready
  59167. */
  59168. InstancedMesh.prototype.isReady = function (completeCheck) {
  59169. if (completeCheck === void 0) { completeCheck = false; }
  59170. return this._sourceMesh.isReady(completeCheck, true);
  59171. };
  59172. /**
  59173. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  59174. */
  59175. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  59176. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  59177. };
  59178. /**
  59179. * Sets the vertex data of the mesh geometry for the requested `kind`.
  59180. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  59181. * The `data` are either a numeric array either a Float32Array.
  59182. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  59183. * 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).
  59184. * Note that a new underlying VertexBuffer object is created each call.
  59185. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  59186. *
  59187. * Possible `kind` values :
  59188. * - BABYLON.VertexBuffer.PositionKind
  59189. * - BABYLON.VertexBuffer.UVKind
  59190. * - BABYLON.VertexBuffer.UV2Kind
  59191. * - BABYLON.VertexBuffer.UV3Kind
  59192. * - BABYLON.VertexBuffer.UV4Kind
  59193. * - BABYLON.VertexBuffer.UV5Kind
  59194. * - BABYLON.VertexBuffer.UV6Kind
  59195. * - BABYLON.VertexBuffer.ColorKind
  59196. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59197. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59198. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59199. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59200. *
  59201. * Returns the Mesh.
  59202. */
  59203. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  59204. if (this.sourceMesh) {
  59205. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  59206. }
  59207. return this.sourceMesh;
  59208. };
  59209. /**
  59210. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  59211. * If the mesh has no geometry, it is simply returned as it is.
  59212. * The `data` are either a numeric array either a Float32Array.
  59213. * No new underlying VertexBuffer object is created.
  59214. * 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.
  59215. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  59216. *
  59217. * Possible `kind` values :
  59218. * - BABYLON.VertexBuffer.PositionKind
  59219. * - BABYLON.VertexBuffer.UVKind
  59220. * - BABYLON.VertexBuffer.UV2Kind
  59221. * - BABYLON.VertexBuffer.UV3Kind
  59222. * - BABYLON.VertexBuffer.UV4Kind
  59223. * - BABYLON.VertexBuffer.UV5Kind
  59224. * - BABYLON.VertexBuffer.UV6Kind
  59225. * - BABYLON.VertexBuffer.ColorKind
  59226. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59227. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59228. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59229. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59230. *
  59231. * Returns the Mesh.
  59232. */
  59233. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  59234. if (this.sourceMesh) {
  59235. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  59236. }
  59237. return this.sourceMesh;
  59238. };
  59239. /**
  59240. * Sets the mesh indices.
  59241. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  59242. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  59243. * This method creates a new index buffer each call.
  59244. * Returns the Mesh.
  59245. */
  59246. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  59247. if (totalVertices === void 0) { totalVertices = null; }
  59248. if (this.sourceMesh) {
  59249. this.sourceMesh.setIndices(indices, totalVertices);
  59250. }
  59251. return this.sourceMesh;
  59252. };
  59253. /**
  59254. * Boolean : True if the mesh owns the requested kind of data.
  59255. */
  59256. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  59257. return this._sourceMesh.isVerticesDataPresent(kind);
  59258. };
  59259. /**
  59260. * Returns an array of indices (IndicesArray).
  59261. */
  59262. InstancedMesh.prototype.getIndices = function () {
  59263. return this._sourceMesh.getIndices();
  59264. };
  59265. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  59266. get: function () {
  59267. return this._sourceMesh._positions;
  59268. },
  59269. enumerable: true,
  59270. configurable: true
  59271. });
  59272. /**
  59273. * Sets a new updated BoundingInfo to the mesh.
  59274. * Returns the mesh.
  59275. */
  59276. InstancedMesh.prototype.refreshBoundingInfo = function () {
  59277. var meshBB = this._sourceMesh.getBoundingInfo();
  59278. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  59279. this._updateBoundingInfo();
  59280. return this;
  59281. };
  59282. /** @hidden */
  59283. InstancedMesh.prototype._preActivate = function () {
  59284. if (this._currentLOD) {
  59285. this._currentLOD._preActivate();
  59286. }
  59287. return this;
  59288. };
  59289. /** @hidden */
  59290. InstancedMesh.prototype._activate = function (renderId) {
  59291. if (this._currentLOD) {
  59292. this._currentLOD._registerInstanceForRenderId(this, renderId);
  59293. }
  59294. return this;
  59295. };
  59296. /**
  59297. * Returns the current associated LOD AbstractMesh.
  59298. */
  59299. InstancedMesh.prototype.getLOD = function (camera) {
  59300. if (!camera) {
  59301. return this;
  59302. }
  59303. var boundingInfo = this.getBoundingInfo();
  59304. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  59305. if (this._currentLOD === this.sourceMesh) {
  59306. return this;
  59307. }
  59308. return this._currentLOD;
  59309. };
  59310. /** @hidden */
  59311. InstancedMesh.prototype._syncSubMeshes = function () {
  59312. this.releaseSubMeshes();
  59313. if (this._sourceMesh.subMeshes) {
  59314. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  59315. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  59316. }
  59317. }
  59318. return this;
  59319. };
  59320. /** @hidden */
  59321. InstancedMesh.prototype._generatePointsArray = function () {
  59322. return this._sourceMesh._generatePointsArray();
  59323. };
  59324. /**
  59325. * Creates a new InstancedMesh from the current mesh.
  59326. * - name (string) : the cloned mesh name
  59327. * - newParent (optional Node) : the optional Node to parent the clone to.
  59328. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  59329. *
  59330. * Returns the clone.
  59331. */
  59332. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59333. var result = this._sourceMesh.createInstance(name);
  59334. // Deep copy
  59335. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  59336. // Bounding info
  59337. this.refreshBoundingInfo();
  59338. // Parent
  59339. if (newParent) {
  59340. result.parent = newParent;
  59341. }
  59342. if (!doNotCloneChildren) {
  59343. // Children
  59344. for (var index = 0; index < this.getScene().meshes.length; index++) {
  59345. var mesh = this.getScene().meshes[index];
  59346. if (mesh.parent === this) {
  59347. mesh.clone(mesh.name, result);
  59348. }
  59349. }
  59350. }
  59351. result.computeWorldMatrix(true);
  59352. return result;
  59353. };
  59354. /**
  59355. * Disposes the InstancedMesh.
  59356. * Returns nothing.
  59357. */
  59358. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  59359. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  59360. // Remove from mesh
  59361. var index = this._sourceMesh.instances.indexOf(this);
  59362. this._sourceMesh.instances.splice(index, 1);
  59363. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  59364. };
  59365. return InstancedMesh;
  59366. }(BABYLON.AbstractMesh));
  59367. BABYLON.InstancedMesh = InstancedMesh;
  59368. })(BABYLON || (BABYLON = {}));
  59369. //# sourceMappingURL=babylon.instancedMesh.js.map
  59370. var BABYLON;
  59371. (function (BABYLON) {
  59372. var LinesMesh = /** @class */ (function (_super) {
  59373. __extends(LinesMesh, _super);
  59374. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  59375. if (scene === void 0) { scene = null; }
  59376. if (parent === void 0) { parent = null; }
  59377. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  59378. _this.useVertexColor = useVertexColor;
  59379. _this.useVertexAlpha = useVertexAlpha;
  59380. _this.color = new BABYLON.Color3(1, 1, 1);
  59381. _this.alpha = 1;
  59382. if (source) {
  59383. _this.color = source.color.clone();
  59384. _this.alpha = source.alpha;
  59385. _this.useVertexColor = source.useVertexColor;
  59386. _this.useVertexAlpha = source.useVertexAlpha;
  59387. }
  59388. _this._intersectionThreshold = 0.1;
  59389. var defines = [];
  59390. var options = {
  59391. attributes: [BABYLON.VertexBuffer.PositionKind],
  59392. uniforms: ["world", "viewProjection"],
  59393. needAlphaBlending: true,
  59394. defines: defines
  59395. };
  59396. if (useVertexAlpha === false) {
  59397. options.needAlphaBlending = false;
  59398. }
  59399. if (!useVertexColor) {
  59400. options.uniforms.push("color");
  59401. }
  59402. else {
  59403. options.defines.push("#define VERTEXCOLOR");
  59404. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  59405. }
  59406. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  59407. return _this;
  59408. }
  59409. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  59410. /**
  59411. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59412. * This margin is expressed in world space coordinates, so its value may vary.
  59413. * Default value is 0.1
  59414. * @returns the intersection Threshold value.
  59415. */
  59416. get: function () {
  59417. return this._intersectionThreshold;
  59418. },
  59419. /**
  59420. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59421. * This margin is expressed in world space coordinates, so its value may vary.
  59422. * @param value the new threshold to apply
  59423. */
  59424. set: function (value) {
  59425. if (this._intersectionThreshold === value) {
  59426. return;
  59427. }
  59428. this._intersectionThreshold = value;
  59429. if (this.geometry) {
  59430. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  59431. }
  59432. },
  59433. enumerable: true,
  59434. configurable: true
  59435. });
  59436. /**
  59437. * Returns the string "LineMesh"
  59438. */
  59439. LinesMesh.prototype.getClassName = function () {
  59440. return "LinesMesh";
  59441. };
  59442. Object.defineProperty(LinesMesh.prototype, "material", {
  59443. /**
  59444. * @hidden
  59445. */
  59446. get: function () {
  59447. return this._colorShader;
  59448. },
  59449. /**
  59450. * @hidden
  59451. */
  59452. set: function (value) {
  59453. // Do nothing
  59454. },
  59455. enumerable: true,
  59456. configurable: true
  59457. });
  59458. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  59459. /**
  59460. * @hidden
  59461. */
  59462. get: function () {
  59463. return false;
  59464. },
  59465. enumerable: true,
  59466. configurable: true
  59467. });
  59468. LinesMesh.prototype.createInstance = function (name) {
  59469. throw new Error("LinesMeshes do not support createInstance.");
  59470. };
  59471. /** @hidden */
  59472. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  59473. if (!this._geometry) {
  59474. return this;
  59475. }
  59476. // VBOs
  59477. this._geometry._bind(this._colorShader.getEffect());
  59478. // Color
  59479. if (!this.useVertexColor) {
  59480. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  59481. }
  59482. return this;
  59483. };
  59484. /** @hidden */
  59485. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  59486. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  59487. return this;
  59488. }
  59489. var engine = this.getScene().getEngine();
  59490. // Draw order
  59491. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  59492. return this;
  59493. };
  59494. LinesMesh.prototype.dispose = function (doNotRecurse) {
  59495. this._colorShader.dispose();
  59496. _super.prototype.dispose.call(this, doNotRecurse);
  59497. };
  59498. /**
  59499. * Returns a new LineMesh object cloned from the current one.
  59500. */
  59501. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59502. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  59503. };
  59504. return LinesMesh;
  59505. }(BABYLON.Mesh));
  59506. BABYLON.LinesMesh = LinesMesh;
  59507. })(BABYLON || (BABYLON = {}));
  59508. //# sourceMappingURL=babylon.linesMesh.js.map
  59509. var BABYLON;
  59510. (function (BABYLON) {
  59511. /**
  59512. * This class implement a typical dictionary using a string as key and the generic type T as value.
  59513. * The underlying implementation relies on an associative array to ensure the best performances.
  59514. * The value can be anything including 'null' but except 'undefined'
  59515. */
  59516. var StringDictionary = /** @class */ (function () {
  59517. function StringDictionary() {
  59518. this._count = 0;
  59519. this._data = {};
  59520. }
  59521. /**
  59522. * This will clear this dictionary and copy the content from the 'source' one.
  59523. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  59524. * @param source the dictionary to take the content from and copy to this dictionary
  59525. */
  59526. StringDictionary.prototype.copyFrom = function (source) {
  59527. var _this = this;
  59528. this.clear();
  59529. source.forEach(function (t, v) { return _this.add(t, v); });
  59530. };
  59531. /**
  59532. * Get a value based from its key
  59533. * @param key the given key to get the matching value from
  59534. * @return the value if found, otherwise undefined is returned
  59535. */
  59536. StringDictionary.prototype.get = function (key) {
  59537. var val = this._data[key];
  59538. if (val !== undefined) {
  59539. return val;
  59540. }
  59541. return undefined;
  59542. };
  59543. /**
  59544. * Get a value from its key or add it if it doesn't exist.
  59545. * This method will ensure you that a given key/data will be present in the dictionary.
  59546. * @param key the given key to get the matching value from
  59547. * @param factory the factory that will create the value if the key is not present in the dictionary.
  59548. * The factory will only be invoked if there's no data for the given key.
  59549. * @return the value corresponding to the key.
  59550. */
  59551. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  59552. var val = this.get(key);
  59553. if (val !== undefined) {
  59554. return val;
  59555. }
  59556. val = factory(key);
  59557. if (val) {
  59558. this.add(key, val);
  59559. }
  59560. return val;
  59561. };
  59562. /**
  59563. * Get a value from its key if present in the dictionary otherwise add it
  59564. * @param key the key to get the value from
  59565. * @param val if there's no such key/value pair in the dictionary add it with this value
  59566. * @return the value corresponding to the key
  59567. */
  59568. StringDictionary.prototype.getOrAdd = function (key, val) {
  59569. var curVal = this.get(key);
  59570. if (curVal !== undefined) {
  59571. return curVal;
  59572. }
  59573. this.add(key, val);
  59574. return val;
  59575. };
  59576. /**
  59577. * Check if there's a given key in the dictionary
  59578. * @param key the key to check for
  59579. * @return true if the key is present, false otherwise
  59580. */
  59581. StringDictionary.prototype.contains = function (key) {
  59582. return this._data[key] !== undefined;
  59583. };
  59584. /**
  59585. * Add a new key and its corresponding value
  59586. * @param key the key to add
  59587. * @param value the value corresponding to the key
  59588. * @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
  59589. */
  59590. StringDictionary.prototype.add = function (key, value) {
  59591. if (this._data[key] !== undefined) {
  59592. return false;
  59593. }
  59594. this._data[key] = value;
  59595. ++this._count;
  59596. return true;
  59597. };
  59598. StringDictionary.prototype.set = function (key, value) {
  59599. if (this._data[key] === undefined) {
  59600. return false;
  59601. }
  59602. this._data[key] = value;
  59603. return true;
  59604. };
  59605. /**
  59606. * Get the element of the given key and remove it from the dictionary
  59607. * @param key
  59608. */
  59609. StringDictionary.prototype.getAndRemove = function (key) {
  59610. var val = this.get(key);
  59611. if (val !== undefined) {
  59612. delete this._data[key];
  59613. --this._count;
  59614. return val;
  59615. }
  59616. return null;
  59617. };
  59618. /**
  59619. * Remove a key/value from the dictionary.
  59620. * @param key the key to remove
  59621. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  59622. */
  59623. StringDictionary.prototype.remove = function (key) {
  59624. if (this.contains(key)) {
  59625. delete this._data[key];
  59626. --this._count;
  59627. return true;
  59628. }
  59629. return false;
  59630. };
  59631. /**
  59632. * Clear the whole content of the dictionary
  59633. */
  59634. StringDictionary.prototype.clear = function () {
  59635. this._data = {};
  59636. this._count = 0;
  59637. };
  59638. Object.defineProperty(StringDictionary.prototype, "count", {
  59639. get: function () {
  59640. return this._count;
  59641. },
  59642. enumerable: true,
  59643. configurable: true
  59644. });
  59645. /**
  59646. * Execute a callback on each key/val of the dictionary.
  59647. * Note that you can remove any element in this dictionary in the callback implementation
  59648. * @param callback the callback to execute on a given key/value pair
  59649. */
  59650. StringDictionary.prototype.forEach = function (callback) {
  59651. for (var cur in this._data) {
  59652. var val = this._data[cur];
  59653. callback(cur, val);
  59654. }
  59655. };
  59656. /**
  59657. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  59658. * If the callback returns null or undefined the method will iterate to the next key/value pair
  59659. * Note that you can remove any element in this dictionary in the callback implementation
  59660. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  59661. */
  59662. StringDictionary.prototype.first = function (callback) {
  59663. for (var cur in this._data) {
  59664. var val = this._data[cur];
  59665. var res = callback(cur, val);
  59666. if (res) {
  59667. return res;
  59668. }
  59669. }
  59670. return null;
  59671. };
  59672. return StringDictionary;
  59673. }());
  59674. BABYLON.StringDictionary = StringDictionary;
  59675. })(BABYLON || (BABYLON = {}));
  59676. //# sourceMappingURL=babylon.stringDictionary.js.map
  59677. var BABYLON;
  59678. (function (BABYLON) {
  59679. var Debug;
  59680. (function (Debug) {
  59681. /**
  59682. * Class used to render a debug view of a given skeleton
  59683. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  59684. */
  59685. var SkeletonViewer = /** @class */ (function () {
  59686. /**
  59687. * Creates a new SkeletonViewer
  59688. * @param skeleton defines the skeleton to render
  59689. * @param mesh defines the mesh attached to the skeleton
  59690. * @param scene defines the hosting scene
  59691. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  59692. * @param renderingGroupId defines the rendering group id to use with the viewer
  59693. */
  59694. function SkeletonViewer(
  59695. /** defines the skeleton to render */
  59696. skeleton,
  59697. /** defines the mesh attached to the skeleton */
  59698. mesh, scene,
  59699. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  59700. autoUpdateBonesMatrices,
  59701. /** defines the rendering group id to use with the viewer */
  59702. renderingGroupId) {
  59703. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  59704. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  59705. this.skeleton = skeleton;
  59706. this.mesh = mesh;
  59707. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  59708. this.renderingGroupId = renderingGroupId;
  59709. /** Gets or sets the color used to render the skeleton */
  59710. this.color = BABYLON.Color3.White();
  59711. this._debugLines = new Array();
  59712. this._isEnabled = false;
  59713. this._scene = scene;
  59714. this.update();
  59715. this._renderFunction = this.update.bind(this);
  59716. }
  59717. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  59718. get: function () {
  59719. return this._isEnabled;
  59720. },
  59721. /** Gets or sets a boolean indicating if the viewer is enabled */
  59722. set: function (value) {
  59723. if (this._isEnabled === value) {
  59724. return;
  59725. }
  59726. this._isEnabled = value;
  59727. if (value) {
  59728. this._scene.registerBeforeRender(this._renderFunction);
  59729. }
  59730. else {
  59731. this._scene.unregisterBeforeRender(this._renderFunction);
  59732. }
  59733. },
  59734. enumerable: true,
  59735. configurable: true
  59736. });
  59737. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  59738. if (x === void 0) { x = 0; }
  59739. if (y === void 0) { y = 0; }
  59740. if (z === void 0) { z = 0; }
  59741. var tmat = BABYLON.Tmp.Matrix[0];
  59742. var parentBone = bone.getParent();
  59743. tmat.copyFrom(bone.getLocalMatrix());
  59744. if (x !== 0 || y !== 0 || z !== 0) {
  59745. var tmat2 = BABYLON.Tmp.Matrix[1];
  59746. BABYLON.Matrix.IdentityToRef(tmat2);
  59747. tmat2.m[12] = x;
  59748. tmat2.m[13] = y;
  59749. tmat2.m[14] = z;
  59750. tmat2.multiplyToRef(tmat, tmat);
  59751. }
  59752. if (parentBone) {
  59753. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  59754. }
  59755. tmat.multiplyToRef(meshMat, tmat);
  59756. position.x = tmat.m[12];
  59757. position.y = tmat.m[13];
  59758. position.z = tmat.m[14];
  59759. };
  59760. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  59761. var len = bones.length;
  59762. var meshPos = this.mesh.position;
  59763. for (var i = 0; i < len; i++) {
  59764. var bone = bones[i];
  59765. var points = this._debugLines[i];
  59766. if (!points) {
  59767. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59768. this._debugLines[i] = points;
  59769. }
  59770. this._getBonePosition(points[0], bone, meshMat);
  59771. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  59772. points[0].subtractInPlace(meshPos);
  59773. points[1].subtractInPlace(meshPos);
  59774. }
  59775. };
  59776. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  59777. var len = bones.length;
  59778. var boneNum = 0;
  59779. var meshPos = this.mesh.position;
  59780. for (var i = len - 1; i >= 0; i--) {
  59781. var childBone = bones[i];
  59782. var parentBone = childBone.getParent();
  59783. if (!parentBone) {
  59784. continue;
  59785. }
  59786. var points = this._debugLines[boneNum];
  59787. if (!points) {
  59788. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59789. this._debugLines[boneNum] = points;
  59790. }
  59791. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  59792. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  59793. points[0].subtractInPlace(meshPos);
  59794. points[1].subtractInPlace(meshPos);
  59795. boneNum++;
  59796. }
  59797. };
  59798. /** Update the viewer to sync with current skeleton state */
  59799. SkeletonViewer.prototype.update = function () {
  59800. if (this.autoUpdateBonesMatrices) {
  59801. this.skeleton.computeAbsoluteTransforms();
  59802. }
  59803. if (this.skeleton.bones[0].length === undefined) {
  59804. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  59805. }
  59806. else {
  59807. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  59808. }
  59809. if (!this._debugMesh) {
  59810. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  59811. this._debugMesh.renderingGroupId = this.renderingGroupId;
  59812. }
  59813. else {
  59814. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  59815. }
  59816. this._debugMesh.position.copyFrom(this.mesh.position);
  59817. this._debugMesh.color = this.color;
  59818. };
  59819. /** Release associated resources */
  59820. SkeletonViewer.prototype.dispose = function () {
  59821. if (this._debugMesh) {
  59822. this.isEnabled = false;
  59823. this._debugMesh.dispose();
  59824. this._debugMesh = null;
  59825. }
  59826. };
  59827. return SkeletonViewer;
  59828. }());
  59829. Debug.SkeletonViewer = SkeletonViewer;
  59830. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  59831. })(BABYLON || (BABYLON = {}));
  59832. //# sourceMappingURL=babylon.skeletonViewer.js.map
  59833. /**
  59834. * Module Debug contains the (visual) components to debug a scene correctly
  59835. */
  59836. var BABYLON;
  59837. (function (BABYLON) {
  59838. var Debug;
  59839. (function (Debug) {
  59840. /**
  59841. * The Axes viewer will show 3 axes in a specific point in space
  59842. */
  59843. var AxesViewer = /** @class */ (function () {
  59844. /**
  59845. * Creates a new AxesViewer
  59846. * @param scene defines the hosting scene
  59847. * @param scaleLines defines a number used to scale line length (1 by default)
  59848. */
  59849. function AxesViewer(scene, scaleLines) {
  59850. if (scaleLines === void 0) { scaleLines = 1; }
  59851. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59852. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59853. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59854. /**
  59855. * Gets or sets a number used to scale line length
  59856. */
  59857. this.scaleLines = 1;
  59858. this.scaleLines = scaleLines;
  59859. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  59860. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  59861. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  59862. this._xmesh.renderingGroupId = 2;
  59863. this._ymesh.renderingGroupId = 2;
  59864. this._zmesh.renderingGroupId = 2;
  59865. this._xmesh.material.checkReadyOnlyOnce = true;
  59866. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  59867. this._ymesh.material.checkReadyOnlyOnce = true;
  59868. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  59869. this._zmesh.material.checkReadyOnlyOnce = true;
  59870. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  59871. this.scene = scene;
  59872. }
  59873. /**
  59874. * Force the viewer to update
  59875. * @param position defines the position of the viewer
  59876. * @param xaxis defines the x axis of the viewer
  59877. * @param yaxis defines the y axis of the viewer
  59878. * @param zaxis defines the z axis of the viewer
  59879. */
  59880. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  59881. var scaleLines = this.scaleLines;
  59882. if (this._xmesh) {
  59883. this._xmesh.position.copyFrom(position);
  59884. }
  59885. if (this._ymesh) {
  59886. this._ymesh.position.copyFrom(position);
  59887. }
  59888. if (this._zmesh) {
  59889. this._zmesh.position.copyFrom(position);
  59890. }
  59891. var point2 = this._xline[1];
  59892. point2.x = xaxis.x * scaleLines;
  59893. point2.y = xaxis.y * scaleLines;
  59894. point2.z = xaxis.z * scaleLines;
  59895. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  59896. point2 = this._yline[1];
  59897. point2.x = yaxis.x * scaleLines;
  59898. point2.y = yaxis.y * scaleLines;
  59899. point2.z = yaxis.z * scaleLines;
  59900. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  59901. point2 = this._zline[1];
  59902. point2.x = zaxis.x * scaleLines;
  59903. point2.y = zaxis.y * scaleLines;
  59904. point2.z = zaxis.z * scaleLines;
  59905. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  59906. };
  59907. /** Releases resources */
  59908. AxesViewer.prototype.dispose = function () {
  59909. if (this._xmesh) {
  59910. this._xmesh.dispose();
  59911. }
  59912. if (this._ymesh) {
  59913. this._ymesh.dispose();
  59914. }
  59915. if (this._zmesh) {
  59916. this._zmesh.dispose();
  59917. }
  59918. this._xmesh = null;
  59919. this._ymesh = null;
  59920. this._zmesh = null;
  59921. this.scene = null;
  59922. };
  59923. return AxesViewer;
  59924. }());
  59925. Debug.AxesViewer = AxesViewer;
  59926. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  59927. })(BABYLON || (BABYLON = {}));
  59928. //# sourceMappingURL=babylon.axesViewer.js.map
  59929. var BABYLON;
  59930. (function (BABYLON) {
  59931. var Debug;
  59932. (function (Debug) {
  59933. /**
  59934. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  59935. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  59936. */
  59937. var BoneAxesViewer = /** @class */ (function (_super) {
  59938. __extends(BoneAxesViewer, _super);
  59939. /**
  59940. * Creates a new BoneAxesViewer
  59941. * @param scene defines the hosting scene
  59942. * @param bone defines the target bone
  59943. * @param mesh defines the target mesh
  59944. * @param scaleLines defines a scaling factor for line length (1 by default)
  59945. */
  59946. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  59947. if (scaleLines === void 0) { scaleLines = 1; }
  59948. var _this = _super.call(this, scene, scaleLines) || this;
  59949. /** Gets current position */
  59950. _this.pos = BABYLON.Vector3.Zero();
  59951. /** Gets direction of X axis */
  59952. _this.xaxis = BABYLON.Vector3.Zero();
  59953. /** Gets direction of Y axis */
  59954. _this.yaxis = BABYLON.Vector3.Zero();
  59955. /** Gets direction of Z axis */
  59956. _this.zaxis = BABYLON.Vector3.Zero();
  59957. _this.mesh = mesh;
  59958. _this.bone = bone;
  59959. return _this;
  59960. }
  59961. /**
  59962. * Force the viewer to update
  59963. */
  59964. BoneAxesViewer.prototype.update = function () {
  59965. if (!this.mesh || !this.bone) {
  59966. return;
  59967. }
  59968. var bone = this.bone;
  59969. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  59970. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  59971. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  59972. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  59973. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  59974. };
  59975. /** Releases resources */
  59976. BoneAxesViewer.prototype.dispose = function () {
  59977. if (this.mesh) {
  59978. this.mesh = null;
  59979. this.bone = null;
  59980. _super.prototype.dispose.call(this);
  59981. }
  59982. };
  59983. return BoneAxesViewer;
  59984. }(Debug.AxesViewer));
  59985. Debug.BoneAxesViewer = BoneAxesViewer;
  59986. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  59987. })(BABYLON || (BABYLON = {}));
  59988. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  59989. var BABYLON;
  59990. (function (BABYLON) {
  59991. var RayHelper = /** @class */ (function () {
  59992. function RayHelper(ray) {
  59993. this.ray = ray;
  59994. }
  59995. RayHelper.CreateAndShow = function (ray, scene, color) {
  59996. var helper = new RayHelper(ray);
  59997. helper.show(scene, color);
  59998. return helper;
  59999. };
  60000. RayHelper.prototype.show = function (scene, color) {
  60001. if (!this._renderFunction && this.ray) {
  60002. var ray = this.ray;
  60003. this._renderFunction = this._render.bind(this);
  60004. this._scene = scene;
  60005. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  60006. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  60007. if (this._renderFunction) {
  60008. this._scene.registerBeforeRender(this._renderFunction);
  60009. }
  60010. }
  60011. if (color && this._renderLine) {
  60012. this._renderLine.color.copyFrom(color);
  60013. }
  60014. };
  60015. RayHelper.prototype.hide = function () {
  60016. if (this._renderFunction && this._scene) {
  60017. this._scene.unregisterBeforeRender(this._renderFunction);
  60018. this._scene = null;
  60019. this._renderFunction = null;
  60020. if (this._renderLine) {
  60021. this._renderLine.dispose();
  60022. this._renderLine = null;
  60023. }
  60024. this._renderPoints = [];
  60025. }
  60026. };
  60027. RayHelper.prototype._render = function () {
  60028. var ray = this.ray;
  60029. if (!ray) {
  60030. return;
  60031. }
  60032. var point = this._renderPoints[1];
  60033. var len = Math.min(ray.length, 1000000);
  60034. point.copyFrom(ray.direction);
  60035. point.scaleInPlace(len);
  60036. point.addInPlace(ray.origin);
  60037. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  60038. };
  60039. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  60040. this._attachedToMesh = mesh;
  60041. var ray = this.ray;
  60042. if (!ray) {
  60043. return;
  60044. }
  60045. if (!ray.direction) {
  60046. ray.direction = BABYLON.Vector3.Zero();
  60047. }
  60048. if (!ray.origin) {
  60049. ray.origin = BABYLON.Vector3.Zero();
  60050. }
  60051. if (length) {
  60052. ray.length = length;
  60053. }
  60054. if (!meshSpaceOrigin) {
  60055. meshSpaceOrigin = BABYLON.Vector3.Zero();
  60056. }
  60057. if (!meshSpaceDirection) {
  60058. // -1 so that this will work with Mesh.lookAt
  60059. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  60060. }
  60061. if (!this._meshSpaceDirection) {
  60062. this._meshSpaceDirection = meshSpaceDirection.clone();
  60063. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  60064. }
  60065. else {
  60066. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  60067. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  60068. }
  60069. if (!this._updateToMeshFunction) {
  60070. this._updateToMeshFunction = this._updateToMesh.bind(this);
  60071. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  60072. }
  60073. this._updateToMesh();
  60074. };
  60075. RayHelper.prototype.detachFromMesh = function () {
  60076. if (this._attachedToMesh) {
  60077. if (this._updateToMeshFunction) {
  60078. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  60079. }
  60080. this._attachedToMesh = null;
  60081. this._updateToMeshFunction = null;
  60082. }
  60083. };
  60084. RayHelper.prototype._updateToMesh = function () {
  60085. var ray = this.ray;
  60086. if (!this._attachedToMesh || !ray) {
  60087. return;
  60088. }
  60089. if (this._attachedToMesh._isDisposed) {
  60090. this.detachFromMesh();
  60091. return;
  60092. }
  60093. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  60094. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  60095. };
  60096. RayHelper.prototype.dispose = function () {
  60097. this.hide();
  60098. this.detachFromMesh();
  60099. this.ray = null;
  60100. };
  60101. return RayHelper;
  60102. }());
  60103. BABYLON.RayHelper = RayHelper;
  60104. })(BABYLON || (BABYLON = {}));
  60105. //# sourceMappingURL=babylon.rayHelper.js.map
  60106. var BABYLON;
  60107. (function (BABYLON) {
  60108. // load the inspector using require, if not present in the global namespace.
  60109. var DebugLayer = /** @class */ (function () {
  60110. function DebugLayer(scene) {
  60111. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  60112. this.onPropertyChangedObservable = new BABYLON.Observable();
  60113. this._scene = scene;
  60114. }
  60115. /** Creates the inspector window. */
  60116. DebugLayer.prototype._createInspector = function (config) {
  60117. if (config === void 0) { config = {}; }
  60118. var popup = config.popup || false;
  60119. var initialTab = config.initialTab || 0;
  60120. var parentElement = config.parentElement || null;
  60121. if (!this._inspector) {
  60122. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  60123. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  60124. } // else nothing to do as instance is already created
  60125. };
  60126. DebugLayer.prototype.isVisible = function () {
  60127. if (!this._inspector) {
  60128. return false;
  60129. }
  60130. return true;
  60131. };
  60132. DebugLayer.prototype.hide = function () {
  60133. if (this._inspector) {
  60134. try {
  60135. this._inspector.dispose();
  60136. }
  60137. catch (e) {
  60138. // If the inspector has been removed directly from the inspector tool
  60139. }
  60140. this.onPropertyChangedObservable.clear();
  60141. this._inspector = null;
  60142. }
  60143. };
  60144. /**
  60145. *
  60146. * Launch the debugLayer.
  60147. *
  60148. * initialTab:
  60149. * | Value | Tab Name |
  60150. * | --- | --- |
  60151. * | 0 | Scene |
  60152. * | 1 | Console |
  60153. * | 2 | Stats |
  60154. * | 3 | Textures |
  60155. * | 4 | Mesh |
  60156. * | 5 | Light |
  60157. * | 6 | Material |
  60158. * | 7 | GLTF |
  60159. * | 8 | GUI |
  60160. * | 9 | Physics |
  60161. * | 10 | Camera |
  60162. * | 11 | Audio |
  60163. *
  60164. */
  60165. DebugLayer.prototype.show = function (config) {
  60166. if (config === void 0) { config = {}; }
  60167. if (typeof this.BJSINSPECTOR == 'undefined') {
  60168. // Load inspector and add it to the DOM
  60169. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  60170. }
  60171. else {
  60172. // Otherwise creates the inspector
  60173. this._createInspector(config);
  60174. }
  60175. };
  60176. /**
  60177. * Gets the active tab
  60178. * @return the index of the active tab or -1 if the inspector is hidden
  60179. */
  60180. DebugLayer.prototype.getActiveTab = function () {
  60181. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  60182. };
  60183. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  60184. return DebugLayer;
  60185. }());
  60186. BABYLON.DebugLayer = DebugLayer;
  60187. })(BABYLON || (BABYLON = {}));
  60188. //# sourceMappingURL=babylon.debugLayer.js.map
  60189. var BABYLON;
  60190. (function (BABYLON) {
  60191. var Debug;
  60192. (function (Debug) {
  60193. /**
  60194. * Used to show the physics impostor around the specific mesh
  60195. */
  60196. var PhysicsViewer = /** @class */ (function () {
  60197. /**
  60198. * Creates a new PhysicsViewer
  60199. * @param scene defines the hosting scene
  60200. */
  60201. function PhysicsViewer(scene) {
  60202. /** @hidden */
  60203. this._impostors = [];
  60204. /** @hidden */
  60205. this._meshes = [];
  60206. /** @hidden */
  60207. this._numMeshes = 0;
  60208. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  60209. var physicEngine = this._scene.getPhysicsEngine();
  60210. if (physicEngine) {
  60211. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  60212. }
  60213. }
  60214. /** @hidden */
  60215. PhysicsViewer.prototype._updateDebugMeshes = function () {
  60216. var plugin = this._physicsEnginePlugin;
  60217. for (var i = 0; i < this._numMeshes; i++) {
  60218. var impostor = this._impostors[i];
  60219. if (!impostor) {
  60220. continue;
  60221. }
  60222. if (impostor.isDisposed) {
  60223. this.hideImpostor(this._impostors[i--]);
  60224. }
  60225. else {
  60226. var mesh = this._meshes[i];
  60227. if (mesh && plugin) {
  60228. plugin.syncMeshWithImpostor(mesh, impostor);
  60229. }
  60230. }
  60231. }
  60232. };
  60233. /**
  60234. * Renders a specified physic impostor
  60235. * @param impostor defines the impostor to render
  60236. */
  60237. PhysicsViewer.prototype.showImpostor = function (impostor) {
  60238. if (!this._scene) {
  60239. return;
  60240. }
  60241. for (var i = 0; i < this._numMeshes; i++) {
  60242. if (this._impostors[i] == impostor) {
  60243. return;
  60244. }
  60245. }
  60246. var debugMesh = this._getDebugMesh(impostor, this._scene);
  60247. if (debugMesh) {
  60248. this._impostors[this._numMeshes] = impostor;
  60249. this._meshes[this._numMeshes] = debugMesh;
  60250. if (this._numMeshes === 0) {
  60251. this._renderFunction = this._updateDebugMeshes.bind(this);
  60252. this._scene.registerBeforeRender(this._renderFunction);
  60253. }
  60254. this._numMeshes++;
  60255. }
  60256. };
  60257. /**
  60258. * Hides a specified physic impostor
  60259. * @param impostor defines the impostor to hide
  60260. */
  60261. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  60262. if (!impostor || !this._scene) {
  60263. return;
  60264. }
  60265. var removed = false;
  60266. for (var i = 0; i < this._numMeshes; i++) {
  60267. if (this._impostors[i] == impostor) {
  60268. var mesh = this._meshes[i];
  60269. if (!mesh) {
  60270. continue;
  60271. }
  60272. this._scene.removeMesh(mesh);
  60273. mesh.dispose();
  60274. this._numMeshes--;
  60275. if (this._numMeshes > 0) {
  60276. this._meshes[i] = this._meshes[this._numMeshes];
  60277. this._impostors[i] = this._impostors[this._numMeshes];
  60278. this._meshes[this._numMeshes] = null;
  60279. this._impostors[this._numMeshes] = null;
  60280. }
  60281. else {
  60282. this._meshes[0] = null;
  60283. this._impostors[0] = null;
  60284. }
  60285. removed = true;
  60286. break;
  60287. }
  60288. }
  60289. if (removed && this._numMeshes === 0) {
  60290. this._scene.unregisterBeforeRender(this._renderFunction);
  60291. }
  60292. };
  60293. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  60294. if (!this._debugMaterial) {
  60295. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  60296. this._debugMaterial.wireframe = true;
  60297. }
  60298. return this._debugMaterial;
  60299. };
  60300. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  60301. if (!this._debugBoxMesh) {
  60302. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  60303. this._debugBoxMesh.renderingGroupId = 1;
  60304. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  60305. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  60306. scene.removeMesh(this._debugBoxMesh);
  60307. }
  60308. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  60309. };
  60310. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  60311. if (!this._debugSphereMesh) {
  60312. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  60313. this._debugSphereMesh.renderingGroupId = 1;
  60314. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  60315. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  60316. scene.removeMesh(this._debugSphereMesh);
  60317. }
  60318. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  60319. };
  60320. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  60321. var mesh = null;
  60322. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  60323. mesh = this._getDebugBoxMesh(scene);
  60324. impostor.getBoxSizeToRef(mesh.scaling);
  60325. }
  60326. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  60327. mesh = this._getDebugSphereMesh(scene);
  60328. var radius = impostor.getRadius();
  60329. mesh.scaling.x = radius * 2;
  60330. mesh.scaling.y = radius * 2;
  60331. mesh.scaling.z = radius * 2;
  60332. }
  60333. return mesh;
  60334. };
  60335. /** Releases all resources */
  60336. PhysicsViewer.prototype.dispose = function () {
  60337. for (var i = 0; i < this._numMeshes; i++) {
  60338. this.hideImpostor(this._impostors[i]);
  60339. }
  60340. if (this._debugBoxMesh) {
  60341. this._debugBoxMesh.dispose();
  60342. }
  60343. if (this._debugSphereMesh) {
  60344. this._debugSphereMesh.dispose();
  60345. }
  60346. if (this._debugMaterial) {
  60347. this._debugMaterial.dispose();
  60348. }
  60349. this._impostors.length = 0;
  60350. this._scene = null;
  60351. this._physicsEnginePlugin = null;
  60352. };
  60353. return PhysicsViewer;
  60354. }());
  60355. Debug.PhysicsViewer = PhysicsViewer;
  60356. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  60357. })(BABYLON || (BABYLON = {}));
  60358. //# sourceMappingURL=babylon.physicsViewer.js.map
  60359. var BABYLON;
  60360. (function (BABYLON) {
  60361. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  60362. get: function () {
  60363. return this._forceShowBoundingBoxes || false;
  60364. },
  60365. set: function (value) {
  60366. this._forceShowBoundingBoxes = value;
  60367. // Lazyly creates a BB renderer if needed.
  60368. if (value) {
  60369. this.getBoundingBoxRenderer();
  60370. }
  60371. },
  60372. enumerable: true,
  60373. configurable: true
  60374. });
  60375. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  60376. if (!this._boundingBoxRenderer) {
  60377. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  60378. }
  60379. return this._boundingBoxRenderer;
  60380. };
  60381. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  60382. get: function () {
  60383. return this._showBoundingBox || false;
  60384. },
  60385. set: function (value) {
  60386. this._showBoundingBox = value;
  60387. // Lazyly creates a BB renderer if needed.
  60388. if (value) {
  60389. this.getScene().getBoundingBoxRenderer();
  60390. }
  60391. },
  60392. enumerable: true,
  60393. configurable: true
  60394. });
  60395. var BoundingBoxRenderer = /** @class */ (function () {
  60396. function BoundingBoxRenderer(scene) {
  60397. /**
  60398. * The component name helpfull to identify the component in the list of scene components.
  60399. */
  60400. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  60401. this.frontColor = new BABYLON.Color3(1, 1, 1);
  60402. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  60403. this.showBackLines = true;
  60404. this.renderList = new BABYLON.SmartArray(32);
  60405. this._vertexBuffers = {};
  60406. this.scene = scene;
  60407. scene._addComponent(this);
  60408. }
  60409. /**
  60410. * Registers the component in a given scene
  60411. */
  60412. BoundingBoxRenderer.prototype.register = function () {
  60413. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  60414. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  60415. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  60416. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_BOUNDINGBOXRENDERER, this, this.render);
  60417. };
  60418. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  60419. if (mesh.showSubMeshesBoundingBox) {
  60420. var boundingInfo = subMesh.getBoundingInfo();
  60421. if (boundingInfo !== null && boundingInfo !== undefined) {
  60422. this.renderList.push(boundingInfo.boundingBox);
  60423. }
  60424. }
  60425. };
  60426. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  60427. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  60428. var boundingInfo = sourceMesh.getBoundingInfo();
  60429. this.renderList.push(boundingInfo.boundingBox);
  60430. }
  60431. };
  60432. BoundingBoxRenderer.prototype._prepareRessources = function () {
  60433. if (this._colorShader) {
  60434. return;
  60435. }
  60436. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  60437. attributes: [BABYLON.VertexBuffer.PositionKind],
  60438. uniforms: ["world", "viewProjection", "color"]
  60439. });
  60440. var engine = this.scene.getEngine();
  60441. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  60442. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  60443. this._createIndexBuffer();
  60444. };
  60445. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  60446. var engine = this.scene.getEngine();
  60447. 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]);
  60448. };
  60449. /**
  60450. * Rebuilds the elements related to this component in case of
  60451. * context lost for instance.
  60452. */
  60453. BoundingBoxRenderer.prototype.rebuild = function () {
  60454. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  60455. if (vb) {
  60456. vb._rebuild();
  60457. }
  60458. this._createIndexBuffer();
  60459. };
  60460. BoundingBoxRenderer.prototype.reset = function () {
  60461. this.renderList.reset();
  60462. };
  60463. BoundingBoxRenderer.prototype.render = function () {
  60464. if (this.renderList.length === 0) {
  60465. return;
  60466. }
  60467. this._prepareRessources();
  60468. if (!this._colorShader.isReady()) {
  60469. return;
  60470. }
  60471. var engine = this.scene.getEngine();
  60472. engine.setDepthWrite(false);
  60473. this._colorShader._preBind();
  60474. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  60475. var boundingBox = this.renderList.data[boundingBoxIndex];
  60476. var min = boundingBox.minimum;
  60477. var max = boundingBox.maximum;
  60478. var diff = max.subtract(min);
  60479. var median = min.add(diff.scale(0.5));
  60480. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  60481. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  60482. .multiply(boundingBox.getWorldMatrix());
  60483. // VBOs
  60484. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  60485. if (this.showBackLines) {
  60486. // Back
  60487. engine.setDepthFunctionToGreaterOrEqual();
  60488. this.scene.resetCachedMaterial();
  60489. this._colorShader.setColor4("color", this.backColor.toColor4());
  60490. this._colorShader.bind(worldMatrix);
  60491. // Draw order
  60492. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  60493. }
  60494. // Front
  60495. engine.setDepthFunctionToLess();
  60496. this.scene.resetCachedMaterial();
  60497. this._colorShader.setColor4("color", this.frontColor.toColor4());
  60498. this._colorShader.bind(worldMatrix);
  60499. // Draw order
  60500. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  60501. }
  60502. this._colorShader.unbind();
  60503. engine.setDepthFunctionToLessOrEqual();
  60504. engine.setDepthWrite(true);
  60505. };
  60506. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  60507. this._prepareRessources();
  60508. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  60509. return;
  60510. }
  60511. var engine = this.scene.getEngine();
  60512. engine.setDepthWrite(false);
  60513. engine.setColorWrite(false);
  60514. this._colorShader._preBind();
  60515. var boundingBox = mesh._boundingInfo.boundingBox;
  60516. var min = boundingBox.minimum;
  60517. var max = boundingBox.maximum;
  60518. var diff = max.subtract(min);
  60519. var median = min.add(diff.scale(0.5));
  60520. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  60521. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  60522. .multiply(boundingBox.getWorldMatrix());
  60523. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  60524. engine.setDepthFunctionToLess();
  60525. this.scene.resetCachedMaterial();
  60526. this._colorShader.bind(worldMatrix);
  60527. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  60528. this._colorShader.unbind();
  60529. engine.setDepthFunctionToLessOrEqual();
  60530. engine.setDepthWrite(true);
  60531. engine.setColorWrite(true);
  60532. };
  60533. BoundingBoxRenderer.prototype.dispose = function () {
  60534. if (!this._colorShader) {
  60535. return;
  60536. }
  60537. this.renderList.dispose();
  60538. this._colorShader.dispose();
  60539. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  60540. if (buffer) {
  60541. buffer.dispose();
  60542. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  60543. }
  60544. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  60545. };
  60546. return BoundingBoxRenderer;
  60547. }());
  60548. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  60549. })(BABYLON || (BABYLON = {}));
  60550. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  60551. var BABYLON;
  60552. (function (BABYLON) {
  60553. BABYLON.Engine.prototype.createTransformFeedback = function () {
  60554. return this._gl.createTransformFeedback();
  60555. };
  60556. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  60557. this._gl.deleteTransformFeedback(value);
  60558. };
  60559. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  60560. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  60561. };
  60562. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  60563. if (usePoints === void 0) { usePoints = true; }
  60564. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  60565. };
  60566. BABYLON.Engine.prototype.endTransformFeedback = function () {
  60567. this._gl.endTransformFeedback();
  60568. };
  60569. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  60570. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  60571. };
  60572. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  60573. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  60574. };
  60575. })(BABYLON || (BABYLON = {}));
  60576. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  60577. var BABYLON;
  60578. (function (BABYLON) {
  60579. /**
  60580. * This represents a GPU particle system in Babylon
  60581. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  60582. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  60583. */
  60584. var GPUParticleSystem = /** @class */ (function (_super) {
  60585. __extends(GPUParticleSystem, _super);
  60586. /**
  60587. * Instantiates a GPU particle system.
  60588. * 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.
  60589. * @param name The name of the particle system
  60590. * @param options The options used to create the system
  60591. * @param scene The scene the particle system belongs to
  60592. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  60593. */
  60594. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  60595. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  60596. var _this = _super.call(this, name) || this;
  60597. /**
  60598. * The layer mask we are rendering the particles through.
  60599. */
  60600. _this.layerMask = 0x0FFFFFFF;
  60601. _this._accumulatedCount = 0;
  60602. _this._targetIndex = 0;
  60603. _this._currentRenderId = -1;
  60604. _this._started = false;
  60605. _this._stopped = false;
  60606. _this._timeDelta = 0;
  60607. _this._attributesStrideSize = 21;
  60608. _this._actualFrame = 0;
  60609. _this._rawTextureWidth = 256;
  60610. /**
  60611. * An event triggered when the system is disposed.
  60612. */
  60613. _this.onDisposeObservable = new BABYLON.Observable();
  60614. /**
  60615. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  60616. * to override the particles.
  60617. */
  60618. _this.forceDepthWrite = false;
  60619. _this._preWarmDone = false;
  60620. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  60621. // Setup the default processing configuration to the scene.
  60622. _this._attachImageProcessingConfiguration(null);
  60623. _this._engine = _this._scene.getEngine();
  60624. if (!options.randomTextureSize) {
  60625. delete options.randomTextureSize;
  60626. }
  60627. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  60628. var optionsAsNumber = options;
  60629. if (isFinite(optionsAsNumber)) {
  60630. fullOptions.capacity = optionsAsNumber;
  60631. }
  60632. _this._capacity = fullOptions.capacity;
  60633. _this._activeCount = fullOptions.capacity;
  60634. _this._currentActiveCount = 0;
  60635. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  60636. _this._scene.particleSystems.push(_this);
  60637. _this._updateEffectOptions = {
  60638. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex"],
  60639. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  60640. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  60641. "angleRange", "radiusRange", "cellInfos", "noiseStrength"],
  60642. uniformBuffersNames: [],
  60643. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "noiseSampler"],
  60644. defines: "",
  60645. fallbacks: null,
  60646. onCompiled: null,
  60647. onError: null,
  60648. indexParameters: null,
  60649. maxSimultaneousLights: 0,
  60650. transformFeedbackVaryings: []
  60651. };
  60652. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  60653. // Random data
  60654. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  60655. var d = [];
  60656. for (var i = 0; i < maxTextureSize; ++i) {
  60657. d.push(Math.random());
  60658. d.push(Math.random());
  60659. d.push(Math.random());
  60660. d.push(Math.random());
  60661. }
  60662. _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);
  60663. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60664. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60665. d = [];
  60666. for (var i = 0; i < maxTextureSize; ++i) {
  60667. d.push(Math.random());
  60668. d.push(Math.random());
  60669. d.push(Math.random());
  60670. d.push(Math.random());
  60671. }
  60672. _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);
  60673. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60674. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60675. _this._randomTextureSize = maxTextureSize;
  60676. return _this;
  60677. }
  60678. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  60679. /**
  60680. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  60681. */
  60682. get: function () {
  60683. if (!BABYLON.Engine.LastCreatedEngine) {
  60684. return false;
  60685. }
  60686. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  60687. },
  60688. enumerable: true,
  60689. configurable: true
  60690. });
  60691. /**
  60692. * Gets the maximum number of particles active at the same time.
  60693. * @returns The max number of active particles.
  60694. */
  60695. GPUParticleSystem.prototype.getCapacity = function () {
  60696. return this._capacity;
  60697. };
  60698. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  60699. /**
  60700. * Gets or set the number of active particles
  60701. */
  60702. get: function () {
  60703. return this._activeCount;
  60704. },
  60705. set: function (value) {
  60706. this._activeCount = Math.min(value, this._capacity);
  60707. },
  60708. enumerable: true,
  60709. configurable: true
  60710. });
  60711. /**
  60712. * Is this system ready to be used/rendered
  60713. * @return true if the system is ready
  60714. */
  60715. GPUParticleSystem.prototype.isReady = function () {
  60716. if (!this._updateEffect) {
  60717. this._recreateUpdateEffect();
  60718. this._recreateRenderEffect();
  60719. return false;
  60720. }
  60721. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  60722. return false;
  60723. }
  60724. return true;
  60725. };
  60726. /**
  60727. * Gets Wether the system has been started.
  60728. * @returns True if it has been started, otherwise false.
  60729. */
  60730. GPUParticleSystem.prototype.isStarted = function () {
  60731. return this._started;
  60732. };
  60733. /**
  60734. * Starts the particle system and begins to emit
  60735. * @param delay defines the delay in milliseconds before starting the system (0 by default)
  60736. */
  60737. GPUParticleSystem.prototype.start = function (delay) {
  60738. var _this = this;
  60739. if (delay === void 0) { delay = 0; }
  60740. if (delay) {
  60741. setTimeout(function () {
  60742. _this.start(0);
  60743. }, delay);
  60744. return;
  60745. }
  60746. this._started = true;
  60747. this._stopped = false;
  60748. this._preWarmDone = false;
  60749. };
  60750. /**
  60751. * Stops the particle system.
  60752. */
  60753. GPUParticleSystem.prototype.stop = function () {
  60754. this._stopped = true;
  60755. };
  60756. /**
  60757. * Remove all active particles
  60758. */
  60759. GPUParticleSystem.prototype.reset = function () {
  60760. this._releaseBuffers();
  60761. this._releaseVAOs();
  60762. this._currentActiveCount = 0;
  60763. this._targetIndex = 0;
  60764. };
  60765. /**
  60766. * Returns the string "GPUParticleSystem"
  60767. * @returns a string containing the class name
  60768. */
  60769. GPUParticleSystem.prototype.getClassName = function () {
  60770. return "GPUParticleSystem";
  60771. };
  60772. GPUParticleSystem.prototype._removeGradient = function (gradient, gradients, texture) {
  60773. if (!gradients) {
  60774. return this;
  60775. }
  60776. var index = 0;
  60777. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  60778. var valueGradient = gradients_1[_i];
  60779. if (valueGradient.gradient === gradient) {
  60780. gradients.splice(index, 1);
  60781. break;
  60782. }
  60783. index++;
  60784. }
  60785. if (texture) {
  60786. texture.dispose();
  60787. }
  60788. this._releaseBuffers();
  60789. return this;
  60790. };
  60791. /**
  60792. * Adds a new color gradient
  60793. * @param gradient defines the gradient to use (between 0 and 1)
  60794. * @param color defines the color to affect to the specified gradient
  60795. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  60796. * @returns the current particle system
  60797. */
  60798. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  60799. if (!this._colorGradients) {
  60800. this._colorGradients = [];
  60801. }
  60802. var colorGradient = new BABYLON.ColorGradient();
  60803. colorGradient.gradient = gradient;
  60804. colorGradient.color1 = color1;
  60805. this._colorGradients.push(colorGradient);
  60806. this._colorGradients.sort(function (a, b) {
  60807. if (a.gradient < b.gradient) {
  60808. return -1;
  60809. }
  60810. else if (a.gradient > b.gradient) {
  60811. return 1;
  60812. }
  60813. return 0;
  60814. });
  60815. if (this._colorGradientsTexture) {
  60816. this._colorGradientsTexture.dispose();
  60817. this._colorGradientsTexture = null;
  60818. }
  60819. this._releaseBuffers();
  60820. return this;
  60821. };
  60822. /**
  60823. * Remove a specific color gradient
  60824. * @param gradient defines the gradient to remove
  60825. * @returns the current particle system
  60826. */
  60827. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  60828. this._removeGradient(gradient, this._colorGradients, this._colorGradientsTexture);
  60829. this._colorGradientsTexture = null;
  60830. return this;
  60831. };
  60832. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  60833. var valueGradient = new BABYLON.FactorGradient();
  60834. valueGradient.gradient = gradient;
  60835. valueGradient.factor1 = factor;
  60836. factorGradients.push(valueGradient);
  60837. factorGradients.sort(function (a, b) {
  60838. if (a.gradient < b.gradient) {
  60839. return -1;
  60840. }
  60841. else if (a.gradient > b.gradient) {
  60842. return 1;
  60843. }
  60844. return 0;
  60845. });
  60846. this._releaseBuffers();
  60847. };
  60848. /**
  60849. * Adds a new size gradient
  60850. * @param gradient defines the gradient to use (between 0 and 1)
  60851. * @param factor defines the size factor to affect to the specified gradient
  60852. * @returns the current particle system
  60853. */
  60854. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  60855. if (!this._sizeGradients) {
  60856. this._sizeGradients = [];
  60857. }
  60858. this._addFactorGradient(this._sizeGradients, gradient, factor);
  60859. if (this._sizeGradientsTexture) {
  60860. this._sizeGradientsTexture.dispose();
  60861. this._sizeGradientsTexture = null;
  60862. }
  60863. this._releaseBuffers();
  60864. return this;
  60865. };
  60866. /**
  60867. * Remove a specific size gradient
  60868. * @param gradient defines the gradient to remove
  60869. * @returns the current particle system
  60870. */
  60871. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  60872. this._removeGradient(gradient, this._sizeGradients, this._sizeGradientsTexture);
  60873. this._sizeGradientsTexture = null;
  60874. return this;
  60875. };
  60876. /**
  60877. * Adds a new angular speed gradient
  60878. * @param gradient defines the gradient to use (between 0 and 1)
  60879. * @param factor defines the angular speed to affect to the specified gradient
  60880. * @returns the current particle system
  60881. */
  60882. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  60883. if (!this._angularSpeedGradients) {
  60884. this._angularSpeedGradients = [];
  60885. }
  60886. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  60887. if (this._angularSpeedGradientsTexture) {
  60888. this._angularSpeedGradientsTexture.dispose();
  60889. this._angularSpeedGradientsTexture = null;
  60890. }
  60891. this._releaseBuffers();
  60892. return this;
  60893. };
  60894. /**
  60895. * Remove a specific angular speed gradient
  60896. * @param gradient defines the gradient to remove
  60897. * @returns the current particle system
  60898. */
  60899. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  60900. this._removeGradient(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  60901. this._angularSpeedGradientsTexture = null;
  60902. return this;
  60903. };
  60904. /**
  60905. * Adds a new velocity gradient
  60906. * @param gradient defines the gradient to use (between 0 and 1)
  60907. * @param factor defines the velocity to affect to the specified gradient
  60908. * @returns the current particle system
  60909. */
  60910. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  60911. if (!this._velocityGradients) {
  60912. this._velocityGradients = [];
  60913. }
  60914. this._addFactorGradient(this._velocityGradients, gradient, factor);
  60915. if (this._velocityGradientsTexture) {
  60916. this._velocityGradientsTexture.dispose();
  60917. this._velocityGradientsTexture = null;
  60918. }
  60919. this._releaseBuffers();
  60920. return this;
  60921. };
  60922. /**
  60923. * Remove a specific velocity gradient
  60924. * @param gradient defines the gradient to remove
  60925. * @returns the current particle system
  60926. */
  60927. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  60928. this._removeGradient(gradient, this._velocityGradients, this._velocityGradientsTexture);
  60929. this._velocityGradientsTexture = null;
  60930. return this;
  60931. };
  60932. /**
  60933. * Adds a new limit velocity gradient
  60934. * @param gradient defines the gradient to use (between 0 and 1)
  60935. * @param factor defines the limit velocity value to affect to the specified gradient
  60936. * @returns the current particle system
  60937. */
  60938. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  60939. if (!this._limitVelocityGradients) {
  60940. this._limitVelocityGradients = [];
  60941. }
  60942. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  60943. if (this._limitVelocityGradientsTexture) {
  60944. this._limitVelocityGradientsTexture.dispose();
  60945. this._limitVelocityGradientsTexture = null;
  60946. }
  60947. this._releaseBuffers();
  60948. return this;
  60949. };
  60950. /**
  60951. * Remove a specific limit velocity gradient
  60952. * @param gradient defines the gradient to remove
  60953. * @returns the current particle system
  60954. */
  60955. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  60956. this._removeGradient(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  60957. this._limitVelocityGradientsTexture = null;
  60958. return this;
  60959. };
  60960. GPUParticleSystem.prototype._reset = function () {
  60961. this._releaseBuffers();
  60962. };
  60963. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  60964. var updateVertexBuffers = {};
  60965. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  60966. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  60967. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  60968. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  60969. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  60970. var offset = 12;
  60971. if (!this._colorGradientsTexture) {
  60972. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  60973. offset += 4;
  60974. }
  60975. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  60976. offset += 3;
  60977. if (!this._isBillboardBased) {
  60978. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  60979. offset += 3;
  60980. }
  60981. if (this._angularSpeedGradientsTexture) {
  60982. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  60983. offset += 1;
  60984. }
  60985. else {
  60986. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  60987. offset += 2;
  60988. }
  60989. if (this._isAnimationSheetEnabled) {
  60990. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  60991. offset += 1;
  60992. }
  60993. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  60994. this._engine.bindArrayBuffer(null);
  60995. return vao;
  60996. };
  60997. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  60998. var renderVertexBuffers = {};
  60999. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  61000. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  61001. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  61002. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  61003. var offset = 12;
  61004. if (!this._colorGradientsTexture) {
  61005. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  61006. offset += 4;
  61007. }
  61008. offset += 3; // Direction
  61009. if (!this._isBillboardBased) {
  61010. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  61011. offset += 3;
  61012. }
  61013. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  61014. if (this._angularSpeedGradientsTexture) {
  61015. offset++;
  61016. }
  61017. else {
  61018. offset += 2;
  61019. }
  61020. if (this._isAnimationSheetEnabled) {
  61021. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  61022. offset += 1;
  61023. }
  61024. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  61025. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  61026. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  61027. this._engine.bindArrayBuffer(null);
  61028. return vao;
  61029. };
  61030. GPUParticleSystem.prototype._initialize = function (force) {
  61031. if (force === void 0) { force = false; }
  61032. if (this._buffer0 && !force) {
  61033. return;
  61034. }
  61035. var engine = this._scene.getEngine();
  61036. var data = new Array();
  61037. if (!this.isBillboardBased) {
  61038. this._attributesStrideSize += 3;
  61039. }
  61040. if (this._colorGradientsTexture) {
  61041. this._attributesStrideSize -= 4;
  61042. }
  61043. if (this._angularSpeedGradientsTexture) {
  61044. this._attributesStrideSize -= 1;
  61045. }
  61046. if (this._isAnimationSheetEnabled) {
  61047. this._attributesStrideSize += 1;
  61048. }
  61049. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  61050. // position
  61051. data.push(0.0);
  61052. data.push(0.0);
  61053. data.push(0.0);
  61054. // Age and life
  61055. data.push(0.0); // create the particle as a dead one to create a new one at start
  61056. data.push(0.0);
  61057. // Seed
  61058. data.push(Math.random());
  61059. data.push(Math.random());
  61060. data.push(Math.random());
  61061. data.push(Math.random());
  61062. // Size
  61063. data.push(0.0);
  61064. data.push(0.0);
  61065. data.push(0.0);
  61066. if (!this._colorGradientsTexture) {
  61067. // color
  61068. data.push(0.0);
  61069. data.push(0.0);
  61070. data.push(0.0);
  61071. data.push(0.0);
  61072. }
  61073. // direction
  61074. data.push(0.0);
  61075. data.push(0.0);
  61076. data.push(0.0);
  61077. if (!this.isBillboardBased) {
  61078. // initialDirection
  61079. data.push(0.0);
  61080. data.push(0.0);
  61081. data.push(0.0);
  61082. }
  61083. // angle
  61084. data.push(0.0);
  61085. if (!this._angularSpeedGradientsTexture) {
  61086. data.push(0.0);
  61087. }
  61088. if (this._isAnimationSheetEnabled) {
  61089. data.push(0.0);
  61090. }
  61091. }
  61092. // Sprite data
  61093. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  61094. -0.5, 0.5, 0, 1,
  61095. -0.5, -0.5, 0, 0,
  61096. 0.5, -0.5, 1, 0]);
  61097. // Buffers
  61098. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  61099. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  61100. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  61101. // Update VAO
  61102. this._updateVAO = [];
  61103. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  61104. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  61105. // Render VAO
  61106. this._renderVAO = [];
  61107. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  61108. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  61109. // Links
  61110. this._sourceBuffer = this._buffer0;
  61111. this._targetBuffer = this._buffer1;
  61112. };
  61113. /** @hidden */
  61114. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  61115. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  61116. if (this._isBillboardBased) {
  61117. defines += "\n#define BILLBOARD";
  61118. }
  61119. if (this._colorGradientsTexture) {
  61120. defines += "\n#define COLORGRADIENTS";
  61121. }
  61122. if (this._sizeGradientsTexture) {
  61123. defines += "\n#define SIZEGRADIENTS";
  61124. }
  61125. if (this._angularSpeedGradientsTexture) {
  61126. defines += "\n#define ANGULARSPEEDGRADIENTS";
  61127. }
  61128. if (this._velocityGradientsTexture) {
  61129. defines += "\n#define VELOCITYGRADIENTS";
  61130. }
  61131. if (this.isAnimationSheetEnabled) {
  61132. defines += "\n#define ANIMATESHEET";
  61133. }
  61134. if (this.noiseTexture) {
  61135. defines += "\n#define NOISE";
  61136. }
  61137. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  61138. return;
  61139. }
  61140. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  61141. if (!this._colorGradientsTexture) {
  61142. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  61143. }
  61144. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  61145. if (!this._isBillboardBased) {
  61146. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  61147. }
  61148. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  61149. if (this.isAnimationSheetEnabled) {
  61150. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  61151. }
  61152. this._updateEffectOptions.defines = defines;
  61153. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  61154. };
  61155. /** @hidden */
  61156. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  61157. var defines = "";
  61158. if (this._scene.clipPlane) {
  61159. defines = "\n#define CLIPPLANE";
  61160. }
  61161. if (this._scene.clipPlane2) {
  61162. defines = "\n#define CLIPPLANE2";
  61163. }
  61164. if (this._scene.clipPlane3) {
  61165. defines = "\n#define CLIPPLANE3";
  61166. }
  61167. if (this._scene.clipPlane4) {
  61168. defines = "\n#define CLIPPLANE4";
  61169. }
  61170. if (this._isBillboardBased) {
  61171. defines += "\n#define BILLBOARD";
  61172. switch (this.billboardMode) {
  61173. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  61174. defines += "\n#define BILLBOARDY";
  61175. break;
  61176. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  61177. default:
  61178. break;
  61179. }
  61180. }
  61181. if (this._colorGradientsTexture) {
  61182. defines += "\n#define COLORGRADIENTS";
  61183. }
  61184. if (this.isAnimationSheetEnabled) {
  61185. defines += "\n#define ANIMATESHEET";
  61186. }
  61187. if (this._imageProcessingConfiguration) {
  61188. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  61189. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  61190. }
  61191. if (this._renderEffect && this._renderEffect.defines === defines) {
  61192. return;
  61193. }
  61194. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  61195. var samplers = ["textureSampler", "colorGradientSampler"];
  61196. if (BABYLON.ImageProcessingConfiguration) {
  61197. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  61198. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  61199. }
  61200. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  61201. };
  61202. /**
  61203. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  61204. * @param preWarm defines if we are in the pre-warmimg phase
  61205. */
  61206. GPUParticleSystem.prototype.animate = function (preWarm) {
  61207. if (preWarm === void 0) { preWarm = false; }
  61208. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  61209. this._actualFrame += this._timeDelta;
  61210. if (!this._stopped) {
  61211. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  61212. this.stop();
  61213. }
  61214. }
  61215. };
  61216. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  61217. var texture = this[textureName];
  61218. if (!factorGradients || !factorGradients.length || texture) {
  61219. return;
  61220. }
  61221. var data = new Float32Array(this._rawTextureWidth);
  61222. for (var x = 0; x < this._rawTextureWidth; x++) {
  61223. var ratio = x / this._rawTextureWidth;
  61224. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  61225. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  61226. });
  61227. }
  61228. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  61229. };
  61230. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  61231. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  61232. };
  61233. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  61234. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  61235. };
  61236. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  61237. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  61238. };
  61239. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  61240. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  61241. return;
  61242. }
  61243. var data = new Uint8Array(this._rawTextureWidth * 4);
  61244. var tmpColor = BABYLON.Tmp.Color4[0];
  61245. for (var x = 0; x < this._rawTextureWidth; x++) {
  61246. var ratio = x / this._rawTextureWidth;
  61247. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  61248. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  61249. data[x * 4] = tmpColor.r * 255;
  61250. data[x * 4 + 1] = tmpColor.g * 255;
  61251. data[x * 4 + 2] = tmpColor.b * 255;
  61252. data[x * 4 + 3] = tmpColor.a * 255;
  61253. });
  61254. }
  61255. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  61256. };
  61257. /**
  61258. * Renders the particle system in its current state
  61259. * @param preWarm defines if the system should only update the particles but not render them
  61260. * @returns the current number of particles
  61261. */
  61262. GPUParticleSystem.prototype.render = function (preWarm) {
  61263. if (preWarm === void 0) { preWarm = false; }
  61264. if (!this._started) {
  61265. return 0;
  61266. }
  61267. this._createColorGradientTexture();
  61268. this._createSizeGradientTexture();
  61269. this._createAngularSpeedGradientTexture();
  61270. this._createVelocityGradientTexture();
  61271. this._recreateUpdateEffect();
  61272. this._recreateRenderEffect();
  61273. if (!this.isReady()) {
  61274. return 0;
  61275. }
  61276. if (!preWarm) {
  61277. if (!this._preWarmDone && this.preWarmCycles) {
  61278. for (var index = 0; index < this.preWarmCycles; index++) {
  61279. this.animate(true);
  61280. this.render(true);
  61281. }
  61282. this._preWarmDone = true;
  61283. }
  61284. if (this._currentRenderId === this._scene.getRenderId()) {
  61285. return 0;
  61286. }
  61287. this._currentRenderId = this._scene.getRenderId();
  61288. }
  61289. // Get everything ready to render
  61290. this._initialize();
  61291. this._accumulatedCount += this.emitRate * this._timeDelta;
  61292. if (this._accumulatedCount > 1) {
  61293. var intPart = this._accumulatedCount | 0;
  61294. this._accumulatedCount -= intPart;
  61295. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  61296. }
  61297. if (!this._currentActiveCount) {
  61298. return 0;
  61299. }
  61300. // Enable update effect
  61301. this._engine.enableEffect(this._updateEffect);
  61302. this._engine.setState(false);
  61303. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  61304. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  61305. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  61306. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  61307. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  61308. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  61309. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  61310. if (!this._colorGradientsTexture) {
  61311. this._updateEffect.setDirectColor4("color1", this.color1);
  61312. this._updateEffect.setDirectColor4("color2", this.color2);
  61313. }
  61314. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  61315. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  61316. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  61317. this._updateEffect.setVector3("gravity", this.gravity);
  61318. if (this._sizeGradientsTexture) {
  61319. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  61320. }
  61321. if (this._angularSpeedGradientsTexture) {
  61322. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  61323. }
  61324. if (this._velocityGradientsTexture) {
  61325. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  61326. }
  61327. if (this.particleEmitterType) {
  61328. this.particleEmitterType.applyToShader(this._updateEffect);
  61329. }
  61330. if (this._isAnimationSheetEnabled) {
  61331. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  61332. }
  61333. if (this.noiseTexture) {
  61334. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  61335. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  61336. }
  61337. var emitterWM;
  61338. if (this.emitter.position) {
  61339. var emitterMesh = this.emitter;
  61340. emitterWM = emitterMesh.getWorldMatrix();
  61341. }
  61342. else {
  61343. var emitterPosition = this.emitter;
  61344. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  61345. }
  61346. this._updateEffect.setMatrix("emitterWM", emitterWM);
  61347. // Bind source VAO
  61348. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  61349. // Update
  61350. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  61351. this._engine.setRasterizerState(false);
  61352. this._engine.beginTransformFeedback(true);
  61353. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  61354. this._engine.endTransformFeedback();
  61355. this._engine.setRasterizerState(true);
  61356. this._engine.bindTransformFeedbackBuffer(null);
  61357. if (!preWarm) {
  61358. // Enable render effect
  61359. this._engine.enableEffect(this._renderEffect);
  61360. var viewMatrix = this._scene.getViewMatrix();
  61361. this._renderEffect.setMatrix("view", viewMatrix);
  61362. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  61363. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  61364. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  61365. if (this._colorGradientsTexture) {
  61366. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  61367. }
  61368. else {
  61369. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  61370. }
  61371. if (this._isAnimationSheetEnabled && this.particleTexture) {
  61372. var baseSize = this.particleTexture.getBaseSize();
  61373. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  61374. }
  61375. if (this._isBillboardBased) {
  61376. var camera = this._scene.activeCamera;
  61377. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  61378. }
  61379. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  61380. var invView = viewMatrix.clone();
  61381. invView.invert();
  61382. this._renderEffect.setMatrix("invView", invView);
  61383. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  61384. }
  61385. // image processing
  61386. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  61387. this._imageProcessingConfiguration.bind(this._renderEffect);
  61388. }
  61389. // Draw order
  61390. switch (this.blendMode) {
  61391. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  61392. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  61393. break;
  61394. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  61395. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  61396. break;
  61397. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  61398. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  61399. break;
  61400. }
  61401. if (this.forceDepthWrite) {
  61402. this._engine.setDepthWrite(true);
  61403. }
  61404. // Bind source VAO
  61405. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  61406. // Render
  61407. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  61408. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  61409. }
  61410. // Switch VAOs
  61411. this._targetIndex++;
  61412. if (this._targetIndex === 2) {
  61413. this._targetIndex = 0;
  61414. }
  61415. // Switch buffers
  61416. var tmpBuffer = this._sourceBuffer;
  61417. this._sourceBuffer = this._targetBuffer;
  61418. this._targetBuffer = tmpBuffer;
  61419. return this._currentActiveCount;
  61420. };
  61421. /**
  61422. * Rebuilds the particle system
  61423. */
  61424. GPUParticleSystem.prototype.rebuild = function () {
  61425. this._initialize(true);
  61426. };
  61427. GPUParticleSystem.prototype._releaseBuffers = function () {
  61428. if (this._buffer0) {
  61429. this._buffer0.dispose();
  61430. this._buffer0 = null;
  61431. }
  61432. if (this._buffer1) {
  61433. this._buffer1.dispose();
  61434. this._buffer1 = null;
  61435. }
  61436. if (this._spriteBuffer) {
  61437. this._spriteBuffer.dispose();
  61438. this._spriteBuffer = null;
  61439. }
  61440. };
  61441. GPUParticleSystem.prototype._releaseVAOs = function () {
  61442. if (!this._updateVAO) {
  61443. return;
  61444. }
  61445. for (var index = 0; index < this._updateVAO.length; index++) {
  61446. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  61447. }
  61448. this._updateVAO = [];
  61449. for (var index = 0; index < this._renderVAO.length; index++) {
  61450. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  61451. }
  61452. this._renderVAO = [];
  61453. };
  61454. /**
  61455. * Disposes the particle system and free the associated resources
  61456. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  61457. */
  61458. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  61459. if (disposeTexture === void 0) { disposeTexture = true; }
  61460. var index = this._scene.particleSystems.indexOf(this);
  61461. if (index > -1) {
  61462. this._scene.particleSystems.splice(index, 1);
  61463. }
  61464. this._releaseBuffers();
  61465. this._releaseVAOs();
  61466. if (this._colorGradientsTexture) {
  61467. this._colorGradientsTexture.dispose();
  61468. this._colorGradientsTexture = null;
  61469. }
  61470. if (this._sizeGradientsTexture) {
  61471. this._sizeGradientsTexture.dispose();
  61472. this._sizeGradientsTexture = null;
  61473. }
  61474. if (this._angularSpeedGradientsTexture) {
  61475. this._angularSpeedGradientsTexture.dispose();
  61476. this._angularSpeedGradientsTexture = null;
  61477. }
  61478. if (this._velocityGradientsTexture) {
  61479. this._velocityGradientsTexture.dispose();
  61480. this._velocityGradientsTexture = null;
  61481. }
  61482. if (this._limitVelocityGradientsTexture) {
  61483. this._limitVelocityGradientsTexture.dispose();
  61484. this._limitVelocityGradientsTexture = null;
  61485. }
  61486. if (this._randomTexture) {
  61487. this._randomTexture.dispose();
  61488. this._randomTexture = null;
  61489. }
  61490. if (this._randomTexture2) {
  61491. this._randomTexture2.dispose();
  61492. this._randomTexture2 = null;
  61493. }
  61494. if (disposeTexture && this.particleTexture) {
  61495. this.particleTexture.dispose();
  61496. this.particleTexture = null;
  61497. }
  61498. if (disposeTexture && this.noiseTexture) {
  61499. this.noiseTexture.dispose();
  61500. this.noiseTexture = null;
  61501. }
  61502. // Callback
  61503. this.onDisposeObservable.notifyObservers(this);
  61504. this.onDisposeObservable.clear();
  61505. };
  61506. /**
  61507. * Clones the particle system.
  61508. * @param name The name of the cloned object
  61509. * @param newEmitter The new emitter to use
  61510. * @returns the cloned particle system
  61511. */
  61512. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  61513. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  61514. BABYLON.Tools.DeepCopy(this, result);
  61515. if (newEmitter === undefined) {
  61516. newEmitter = this.emitter;
  61517. }
  61518. result.emitter = newEmitter;
  61519. if (this.particleTexture) {
  61520. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  61521. }
  61522. return result;
  61523. };
  61524. /**
  61525. * Serializes the particle system to a JSON object.
  61526. * @returns the JSON object
  61527. */
  61528. GPUParticleSystem.prototype.serialize = function () {
  61529. var serializationObject = {};
  61530. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  61531. serializationObject.activeParticleCount = this.activeParticleCount;
  61532. return serializationObject;
  61533. };
  61534. /**
  61535. * Parses a JSON object to create a GPU particle system.
  61536. * @param parsedParticleSystem The JSON object to parse
  61537. * @param scene The scene to create the particle system in
  61538. * @param rootUrl The root url to use to load external dependencies like texture
  61539. * @returns the parsed GPU particle system
  61540. */
  61541. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  61542. var name = parsedParticleSystem.name;
  61543. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  61544. if (parsedParticleSystem.activeParticleCount) {
  61545. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  61546. }
  61547. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  61548. return particleSystem;
  61549. };
  61550. return GPUParticleSystem;
  61551. }(BABYLON.BaseParticleSystem));
  61552. BABYLON.GPUParticleSystem = GPUParticleSystem;
  61553. })(BABYLON || (BABYLON = {}));
  61554. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  61555. var BABYLON;
  61556. (function (BABYLON) {
  61557. /**
  61558. * Represents one particle of a solid particle system.
  61559. */
  61560. var SolidParticle = /** @class */ (function () {
  61561. /**
  61562. * Creates a Solid Particle object.
  61563. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  61564. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  61565. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  61566. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  61567. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  61568. * @param shapeId (integer) is the model shape identifier in the SPS.
  61569. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  61570. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  61571. */
  61572. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  61573. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  61574. /**
  61575. * particle global index
  61576. */
  61577. this.idx = 0;
  61578. /**
  61579. * The color of the particle
  61580. */
  61581. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  61582. /**
  61583. * The world space position of the particle.
  61584. */
  61585. this.position = BABYLON.Vector3.Zero();
  61586. /**
  61587. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  61588. */
  61589. this.rotation = BABYLON.Vector3.Zero();
  61590. /**
  61591. * The scaling of the particle.
  61592. */
  61593. this.scaling = BABYLON.Vector3.One();
  61594. /**
  61595. * The uvs of the particle.
  61596. */
  61597. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  61598. /**
  61599. * The current speed of the particle.
  61600. */
  61601. this.velocity = BABYLON.Vector3.Zero();
  61602. /**
  61603. * The pivot point in the particle local space.
  61604. */
  61605. this.pivot = BABYLON.Vector3.Zero();
  61606. /**
  61607. * Must the particle be translated from its pivot point in its local space ?
  61608. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  61609. * Default : false
  61610. */
  61611. this.translateFromPivot = false;
  61612. /**
  61613. * Is the particle active or not ?
  61614. */
  61615. this.alive = true;
  61616. /**
  61617. * Is the particle visible or not ?
  61618. */
  61619. this.isVisible = true;
  61620. /**
  61621. * Index of this particle in the global "positions" array (Internal use)
  61622. * @hidden
  61623. */
  61624. this._pos = 0;
  61625. /**
  61626. * @hidden Index of this particle in the global "indices" array (Internal use)
  61627. */
  61628. this._ind = 0;
  61629. /**
  61630. * ModelShape id of this particle
  61631. */
  61632. this.shapeId = 0;
  61633. /**
  61634. * Index of the particle in its shape id (Internal use)
  61635. */
  61636. this.idxInShape = 0;
  61637. /**
  61638. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  61639. */
  61640. this._stillInvisible = false;
  61641. /**
  61642. * @hidden Last computed particle rotation matrix
  61643. */
  61644. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  61645. /**
  61646. * Parent particle Id, if any.
  61647. * Default null.
  61648. */
  61649. this.parentId = null;
  61650. /**
  61651. * @hidden Internal global position in the SPS.
  61652. */
  61653. this._globalPosition = BABYLON.Vector3.Zero();
  61654. this.idx = particleIndex;
  61655. this._pos = positionIndex;
  61656. this._ind = indiceIndex;
  61657. this._model = model;
  61658. this.shapeId = shapeId;
  61659. this.idxInShape = idxInShape;
  61660. this._sps = sps;
  61661. if (modelBoundingInfo) {
  61662. this._modelBoundingInfo = modelBoundingInfo;
  61663. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  61664. }
  61665. }
  61666. Object.defineProperty(SolidParticle.prototype, "scale", {
  61667. /**
  61668. * Legacy support, changed scale to scaling
  61669. */
  61670. get: function () {
  61671. return this.scaling;
  61672. },
  61673. /**
  61674. * Legacy support, changed scale to scaling
  61675. */
  61676. set: function (scale) {
  61677. this.scaling = scale;
  61678. },
  61679. enumerable: true,
  61680. configurable: true
  61681. });
  61682. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  61683. /**
  61684. * Legacy support, changed quaternion to rotationQuaternion
  61685. */
  61686. get: function () {
  61687. return this.rotationQuaternion;
  61688. },
  61689. /**
  61690. * Legacy support, changed quaternion to rotationQuaternion
  61691. */
  61692. set: function (q) {
  61693. this.rotationQuaternion = q;
  61694. },
  61695. enumerable: true,
  61696. configurable: true
  61697. });
  61698. /**
  61699. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  61700. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  61701. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  61702. * @returns true if it intersects
  61703. */
  61704. SolidParticle.prototype.intersectsMesh = function (target) {
  61705. if (!this._boundingInfo || !target._boundingInfo) {
  61706. return false;
  61707. }
  61708. if (this._sps._bSphereOnly) {
  61709. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  61710. }
  61711. return this._boundingInfo.intersects(target._boundingInfo, false);
  61712. };
  61713. return SolidParticle;
  61714. }());
  61715. BABYLON.SolidParticle = SolidParticle;
  61716. /**
  61717. * Represents the shape of the model used by one particle of a solid particle system.
  61718. * SPS internal tool, don't use it manually.
  61719. */
  61720. var ModelShape = /** @class */ (function () {
  61721. /**
  61722. * 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.
  61723. * SPS internal tool, don't use it manually.
  61724. * @hidden
  61725. */
  61726. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  61727. /**
  61728. * length of the shape in the model indices array (internal use)
  61729. * @hidden
  61730. */
  61731. this._indicesLength = 0;
  61732. this.shapeID = id;
  61733. this._shape = shape;
  61734. this._indicesLength = indicesLength;
  61735. this._shapeUV = shapeUV;
  61736. this._positionFunction = posFunction;
  61737. this._vertexFunction = vtxFunction;
  61738. }
  61739. return ModelShape;
  61740. }());
  61741. BABYLON.ModelShape = ModelShape;
  61742. /**
  61743. * Represents a Depth Sorted Particle in the solid particle system.
  61744. */
  61745. var DepthSortedParticle = /** @class */ (function () {
  61746. function DepthSortedParticle() {
  61747. /**
  61748. * Index of the particle in the "indices" array
  61749. */
  61750. this.ind = 0;
  61751. /**
  61752. * Length of the particle shape in the "indices" array
  61753. */
  61754. this.indicesLength = 0;
  61755. /**
  61756. * Squared distance from the particle to the camera
  61757. */
  61758. this.sqDistance = 0.0;
  61759. }
  61760. return DepthSortedParticle;
  61761. }());
  61762. BABYLON.DepthSortedParticle = DepthSortedParticle;
  61763. })(BABYLON || (BABYLON = {}));
  61764. //# sourceMappingURL=babylon.solidParticle.js.map
  61765. var BABYLON;
  61766. (function (BABYLON) {
  61767. /**
  61768. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  61769. *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.
  61770. * The SPS is also a particle system. It provides some methods to manage the particles.
  61771. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  61772. *
  61773. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  61774. */
  61775. var SolidParticleSystem = /** @class */ (function () {
  61776. /**
  61777. * Creates a SPS (Solid Particle System) object.
  61778. * @param name (String) is the SPS name, this will be the underlying mesh name.
  61779. * @param scene (Scene) is the scene in which the SPS is added.
  61780. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  61781. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  61782. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  61783. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  61784. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  61785. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  61786. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  61787. */
  61788. function SolidParticleSystem(name, scene, options) {
  61789. /**
  61790. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  61791. * Example : var p = SPS.particles[i];
  61792. */
  61793. this.particles = new Array();
  61794. /**
  61795. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  61796. */
  61797. this.nbParticles = 0;
  61798. /**
  61799. * If the particles must ever face the camera (default false). Useful for planar particles.
  61800. */
  61801. this.billboard = false;
  61802. /**
  61803. * Recompute normals when adding a shape
  61804. */
  61805. this.recomputeNormals = true;
  61806. /**
  61807. * This a counter ofr your own usage. It's not set by any SPS functions.
  61808. */
  61809. this.counter = 0;
  61810. /**
  61811. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  61812. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  61813. */
  61814. this.vars = {};
  61815. /**
  61816. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  61817. * @hidden
  61818. */
  61819. this._bSphereOnly = false;
  61820. /**
  61821. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  61822. * @hidden
  61823. */
  61824. this._bSphereRadiusFactor = 1.0;
  61825. this._positions = new Array();
  61826. this._indices = new Array();
  61827. this._normals = new Array();
  61828. this._colors = new Array();
  61829. this._uvs = new Array();
  61830. this._index = 0; // indices index
  61831. this._updatable = true;
  61832. this._pickable = false;
  61833. this._isVisibilityBoxLocked = false;
  61834. this._alwaysVisible = false;
  61835. this._depthSort = false;
  61836. this._shapeCounter = 0;
  61837. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  61838. this._color = new BABYLON.Color4(0, 0, 0, 0);
  61839. this._computeParticleColor = true;
  61840. this._computeParticleTexture = true;
  61841. this._computeParticleRotation = true;
  61842. this._computeParticleVertex = false;
  61843. this._computeBoundingBox = false;
  61844. this._depthSortParticles = true;
  61845. this._cam_axisZ = BABYLON.Vector3.Zero();
  61846. this._cam_axisY = BABYLON.Vector3.Zero();
  61847. this._cam_axisX = BABYLON.Vector3.Zero();
  61848. this._axisZ = BABYLON.Axis.Z;
  61849. this._camDir = BABYLON.Vector3.Zero();
  61850. this._camInvertedPosition = BABYLON.Vector3.Zero();
  61851. this._rotMatrix = new BABYLON.Matrix();
  61852. this._invertMatrix = new BABYLON.Matrix();
  61853. this._rotated = BABYLON.Vector3.Zero();
  61854. this._quaternion = new BABYLON.Quaternion();
  61855. this._vertex = BABYLON.Vector3.Zero();
  61856. this._normal = BABYLON.Vector3.Zero();
  61857. this._yaw = 0.0;
  61858. this._pitch = 0.0;
  61859. this._roll = 0.0;
  61860. this._halfroll = 0.0;
  61861. this._halfpitch = 0.0;
  61862. this._halfyaw = 0.0;
  61863. this._sinRoll = 0.0;
  61864. this._cosRoll = 0.0;
  61865. this._sinPitch = 0.0;
  61866. this._cosPitch = 0.0;
  61867. this._sinYaw = 0.0;
  61868. this._cosYaw = 0.0;
  61869. this._mustUnrotateFixedNormals = false;
  61870. this._minimum = BABYLON.Vector3.Zero();
  61871. this._maximum = BABYLON.Vector3.Zero();
  61872. this._minBbox = BABYLON.Vector3.Zero();
  61873. this._maxBbox = BABYLON.Vector3.Zero();
  61874. this._particlesIntersect = false;
  61875. this._depthSortFunction = function (p1, p2) {
  61876. return (p2.sqDistance - p1.sqDistance);
  61877. };
  61878. this._needs32Bits = false;
  61879. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  61880. this._scaledPivot = BABYLON.Vector3.Zero();
  61881. this._particleHasParent = false;
  61882. this.name = name;
  61883. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  61884. this._camera = scene.activeCamera;
  61885. this._pickable = options ? options.isPickable : false;
  61886. this._depthSort = options ? options.enableDepthSort : false;
  61887. this._particlesIntersect = options ? options.particleIntersection : false;
  61888. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  61889. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  61890. if (options && options.updatable !== undefined) {
  61891. this._updatable = options.updatable;
  61892. }
  61893. else {
  61894. this._updatable = true;
  61895. }
  61896. if (this._pickable) {
  61897. this.pickedParticles = [];
  61898. }
  61899. if (this._depthSort) {
  61900. this.depthSortedParticles = [];
  61901. }
  61902. }
  61903. /**
  61904. * Builds the SPS underlying mesh. Returns a standard Mesh.
  61905. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  61906. * @returns the created mesh
  61907. */
  61908. SolidParticleSystem.prototype.buildMesh = function () {
  61909. if (this.nbParticles === 0) {
  61910. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  61911. this.addShape(triangle, 1);
  61912. triangle.dispose();
  61913. }
  61914. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  61915. this._positions32 = new Float32Array(this._positions);
  61916. this._uvs32 = new Float32Array(this._uvs);
  61917. this._colors32 = new Float32Array(this._colors);
  61918. if (this.recomputeNormals) {
  61919. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  61920. }
  61921. this._normals32 = new Float32Array(this._normals);
  61922. this._fixedNormal32 = new Float32Array(this._normals);
  61923. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  61924. this._unrotateFixedNormals();
  61925. }
  61926. var vertexData = new BABYLON.VertexData();
  61927. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  61928. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  61929. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  61930. if (this._uvs32.length > 0) {
  61931. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  61932. }
  61933. if (this._colors32.length > 0) {
  61934. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  61935. }
  61936. var mesh = new BABYLON.Mesh(this.name, this._scene);
  61937. vertexData.applyToMesh(mesh, this._updatable);
  61938. this.mesh = mesh;
  61939. this.mesh.isPickable = this._pickable;
  61940. // free memory
  61941. if (!this._depthSort) {
  61942. this._indices = null;
  61943. }
  61944. this._positions = null;
  61945. this._normals = null;
  61946. this._uvs = null;
  61947. this._colors = null;
  61948. if (!this._updatable) {
  61949. this.particles.length = 0;
  61950. }
  61951. return mesh;
  61952. };
  61953. /**
  61954. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  61955. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  61956. * Thus the particles generated from `digest()` have their property `position` set yet.
  61957. * @param mesh ( Mesh ) is the mesh to be digested
  61958. * @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
  61959. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  61960. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  61961. * @returns the current SPS
  61962. */
  61963. SolidParticleSystem.prototype.digest = function (mesh, options) {
  61964. var size = (options && options.facetNb) || 1;
  61965. var number = (options && options.number) || 0;
  61966. var delta = (options && options.delta) || 0;
  61967. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61968. var meshInd = mesh.getIndices();
  61969. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  61970. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61971. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61972. var f = 0; // facet counter
  61973. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  61974. // compute size from number
  61975. if (number) {
  61976. number = (number > totalFacets) ? totalFacets : number;
  61977. size = Math.round(totalFacets / number);
  61978. delta = 0;
  61979. }
  61980. else {
  61981. size = (size > totalFacets) ? totalFacets : size;
  61982. }
  61983. var facetPos = []; // submesh positions
  61984. var facetInd = []; // submesh indices
  61985. var facetUV = []; // submesh UV
  61986. var facetCol = []; // submesh colors
  61987. var barycenter = BABYLON.Vector3.Zero();
  61988. var sizeO = size;
  61989. while (f < totalFacets) {
  61990. size = sizeO + Math.floor((1 + delta) * Math.random());
  61991. if (f > totalFacets - size) {
  61992. size = totalFacets - f;
  61993. }
  61994. // reset temp arrays
  61995. facetPos.length = 0;
  61996. facetInd.length = 0;
  61997. facetUV.length = 0;
  61998. facetCol.length = 0;
  61999. // iterate over "size" facets
  62000. var fi = 0;
  62001. for (var j = f * 3; j < (f + size) * 3; j++) {
  62002. facetInd.push(fi);
  62003. var i = meshInd[j];
  62004. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  62005. if (meshUV) {
  62006. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  62007. }
  62008. if (meshCol) {
  62009. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  62010. }
  62011. fi++;
  62012. }
  62013. // create a model shape for each single particle
  62014. var idx = this.nbParticles;
  62015. var shape = this._posToShape(facetPos);
  62016. var shapeUV = this._uvsToShapeUV(facetUV);
  62017. // compute the barycenter of the shape
  62018. var v;
  62019. for (v = 0; v < shape.length; v++) {
  62020. barycenter.addInPlace(shape[v]);
  62021. }
  62022. barycenter.scaleInPlace(1 / shape.length);
  62023. // shift the shape from its barycenter to the origin
  62024. for (v = 0; v < shape.length; v++) {
  62025. shape[v].subtractInPlace(barycenter);
  62026. }
  62027. var bInfo;
  62028. if (this._particlesIntersect) {
  62029. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  62030. }
  62031. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  62032. // add the particle in the SPS
  62033. var currentPos = this._positions.length;
  62034. var currentInd = this._indices.length;
  62035. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  62036. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  62037. // initialize the particle position
  62038. this.particles[this.nbParticles].position.addInPlace(barycenter);
  62039. this._index += shape.length;
  62040. idx++;
  62041. this.nbParticles++;
  62042. this._shapeCounter++;
  62043. f += size;
  62044. }
  62045. return this;
  62046. };
  62047. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  62048. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  62049. var index = 0;
  62050. var idx = 0;
  62051. for (var p = 0; p < this.particles.length; p++) {
  62052. this._particle = this.particles[p];
  62053. this._shape = this._particle._model._shape;
  62054. if (this._particle.rotationQuaternion) {
  62055. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  62056. }
  62057. else {
  62058. this._yaw = this._particle.rotation.y;
  62059. this._pitch = this._particle.rotation.x;
  62060. this._roll = this._particle.rotation.z;
  62061. this._quaternionRotationYPR();
  62062. }
  62063. this._quaternionToRotationMatrix();
  62064. this._rotMatrix.invertToRef(this._invertMatrix);
  62065. for (var pt = 0; pt < this._shape.length; pt++) {
  62066. idx = index + pt * 3;
  62067. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  62068. this._fixedNormal32[idx] = this._normal.x;
  62069. this._fixedNormal32[idx + 1] = this._normal.y;
  62070. this._fixedNormal32[idx + 2] = this._normal.z;
  62071. }
  62072. index = idx + 3;
  62073. }
  62074. };
  62075. //reset copy
  62076. SolidParticleSystem.prototype._resetCopy = function () {
  62077. this._copy.position.x = 0;
  62078. this._copy.position.y = 0;
  62079. this._copy.position.z = 0;
  62080. this._copy.rotation.x = 0;
  62081. this._copy.rotation.y = 0;
  62082. this._copy.rotation.z = 0;
  62083. this._copy.rotationQuaternion = null;
  62084. this._copy.scaling.x = 1.0;
  62085. this._copy.scaling.y = 1.0;
  62086. this._copy.scaling.z = 1.0;
  62087. this._copy.uvs.x = 0;
  62088. this._copy.uvs.y = 0;
  62089. this._copy.uvs.z = 1.0;
  62090. this._copy.uvs.w = 1.0;
  62091. this._copy.color = null;
  62092. this._copy.translateFromPivot = false;
  62093. };
  62094. // _meshBuilder : inserts the shape model in the global SPS mesh
  62095. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  62096. var i;
  62097. var u = 0;
  62098. var c = 0;
  62099. var n = 0;
  62100. this._resetCopy();
  62101. if (options && options.positionFunction) { // call to custom positionFunction
  62102. options.positionFunction(this._copy, idx, idxInShape);
  62103. this._mustUnrotateFixedNormals = true;
  62104. }
  62105. if (this._copy.rotationQuaternion) {
  62106. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  62107. }
  62108. else {
  62109. this._yaw = this._copy.rotation.y;
  62110. this._pitch = this._copy.rotation.x;
  62111. this._roll = this._copy.rotation.z;
  62112. this._quaternionRotationYPR();
  62113. }
  62114. this._quaternionToRotationMatrix();
  62115. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  62116. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  62117. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  62118. if (this._copy.translateFromPivot) {
  62119. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  62120. }
  62121. else {
  62122. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  62123. }
  62124. for (i = 0; i < shape.length; i++) {
  62125. this._vertex.x = shape[i].x;
  62126. this._vertex.y = shape[i].y;
  62127. this._vertex.z = shape[i].z;
  62128. if (options && options.vertexFunction) {
  62129. options.vertexFunction(this._copy, this._vertex, i);
  62130. }
  62131. this._vertex.x *= this._copy.scaling.x;
  62132. this._vertex.y *= this._copy.scaling.y;
  62133. this._vertex.z *= this._copy.scaling.z;
  62134. this._vertex.x -= this._scaledPivot.x;
  62135. this._vertex.y -= this._scaledPivot.y;
  62136. this._vertex.z -= this._scaledPivot.z;
  62137. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  62138. this._rotated.addInPlace(this._pivotBackTranslation);
  62139. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  62140. if (meshUV) {
  62141. 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);
  62142. u += 2;
  62143. }
  62144. if (this._copy.color) {
  62145. this._color = this._copy.color;
  62146. }
  62147. else if (meshCol && meshCol[c] !== undefined) {
  62148. this._color.r = meshCol[c];
  62149. this._color.g = meshCol[c + 1];
  62150. this._color.b = meshCol[c + 2];
  62151. this._color.a = meshCol[c + 3];
  62152. }
  62153. else {
  62154. this._color.r = 1.0;
  62155. this._color.g = 1.0;
  62156. this._color.b = 1.0;
  62157. this._color.a = 1.0;
  62158. }
  62159. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  62160. c += 4;
  62161. if (!this.recomputeNormals && meshNor) {
  62162. this._normal.x = meshNor[n];
  62163. this._normal.y = meshNor[n + 1];
  62164. this._normal.z = meshNor[n + 2];
  62165. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  62166. normals.push(this._normal.x, this._normal.y, this._normal.z);
  62167. n += 3;
  62168. }
  62169. }
  62170. for (i = 0; i < meshInd.length; i++) {
  62171. var current_ind = p + meshInd[i];
  62172. indices.push(current_ind);
  62173. if (current_ind > 65535) {
  62174. this._needs32Bits = true;
  62175. }
  62176. }
  62177. if (this._pickable) {
  62178. var nbfaces = meshInd.length / 3;
  62179. for (i = 0; i < nbfaces; i++) {
  62180. this.pickedParticles.push({ idx: idx, faceId: i });
  62181. }
  62182. }
  62183. if (this._depthSort) {
  62184. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  62185. }
  62186. return this._copy;
  62187. };
  62188. // returns a shape array from positions array
  62189. SolidParticleSystem.prototype._posToShape = function (positions) {
  62190. var shape = [];
  62191. for (var i = 0; i < positions.length; i += 3) {
  62192. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  62193. }
  62194. return shape;
  62195. };
  62196. // returns a shapeUV array from a Vector4 uvs
  62197. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  62198. var shapeUV = [];
  62199. if (uvs) {
  62200. for (var i = 0; i < uvs.length; i++)
  62201. shapeUV.push(uvs[i]);
  62202. }
  62203. return shapeUV;
  62204. };
  62205. // adds a new particle object in the particles array
  62206. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  62207. if (bInfo === void 0) { bInfo = null; }
  62208. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  62209. this.particles.push(sp);
  62210. return sp;
  62211. };
  62212. /**
  62213. * Adds some particles to the SPS from the model shape. Returns the shape id.
  62214. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  62215. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  62216. * @param nb (positive integer) the number of particles to be created from this model
  62217. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  62218. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  62219. * @returns the number of shapes in the system
  62220. */
  62221. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  62222. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  62223. var meshInd = mesh.getIndices();
  62224. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  62225. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  62226. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  62227. var bbInfo;
  62228. if (this._particlesIntersect) {
  62229. bbInfo = mesh.getBoundingInfo();
  62230. }
  62231. var shape = this._posToShape(meshPos);
  62232. var shapeUV = this._uvsToShapeUV(meshUV);
  62233. var posfunc = options ? options.positionFunction : null;
  62234. var vtxfunc = options ? options.vertexFunction : null;
  62235. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  62236. // particles
  62237. var sp;
  62238. var currentCopy;
  62239. var idx = this.nbParticles;
  62240. for (var i = 0; i < nb; i++) {
  62241. var currentPos = this._positions.length;
  62242. var currentInd = this._indices.length;
  62243. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  62244. if (this._updatable) {
  62245. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  62246. sp.position.copyFrom(currentCopy.position);
  62247. sp.rotation.copyFrom(currentCopy.rotation);
  62248. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  62249. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  62250. }
  62251. if (currentCopy.color && sp.color) {
  62252. sp.color.copyFrom(currentCopy.color);
  62253. }
  62254. sp.scaling.copyFrom(currentCopy.scaling);
  62255. sp.uvs.copyFrom(currentCopy.uvs);
  62256. }
  62257. this._index += shape.length;
  62258. idx++;
  62259. }
  62260. this.nbParticles += nb;
  62261. this._shapeCounter++;
  62262. return this._shapeCounter - 1;
  62263. };
  62264. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  62265. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  62266. this._resetCopy();
  62267. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  62268. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  62269. }
  62270. if (this._copy.rotationQuaternion) {
  62271. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  62272. }
  62273. else {
  62274. this._yaw = this._copy.rotation.y;
  62275. this._pitch = this._copy.rotation.x;
  62276. this._roll = this._copy.rotation.z;
  62277. this._quaternionRotationYPR();
  62278. }
  62279. this._quaternionToRotationMatrix();
  62280. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  62281. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  62282. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  62283. if (this._copy.translateFromPivot) {
  62284. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  62285. }
  62286. else {
  62287. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  62288. }
  62289. this._shape = particle._model._shape;
  62290. for (var pt = 0; pt < this._shape.length; pt++) {
  62291. this._vertex.x = this._shape[pt].x;
  62292. this._vertex.y = this._shape[pt].y;
  62293. this._vertex.z = this._shape[pt].z;
  62294. if (particle._model._vertexFunction) {
  62295. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  62296. }
  62297. this._vertex.x *= this._copy.scaling.x;
  62298. this._vertex.y *= this._copy.scaling.y;
  62299. this._vertex.z *= this._copy.scaling.z;
  62300. this._vertex.x -= this._scaledPivot.x;
  62301. this._vertex.y -= this._scaledPivot.y;
  62302. this._vertex.z -= this._scaledPivot.z;
  62303. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  62304. this._rotated.addInPlace(this._pivotBackTranslation);
  62305. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  62306. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  62307. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  62308. }
  62309. particle.position.x = 0.0;
  62310. particle.position.y = 0.0;
  62311. particle.position.z = 0.0;
  62312. particle.rotation.x = 0.0;
  62313. particle.rotation.y = 0.0;
  62314. particle.rotation.z = 0.0;
  62315. particle.rotationQuaternion = null;
  62316. particle.scaling.x = 1.0;
  62317. particle.scaling.y = 1.0;
  62318. particle.scaling.z = 1.0;
  62319. particle.uvs.x = 0.0;
  62320. particle.uvs.y = 0.0;
  62321. particle.uvs.z = 1.0;
  62322. particle.uvs.w = 1.0;
  62323. particle.pivot.x = 0.0;
  62324. particle.pivot.y = 0.0;
  62325. particle.pivot.z = 0.0;
  62326. particle.translateFromPivot = false;
  62327. particle.parentId = null;
  62328. };
  62329. /**
  62330. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  62331. * @returns the SPS.
  62332. */
  62333. SolidParticleSystem.prototype.rebuildMesh = function () {
  62334. for (var p = 0; p < this.particles.length; p++) {
  62335. this._rebuildParticle(this.particles[p]);
  62336. }
  62337. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  62338. return this;
  62339. };
  62340. /**
  62341. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  62342. * This method calls `updateParticle()` for each particle of the SPS.
  62343. * For an animated SPS, it is usually called within the render loop.
  62344. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  62345. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  62346. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  62347. * @returns the SPS.
  62348. */
  62349. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  62350. if (start === void 0) { start = 0; }
  62351. if (end === void 0) { end = this.nbParticles - 1; }
  62352. if (update === void 0) { update = true; }
  62353. if (!this._updatable) {
  62354. return this;
  62355. }
  62356. // custom beforeUpdate
  62357. this.beforeUpdateParticles(start, end, update);
  62358. this._cam_axisX.x = 1.0;
  62359. this._cam_axisX.y = 0.0;
  62360. this._cam_axisX.z = 0.0;
  62361. this._cam_axisY.x = 0.0;
  62362. this._cam_axisY.y = 1.0;
  62363. this._cam_axisY.z = 0.0;
  62364. this._cam_axisZ.x = 0.0;
  62365. this._cam_axisZ.y = 0.0;
  62366. this._cam_axisZ.z = 1.0;
  62367. // cases when the World Matrix is to be computed first
  62368. if (this.billboard || this._depthSort) {
  62369. this.mesh.computeWorldMatrix(true);
  62370. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  62371. }
  62372. // if the particles will always face the camera
  62373. if (this.billboard) {
  62374. // compute the camera position and un-rotate it by the current mesh rotation
  62375. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  62376. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  62377. this._cam_axisZ.normalize();
  62378. // same for camera up vector extracted from the cam view matrix
  62379. var view = this._camera.getViewMatrix(true);
  62380. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  62381. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  62382. this._cam_axisY.normalize();
  62383. this._cam_axisX.normalize();
  62384. }
  62385. // if depthSort, compute the camera global position in the mesh local system
  62386. if (this._depthSort) {
  62387. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  62388. }
  62389. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  62390. var idx = 0; // current position index in the global array positions32
  62391. var index = 0; // position start index in the global array positions32 of the current particle
  62392. var colidx = 0; // current color index in the global array colors32
  62393. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  62394. var uvidx = 0; // current uv index in the global array uvs32
  62395. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  62396. var pt = 0; // current index in the particle model shape
  62397. if (this.mesh.isFacetDataEnabled) {
  62398. this._computeBoundingBox = true;
  62399. }
  62400. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  62401. if (this._computeBoundingBox) {
  62402. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  62403. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  62404. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  62405. }
  62406. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  62407. if (this.mesh._boundingInfo) {
  62408. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  62409. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  62410. }
  62411. }
  62412. }
  62413. // particle loop
  62414. index = this.particles[start]._pos;
  62415. var vpos = (index / 3) | 0;
  62416. colorIndex = vpos * 4;
  62417. uvIndex = vpos * 2;
  62418. for (var p = start; p <= end; p++) {
  62419. this._particle = this.particles[p];
  62420. this._shape = this._particle._model._shape;
  62421. this._shapeUV = this._particle._model._shapeUV;
  62422. // call to custom user function to update the particle properties
  62423. this.updateParticle(this._particle);
  62424. // camera-particle distance for depth sorting
  62425. if (this._depthSort && this._depthSortParticles) {
  62426. var dsp = this.depthSortedParticles[p];
  62427. dsp.ind = this._particle._ind;
  62428. dsp.indicesLength = this._particle._model._indicesLength;
  62429. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  62430. }
  62431. // skip the computations for inactive or already invisible particles
  62432. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  62433. // increment indexes for the next particle
  62434. pt = this._shape.length;
  62435. index += pt * 3;
  62436. colorIndex += pt * 4;
  62437. uvIndex += pt * 2;
  62438. continue;
  62439. }
  62440. if (this._particle.isVisible) {
  62441. this._particle._stillInvisible = false; // un-mark permanent invisibility
  62442. this._particleHasParent = (this._particle.parentId !== null);
  62443. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  62444. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  62445. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  62446. // particle rotation matrix
  62447. if (this.billboard) {
  62448. this._particle.rotation.x = 0.0;
  62449. this._particle.rotation.y = 0.0;
  62450. }
  62451. if (this._computeParticleRotation || this.billboard) {
  62452. if (this._particle.rotationQuaternion) {
  62453. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  62454. }
  62455. else {
  62456. this._yaw = this._particle.rotation.y;
  62457. this._pitch = this._particle.rotation.x;
  62458. this._roll = this._particle.rotation.z;
  62459. this._quaternionRotationYPR();
  62460. }
  62461. this._quaternionToRotationMatrix();
  62462. }
  62463. if (this._particleHasParent) {
  62464. this._parent = this.particles[this._particle.parentId];
  62465. 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];
  62466. 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];
  62467. 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];
  62468. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  62469. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  62470. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  62471. if (this._computeParticleRotation || this.billboard) {
  62472. 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];
  62473. 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];
  62474. 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];
  62475. 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];
  62476. 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];
  62477. 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];
  62478. 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];
  62479. 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];
  62480. 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];
  62481. }
  62482. }
  62483. else {
  62484. this._particle._globalPosition.x = this._particle.position.x;
  62485. this._particle._globalPosition.y = this._particle.position.y;
  62486. this._particle._globalPosition.z = this._particle.position.z;
  62487. if (this._computeParticleRotation || this.billboard) {
  62488. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  62489. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  62490. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  62491. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  62492. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  62493. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  62494. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  62495. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  62496. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  62497. }
  62498. }
  62499. if (this._particle.translateFromPivot) {
  62500. this._pivotBackTranslation.x = 0.0;
  62501. this._pivotBackTranslation.y = 0.0;
  62502. this._pivotBackTranslation.z = 0.0;
  62503. }
  62504. else {
  62505. this._pivotBackTranslation.x = this._scaledPivot.x;
  62506. this._pivotBackTranslation.y = this._scaledPivot.y;
  62507. this._pivotBackTranslation.z = this._scaledPivot.z;
  62508. }
  62509. // particle vertex loop
  62510. for (pt = 0; pt < this._shape.length; pt++) {
  62511. idx = index + pt * 3;
  62512. colidx = colorIndex + pt * 4;
  62513. uvidx = uvIndex + pt * 2;
  62514. this._vertex.x = this._shape[pt].x;
  62515. this._vertex.y = this._shape[pt].y;
  62516. this._vertex.z = this._shape[pt].z;
  62517. if (this._computeParticleVertex) {
  62518. this.updateParticleVertex(this._particle, this._vertex, pt);
  62519. }
  62520. // positions
  62521. this._vertex.x *= this._particle.scaling.x;
  62522. this._vertex.y *= this._particle.scaling.y;
  62523. this._vertex.z *= this._particle.scaling.z;
  62524. this._vertex.x -= this._scaledPivot.x;
  62525. this._vertex.y -= this._scaledPivot.y;
  62526. this._vertex.z -= this._scaledPivot.z;
  62527. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  62528. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  62529. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  62530. this._rotated.x += this._pivotBackTranslation.x;
  62531. this._rotated.y += this._pivotBackTranslation.y;
  62532. this._rotated.z += this._pivotBackTranslation.z;
  62533. 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;
  62534. 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;
  62535. 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;
  62536. if (this._computeBoundingBox) {
  62537. if (this._positions32[idx] < this._minimum.x) {
  62538. this._minimum.x = this._positions32[idx];
  62539. }
  62540. if (this._positions32[idx] > this._maximum.x) {
  62541. this._maximum.x = this._positions32[idx];
  62542. }
  62543. if (this._positions32[idx + 1] < this._minimum.y) {
  62544. this._minimum.y = this._positions32[idx + 1];
  62545. }
  62546. if (this._positions32[idx + 1] > this._maximum.y) {
  62547. this._maximum.y = this._positions32[idx + 1];
  62548. }
  62549. if (this._positions32[idx + 2] < this._minimum.z) {
  62550. this._minimum.z = this._positions32[idx + 2];
  62551. }
  62552. if (this._positions32[idx + 2] > this._maximum.z) {
  62553. this._maximum.z = this._positions32[idx + 2];
  62554. }
  62555. }
  62556. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  62557. if (!this._computeParticleVertex) {
  62558. this._normal.x = this._fixedNormal32[idx];
  62559. this._normal.y = this._fixedNormal32[idx + 1];
  62560. this._normal.z = this._fixedNormal32[idx + 2];
  62561. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  62562. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  62563. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  62564. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  62565. 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;
  62566. 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;
  62567. }
  62568. if (this._computeParticleColor && this._particle.color) {
  62569. this._colors32[colidx] = this._particle.color.r;
  62570. this._colors32[colidx + 1] = this._particle.color.g;
  62571. this._colors32[colidx + 2] = this._particle.color.b;
  62572. this._colors32[colidx + 3] = this._particle.color.a;
  62573. }
  62574. if (this._computeParticleTexture) {
  62575. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  62576. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  62577. }
  62578. }
  62579. }
  62580. // particle just set invisible : scaled to zero and positioned at the origin
  62581. else {
  62582. this._particle._stillInvisible = true; // mark the particle as invisible
  62583. for (pt = 0; pt < this._shape.length; pt++) {
  62584. idx = index + pt * 3;
  62585. colidx = colorIndex + pt * 4;
  62586. uvidx = uvIndex + pt * 2;
  62587. this._positions32[idx] = 0.0;
  62588. this._positions32[idx + 1] = 0.0;
  62589. this._positions32[idx + 2] = 0.0;
  62590. this._normals32[idx] = 0.0;
  62591. this._normals32[idx + 1] = 0.0;
  62592. this._normals32[idx + 2] = 0.0;
  62593. if (this._computeParticleColor && this._particle.color) {
  62594. this._colors32[colidx] = this._particle.color.r;
  62595. this._colors32[colidx + 1] = this._particle.color.g;
  62596. this._colors32[colidx + 2] = this._particle.color.b;
  62597. this._colors32[colidx + 3] = this._particle.color.a;
  62598. }
  62599. if (this._computeParticleTexture) {
  62600. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  62601. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  62602. }
  62603. }
  62604. }
  62605. // if the particle intersections must be computed : update the bbInfo
  62606. if (this._particlesIntersect) {
  62607. var bInfo = this._particle._boundingInfo;
  62608. var bBox = bInfo.boundingBox;
  62609. var bSphere = bInfo.boundingSphere;
  62610. if (!this._bSphereOnly) {
  62611. // place, scale and rotate the particle bbox within the SPS local system, then update it
  62612. for (var b = 0; b < bBox.vectors.length; b++) {
  62613. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  62614. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  62615. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  62616. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  62617. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  62618. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  62619. 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;
  62620. 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;
  62621. 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;
  62622. }
  62623. bBox._update(this.mesh._worldMatrix);
  62624. }
  62625. // place and scale the particle bouding sphere in the SPS local system, then update it
  62626. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  62627. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  62628. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  62629. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  62630. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  62631. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  62632. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  62633. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  62634. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  62635. 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));
  62636. bSphere._update(this.mesh._worldMatrix);
  62637. }
  62638. // increment indexes for the next particle
  62639. index = idx + 3;
  62640. colorIndex = colidx + 4;
  62641. uvIndex = uvidx + 2;
  62642. }
  62643. // if the VBO must be updated
  62644. if (update) {
  62645. if (this._computeParticleColor) {
  62646. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  62647. }
  62648. if (this._computeParticleTexture) {
  62649. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  62650. }
  62651. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  62652. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  62653. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  62654. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  62655. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  62656. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  62657. for (var i = 0; i < this._normals32.length; i++) {
  62658. this._fixedNormal32[i] = this._normals32[i];
  62659. }
  62660. }
  62661. if (!this.mesh.areNormalsFrozen) {
  62662. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  62663. }
  62664. }
  62665. if (this._depthSort && this._depthSortParticles) {
  62666. this.depthSortedParticles.sort(this._depthSortFunction);
  62667. var dspl = this.depthSortedParticles.length;
  62668. var sorted = 0;
  62669. var lind = 0;
  62670. var sind = 0;
  62671. var sid = 0;
  62672. for (sorted = 0; sorted < dspl; sorted++) {
  62673. lind = this.depthSortedParticles[sorted].indicesLength;
  62674. sind = this.depthSortedParticles[sorted].ind;
  62675. for (var i = 0; i < lind; i++) {
  62676. this._indices32[sid] = this._indices[sind + i];
  62677. sid++;
  62678. }
  62679. }
  62680. this.mesh.updateIndices(this._indices32);
  62681. }
  62682. }
  62683. if (this._computeBoundingBox) {
  62684. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  62685. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  62686. }
  62687. this.afterUpdateParticles(start, end, update);
  62688. return this;
  62689. };
  62690. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  62691. this._halfroll = this._roll * 0.5;
  62692. this._halfpitch = this._pitch * 0.5;
  62693. this._halfyaw = this._yaw * 0.5;
  62694. this._sinRoll = Math.sin(this._halfroll);
  62695. this._cosRoll = Math.cos(this._halfroll);
  62696. this._sinPitch = Math.sin(this._halfpitch);
  62697. this._cosPitch = Math.cos(this._halfpitch);
  62698. this._sinYaw = Math.sin(this._halfyaw);
  62699. this._cosYaw = Math.cos(this._halfyaw);
  62700. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  62701. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  62702. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  62703. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  62704. };
  62705. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  62706. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  62707. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  62708. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  62709. this._rotMatrix.m[3] = 0;
  62710. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  62711. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  62712. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  62713. this._rotMatrix.m[7] = 0;
  62714. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  62715. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  62716. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  62717. this._rotMatrix.m[11] = 0;
  62718. this._rotMatrix.m[12] = 0;
  62719. this._rotMatrix.m[13] = 0;
  62720. this._rotMatrix.m[14] = 0;
  62721. this._rotMatrix.m[15] = 1.0;
  62722. };
  62723. /**
  62724. * Disposes the SPS.
  62725. */
  62726. SolidParticleSystem.prototype.dispose = function () {
  62727. this.mesh.dispose();
  62728. this.vars = null;
  62729. // drop references to internal big arrays for the GC
  62730. this._positions = null;
  62731. this._indices = null;
  62732. this._normals = null;
  62733. this._uvs = null;
  62734. this._colors = null;
  62735. this._indices32 = null;
  62736. this._positions32 = null;
  62737. this._normals32 = null;
  62738. this._fixedNormal32 = null;
  62739. this._uvs32 = null;
  62740. this._colors32 = null;
  62741. this.pickedParticles = null;
  62742. };
  62743. /**
  62744. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  62745. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62746. * @returns the SPS.
  62747. */
  62748. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  62749. if (!this._isVisibilityBoxLocked) {
  62750. this.mesh.refreshBoundingInfo();
  62751. }
  62752. return this;
  62753. };
  62754. /**
  62755. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  62756. * @param size the size (float) of the visibility box
  62757. * note : this doesn't lock the SPS mesh bounding box.
  62758. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62759. */
  62760. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  62761. var vis = size / 2;
  62762. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  62763. };
  62764. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  62765. /**
  62766. * Gets whether the SPS as always visible or not
  62767. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62768. */
  62769. get: function () {
  62770. return this._alwaysVisible;
  62771. },
  62772. /**
  62773. * Sets the SPS as always visible or not
  62774. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62775. */
  62776. set: function (val) {
  62777. this._alwaysVisible = val;
  62778. this.mesh.alwaysSelectAsActiveMesh = val;
  62779. },
  62780. enumerable: true,
  62781. configurable: true
  62782. });
  62783. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  62784. /**
  62785. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  62786. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62787. */
  62788. get: function () {
  62789. return this._isVisibilityBoxLocked;
  62790. },
  62791. /**
  62792. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  62793. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  62794. */
  62795. set: function (val) {
  62796. this._isVisibilityBoxLocked = val;
  62797. var boundingInfo = this.mesh.getBoundingInfo();
  62798. boundingInfo.isLocked = val;
  62799. },
  62800. enumerable: true,
  62801. configurable: true
  62802. });
  62803. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  62804. /**
  62805. * Gets if `setParticles()` computes the particle rotations or not.
  62806. * Default value : true. The SPS is faster when it's set to false.
  62807. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  62808. */
  62809. get: function () {
  62810. return this._computeParticleRotation;
  62811. },
  62812. /**
  62813. * Tells to `setParticles()` to compute the particle rotations or not.
  62814. * Default value : true. The SPS is faster when it's set to false.
  62815. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  62816. */
  62817. set: function (val) {
  62818. this._computeParticleRotation = val;
  62819. },
  62820. enumerable: true,
  62821. configurable: true
  62822. });
  62823. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  62824. /**
  62825. * Gets if `setParticles()` computes the particle colors or not.
  62826. * Default value : true. The SPS is faster when it's set to false.
  62827. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  62828. */
  62829. get: function () {
  62830. return this._computeParticleColor;
  62831. },
  62832. /**
  62833. * Tells to `setParticles()` to compute the particle colors or not.
  62834. * Default value : true. The SPS is faster when it's set to false.
  62835. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  62836. */
  62837. set: function (val) {
  62838. this._computeParticleColor = val;
  62839. },
  62840. enumerable: true,
  62841. configurable: true
  62842. });
  62843. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  62844. /**
  62845. * Gets if `setParticles()` computes the particle textures or not.
  62846. * Default value : true. The SPS is faster when it's set to false.
  62847. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  62848. */
  62849. get: function () {
  62850. return this._computeParticleTexture;
  62851. },
  62852. set: function (val) {
  62853. this._computeParticleTexture = val;
  62854. },
  62855. enumerable: true,
  62856. configurable: true
  62857. });
  62858. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  62859. /**
  62860. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  62861. * Default value : false. The SPS is faster when it's set to false.
  62862. * Note : the particle custom vertex positions aren't stored values.
  62863. */
  62864. get: function () {
  62865. return this._computeParticleVertex;
  62866. },
  62867. /**
  62868. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  62869. * Default value : false. The SPS is faster when it's set to false.
  62870. * Note : the particle custom vertex positions aren't stored values.
  62871. */
  62872. set: function (val) {
  62873. this._computeParticleVertex = val;
  62874. },
  62875. enumerable: true,
  62876. configurable: true
  62877. });
  62878. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  62879. /**
  62880. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  62881. */
  62882. get: function () {
  62883. return this._computeBoundingBox;
  62884. },
  62885. /**
  62886. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  62887. */
  62888. set: function (val) {
  62889. this._computeBoundingBox = val;
  62890. },
  62891. enumerable: true,
  62892. configurable: true
  62893. });
  62894. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  62895. /**
  62896. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  62897. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  62898. * Default : `true`
  62899. */
  62900. get: function () {
  62901. return this._depthSortParticles;
  62902. },
  62903. /**
  62904. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  62905. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  62906. * Default : `true`
  62907. */
  62908. set: function (val) {
  62909. this._depthSortParticles = val;
  62910. },
  62911. enumerable: true,
  62912. configurable: true
  62913. });
  62914. // =======================================================================
  62915. // Particle behavior logic
  62916. // these following methods may be overwritten by the user to fit his needs
  62917. /**
  62918. * This function does nothing. It may be overwritten to set all the particle first values.
  62919. * The SPS doesn't call this function, you may have to call it by your own.
  62920. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  62921. */
  62922. SolidParticleSystem.prototype.initParticles = function () {
  62923. };
  62924. /**
  62925. * This function does nothing. It may be overwritten to recycle a particle.
  62926. * The SPS doesn't call this function, you may have to call it by your own.
  62927. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  62928. * @param particle The particle to recycle
  62929. * @returns the recycled particle
  62930. */
  62931. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  62932. return particle;
  62933. };
  62934. /**
  62935. * Updates a particle : this function should be overwritten by the user.
  62936. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  62937. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  62938. * @example : just set a particle position or velocity and recycle conditions
  62939. * @param particle The particle to update
  62940. * @returns the updated particle
  62941. */
  62942. SolidParticleSystem.prototype.updateParticle = function (particle) {
  62943. return particle;
  62944. };
  62945. /**
  62946. * Updates a vertex of a particle : it can be overwritten by the user.
  62947. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  62948. * @param particle the current particle
  62949. * @param vertex the current index of the current particle
  62950. * @param pt the index of the current vertex in the particle shape
  62951. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  62952. * @example : just set a vertex particle position
  62953. * @returns the updated vertex
  62954. */
  62955. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  62956. return vertex;
  62957. };
  62958. /**
  62959. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  62960. * This does nothing and may be overwritten by the user.
  62961. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  62962. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  62963. * @param update the boolean update value actually passed to setParticles()
  62964. */
  62965. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  62966. };
  62967. /**
  62968. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  62969. * This will be passed three parameters.
  62970. * This does nothing and may be overwritten by the user.
  62971. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  62972. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  62973. * @param update the boolean update value actually passed to setParticles()
  62974. */
  62975. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  62976. };
  62977. return SolidParticleSystem;
  62978. }());
  62979. BABYLON.SolidParticleSystem = SolidParticleSystem;
  62980. })(BABYLON || (BABYLON = {}));
  62981. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  62982. var BABYLON;
  62983. (function (BABYLON) {
  62984. /**
  62985. * Class containing static functions to help procedurally build meshes
  62986. */
  62987. var MeshBuilder = /** @class */ (function () {
  62988. function MeshBuilder() {
  62989. }
  62990. MeshBuilder.updateSideOrientation = function (orientation) {
  62991. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  62992. return BABYLON.Mesh.DOUBLESIDE;
  62993. }
  62994. if (orientation === undefined || orientation === null) {
  62995. return BABYLON.Mesh.FRONTSIDE;
  62996. }
  62997. return orientation;
  62998. };
  62999. /**
  63000. * Creates a box mesh
  63001. * * The parameter `size` sets the size (float) of each box side (default 1)
  63002. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  63003. * * 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)
  63004. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  63005. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63006. * * 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
  63007. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63008. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  63009. * @param name defines the name of the mesh
  63010. * @param options defines the options used to create the mesh
  63011. * @param scene defines the hosting scene
  63012. * @returns the box mesh
  63013. */
  63014. MeshBuilder.CreateBox = function (name, options, scene) {
  63015. if (scene === void 0) { scene = null; }
  63016. var box = new BABYLON.Mesh(name, scene);
  63017. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63018. box._originalBuilderSideOrientation = options.sideOrientation;
  63019. var vertexData = BABYLON.VertexData.CreateBox(options);
  63020. vertexData.applyToMesh(box, options.updatable);
  63021. return box;
  63022. };
  63023. /**
  63024. * Creates a sphere mesh
  63025. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  63026. * * 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`)
  63027. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  63028. * * 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
  63029. * * 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)
  63030. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63031. * * 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
  63032. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63033. * @param name defines the name of the mesh
  63034. * @param options defines the options used to create the mesh
  63035. * @param scene defines the hosting scene
  63036. * @returns the sphere mesh
  63037. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  63038. */
  63039. MeshBuilder.CreateSphere = function (name, options, scene) {
  63040. var sphere = new BABYLON.Mesh(name, scene);
  63041. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63042. sphere._originalBuilderSideOrientation = options.sideOrientation;
  63043. var vertexData = BABYLON.VertexData.CreateSphere(options);
  63044. vertexData.applyToMesh(sphere, options.updatable);
  63045. return sphere;
  63046. };
  63047. /**
  63048. * Creates a plane polygonal mesh. By default, this is a disc
  63049. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  63050. * * 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
  63051. * * 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
  63052. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63053. * * 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
  63054. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63055. * @param name defines the name of the mesh
  63056. * @param options defines the options used to create the mesh
  63057. * @param scene defines the hosting scene
  63058. * @returns the plane polygonal mesh
  63059. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  63060. */
  63061. MeshBuilder.CreateDisc = function (name, options, scene) {
  63062. if (scene === void 0) { scene = null; }
  63063. var disc = new BABYLON.Mesh(name, scene);
  63064. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63065. disc._originalBuilderSideOrientation = options.sideOrientation;
  63066. var vertexData = BABYLON.VertexData.CreateDisc(options);
  63067. vertexData.applyToMesh(disc, options.updatable);
  63068. return disc;
  63069. };
  63070. /**
  63071. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  63072. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  63073. * * 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`)
  63074. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  63075. * * 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
  63076. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63077. * * 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
  63078. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63079. * @param name defines the name of the mesh
  63080. * @param options defines the options used to create the mesh
  63081. * @param scene defines the hosting scene
  63082. * @returns the icosahedron mesh
  63083. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  63084. */
  63085. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  63086. var sphere = new BABYLON.Mesh(name, scene);
  63087. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63088. sphere._originalBuilderSideOrientation = options.sideOrientation;
  63089. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  63090. vertexData.applyToMesh(sphere, options.updatable);
  63091. return sphere;
  63092. };
  63093. ;
  63094. /**
  63095. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  63096. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  63097. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  63098. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  63099. * * 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
  63100. * * 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
  63101. * * 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
  63102. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63103. * * 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
  63104. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  63105. * * 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
  63106. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  63107. * * 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
  63108. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  63109. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63110. * @param name defines the name of the mesh
  63111. * @param options defines the options used to create the mesh
  63112. * @param scene defines the hosting scene
  63113. * @returns the ribbon mesh
  63114. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  63115. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  63116. */
  63117. MeshBuilder.CreateRibbon = function (name, options, scene) {
  63118. if (scene === void 0) { scene = null; }
  63119. var pathArray = options.pathArray;
  63120. var closeArray = options.closeArray;
  63121. var closePath = options.closePath;
  63122. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63123. var instance = options.instance;
  63124. var updatable = options.updatable;
  63125. if (instance) { // existing ribbon instance update
  63126. // positionFunction : ribbon case
  63127. // only pathArray and sideOrientation parameters are taken into account for positions update
  63128. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  63129. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  63130. var positionFunction = function (positions) {
  63131. var minlg = pathArray[0].length;
  63132. var i = 0;
  63133. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  63134. for (var si = 1; si <= ns; si++) {
  63135. for (var p = 0; p < pathArray.length; p++) {
  63136. var path = pathArray[p];
  63137. var l = path.length;
  63138. minlg = (minlg < l) ? minlg : l;
  63139. var j = 0;
  63140. while (j < minlg) {
  63141. positions[i] = path[j].x;
  63142. positions[i + 1] = path[j].y;
  63143. positions[i + 2] = path[j].z;
  63144. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  63145. BABYLON.Tmp.Vector3[0].x = path[j].x;
  63146. }
  63147. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  63148. BABYLON.Tmp.Vector3[1].x = path[j].x;
  63149. }
  63150. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  63151. BABYLON.Tmp.Vector3[0].y = path[j].y;
  63152. }
  63153. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  63154. BABYLON.Tmp.Vector3[1].y = path[j].y;
  63155. }
  63156. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  63157. BABYLON.Tmp.Vector3[0].z = path[j].z;
  63158. }
  63159. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  63160. BABYLON.Tmp.Vector3[1].z = path[j].z;
  63161. }
  63162. j++;
  63163. i += 3;
  63164. }
  63165. if (instance._closePath) {
  63166. positions[i] = path[0].x;
  63167. positions[i + 1] = path[0].y;
  63168. positions[i + 2] = path[0].z;
  63169. i += 3;
  63170. }
  63171. }
  63172. }
  63173. };
  63174. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63175. positionFunction(positions);
  63176. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  63177. instance._boundingInfo.update(instance._worldMatrix);
  63178. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  63179. if (options.colors) {
  63180. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  63181. for (var c = 0; c < options.colors.length; c++) {
  63182. colors[c * 4] = options.colors[c].r;
  63183. colors[c * 4 + 1] = options.colors[c].g;
  63184. colors[c * 4 + 2] = options.colors[c].b;
  63185. colors[c * 4 + 3] = options.colors[c].a;
  63186. }
  63187. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  63188. }
  63189. if (options.uvs) {
  63190. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  63191. for (var i = 0; i < options.uvs.length; i++) {
  63192. uvs[i * 2] = options.uvs[i].x;
  63193. uvs[i * 2 + 1] = options.uvs[i].y;
  63194. }
  63195. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  63196. }
  63197. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  63198. var indices = instance.getIndices();
  63199. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  63200. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  63201. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  63202. if (instance._closePath) {
  63203. var indexFirst = 0;
  63204. var indexLast = 0;
  63205. for (var p = 0; p < pathArray.length; p++) {
  63206. indexFirst = instance._idx[p] * 3;
  63207. if (p + 1 < pathArray.length) {
  63208. indexLast = (instance._idx[p + 1] - 1) * 3;
  63209. }
  63210. else {
  63211. indexLast = normals.length - 3;
  63212. }
  63213. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  63214. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  63215. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  63216. normals[indexLast] = normals[indexFirst];
  63217. normals[indexLast + 1] = normals[indexFirst + 1];
  63218. normals[indexLast + 2] = normals[indexFirst + 2];
  63219. }
  63220. }
  63221. if (!(instance.areNormalsFrozen)) {
  63222. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  63223. }
  63224. }
  63225. return instance;
  63226. }
  63227. else { // new ribbon creation
  63228. var ribbon = new BABYLON.Mesh(name, scene);
  63229. ribbon._originalBuilderSideOrientation = sideOrientation;
  63230. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  63231. if (closePath) {
  63232. ribbon._idx = vertexData._idx;
  63233. }
  63234. ribbon._closePath = closePath;
  63235. ribbon._closeArray = closeArray;
  63236. vertexData.applyToMesh(ribbon, updatable);
  63237. return ribbon;
  63238. }
  63239. };
  63240. /**
  63241. * Creates a cylinder or a cone mesh
  63242. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  63243. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  63244. * * 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.
  63245. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  63246. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  63247. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  63248. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  63249. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  63250. * * 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).
  63251. * * 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
  63252. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  63253. * * 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
  63254. * * 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.
  63255. * * If `enclose` is false, a ring surface is one element.
  63256. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  63257. * * 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
  63258. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63259. * * 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
  63260. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63261. * @param name defines the name of the mesh
  63262. * @param options defines the options used to create the mesh
  63263. * @param scene defines the hosting scene
  63264. * @returns the cylinder mesh
  63265. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  63266. */
  63267. MeshBuilder.CreateCylinder = function (name, options, scene) {
  63268. var cylinder = new BABYLON.Mesh(name, scene);
  63269. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63270. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  63271. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  63272. vertexData.applyToMesh(cylinder, options.updatable);
  63273. return cylinder;
  63274. };
  63275. /**
  63276. * Creates a torus mesh
  63277. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  63278. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  63279. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  63280. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63281. * * 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
  63282. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63283. * @param name defines the name of the mesh
  63284. * @param options defines the options used to create the mesh
  63285. * @param scene defines the hosting scene
  63286. * @returns the torus mesh
  63287. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  63288. */
  63289. MeshBuilder.CreateTorus = function (name, options, scene) {
  63290. var torus = new BABYLON.Mesh(name, scene);
  63291. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63292. torus._originalBuilderSideOrientation = options.sideOrientation;
  63293. var vertexData = BABYLON.VertexData.CreateTorus(options);
  63294. vertexData.applyToMesh(torus, options.updatable);
  63295. return torus;
  63296. };
  63297. /**
  63298. * Creates a torus knot mesh
  63299. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  63300. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  63301. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  63302. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  63303. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63304. * * 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
  63305. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63306. * @param name defines the name of the mesh
  63307. * @param options defines the options used to create the mesh
  63308. * @param scene defines the hosting scene
  63309. * @returns the torus knot mesh
  63310. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  63311. */
  63312. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  63313. var torusKnot = new BABYLON.Mesh(name, scene);
  63314. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63315. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  63316. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  63317. vertexData.applyToMesh(torusKnot, options.updatable);
  63318. return torusKnot;
  63319. };
  63320. /**
  63321. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  63322. * * 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
  63323. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  63324. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  63325. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  63326. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  63327. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  63328. * * 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
  63329. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  63330. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63331. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  63332. * @param name defines the name of the new line system
  63333. * @param options defines the options used to create the line system
  63334. * @param scene defines the hosting scene
  63335. * @returns a new line system mesh
  63336. */
  63337. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  63338. var instance = options.instance;
  63339. var lines = options.lines;
  63340. var colors = options.colors;
  63341. if (instance) { // lines update
  63342. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63343. var vertexColor;
  63344. var lineColors;
  63345. if (colors) {
  63346. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  63347. }
  63348. var i = 0;
  63349. var c = 0;
  63350. for (var l = 0; l < lines.length; l++) {
  63351. var points = lines[l];
  63352. for (var p = 0; p < points.length; p++) {
  63353. positions[i] = points[p].x;
  63354. positions[i + 1] = points[p].y;
  63355. positions[i + 2] = points[p].z;
  63356. if (colors && vertexColor) {
  63357. lineColors = colors[l];
  63358. vertexColor[c] = lineColors[p].r;
  63359. vertexColor[c + 1] = lineColors[p].g;
  63360. vertexColor[c + 2] = lineColors[p].b;
  63361. vertexColor[c + 3] = lineColors[p].a;
  63362. c += 4;
  63363. }
  63364. i += 3;
  63365. }
  63366. }
  63367. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  63368. if (colors && vertexColor) {
  63369. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  63370. }
  63371. return instance;
  63372. }
  63373. // line system creation
  63374. var useVertexColor = (colors) ? true : false;
  63375. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  63376. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  63377. vertexData.applyToMesh(lineSystem, options.updatable);
  63378. return lineSystem;
  63379. };
  63380. /**
  63381. * Creates a line mesh
  63382. * 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
  63383. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  63384. * * The parameter `points` is an array successive Vector3
  63385. * * 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
  63386. * * The optional parameter `colors` is an array of successive Color4, one per line point
  63387. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  63388. * * When updating an instance, remember that only point positions can change, not the number of points
  63389. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63390. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  63391. * @param name defines the name of the new line system
  63392. * @param options defines the options used to create the line system
  63393. * @param scene defines the hosting scene
  63394. * @returns a new line mesh
  63395. */
  63396. MeshBuilder.CreateLines = function (name, options, scene) {
  63397. if (scene === void 0) { scene = null; }
  63398. var colors = (options.colors) ? [options.colors] : null;
  63399. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  63400. return lines;
  63401. };
  63402. /**
  63403. * Creates a dashed line mesh
  63404. * * 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
  63405. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  63406. * * The parameter `points` is an array successive Vector3
  63407. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  63408. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  63409. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  63410. * * 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
  63411. * * When updating an instance, remember that only point positions can change, not the number of points
  63412. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63413. * @param name defines the name of the mesh
  63414. * @param options defines the options used to create the mesh
  63415. * @param scene defines the hosting scene
  63416. * @returns the dashed line mesh
  63417. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  63418. */
  63419. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  63420. if (scene === void 0) { scene = null; }
  63421. var points = options.points;
  63422. var instance = options.instance;
  63423. var gapSize = options.gapSize || 1;
  63424. var dashSize = options.dashSize || 3;
  63425. if (instance) { // dashed lines update
  63426. var positionFunction = function (positions) {
  63427. var curvect = BABYLON.Vector3.Zero();
  63428. var nbSeg = positions.length / 6;
  63429. var lg = 0;
  63430. var nb = 0;
  63431. var shft = 0;
  63432. var dashshft = 0;
  63433. var curshft = 0;
  63434. var p = 0;
  63435. var i = 0;
  63436. var j = 0;
  63437. for (i = 0; i < points.length - 1; i++) {
  63438. points[i + 1].subtractToRef(points[i], curvect);
  63439. lg += curvect.length();
  63440. }
  63441. shft = lg / nbSeg;
  63442. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  63443. for (i = 0; i < points.length - 1; i++) {
  63444. points[i + 1].subtractToRef(points[i], curvect);
  63445. nb = Math.floor(curvect.length() / shft);
  63446. curvect.normalize();
  63447. j = 0;
  63448. while (j < nb && p < positions.length) {
  63449. curshft = shft * j;
  63450. positions[p] = points[i].x + curshft * curvect.x;
  63451. positions[p + 1] = points[i].y + curshft * curvect.y;
  63452. positions[p + 2] = points[i].z + curshft * curvect.z;
  63453. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  63454. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  63455. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  63456. p += 6;
  63457. j++;
  63458. }
  63459. }
  63460. while (p < positions.length) {
  63461. positions[p] = points[i].x;
  63462. positions[p + 1] = points[i].y;
  63463. positions[p + 2] = points[i].z;
  63464. p += 3;
  63465. }
  63466. };
  63467. instance.updateMeshPositions(positionFunction, false);
  63468. return instance;
  63469. }
  63470. // dashed lines creation
  63471. var dashedLines = new BABYLON.LinesMesh(name, scene);
  63472. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  63473. vertexData.applyToMesh(dashedLines, options.updatable);
  63474. dashedLines.dashSize = dashSize;
  63475. dashedLines.gapSize = gapSize;
  63476. return dashedLines;
  63477. };
  63478. /**
  63479. * 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.
  63480. * * 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.
  63481. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  63482. * * 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.
  63483. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  63484. * * 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
  63485. * * 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
  63486. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  63487. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63488. * * 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
  63489. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  63490. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63491. * @param name defines the name of the mesh
  63492. * @param options defines the options used to create the mesh
  63493. * @param scene defines the hosting scene
  63494. * @returns the extruded shape mesh
  63495. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  63496. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  63497. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  63498. */
  63499. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  63500. if (scene === void 0) { scene = null; }
  63501. var path = options.path;
  63502. var shape = options.shape;
  63503. var scale = options.scale || 1;
  63504. var rotation = options.rotation || 0;
  63505. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  63506. var updatable = options.updatable;
  63507. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63508. var instance = options.instance || null;
  63509. var invertUV = options.invertUV || false;
  63510. 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);
  63511. };
  63512. /**
  63513. * Creates an custom extruded shape mesh.
  63514. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  63515. * * 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.
  63516. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  63517. * * 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
  63518. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  63519. * * 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
  63520. * * It must returns a float value that will be the scale value applied to the shape on each path point
  63521. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  63522. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  63523. * * 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
  63524. * * 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
  63525. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  63526. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63527. * * 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
  63528. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  63529. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63530. * @param name defines the name of the mesh
  63531. * @param options defines the options used to create the mesh
  63532. * @param scene defines the hosting scene
  63533. * @returns the custom extruded shape mesh
  63534. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  63535. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  63536. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  63537. */
  63538. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  63539. var path = options.path;
  63540. var shape = options.shape;
  63541. var scaleFunction = options.scaleFunction || (function () { return 1; });
  63542. var rotationFunction = options.rotationFunction || (function () { return 0; });
  63543. var ribbonCloseArray = options.ribbonCloseArray || false;
  63544. var ribbonClosePath = options.ribbonClosePath || false;
  63545. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  63546. var updatable = options.updatable;
  63547. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63548. var instance = options.instance;
  63549. var invertUV = options.invertUV || false;
  63550. 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);
  63551. };
  63552. /**
  63553. * Creates lathe mesh.
  63554. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  63555. * * 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
  63556. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  63557. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  63558. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  63559. * * 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
  63560. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  63561. * * 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
  63562. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63563. * * 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
  63564. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  63565. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63566. * @param name defines the name of the mesh
  63567. * @param options defines the options used to create the mesh
  63568. * @param scene defines the hosting scene
  63569. * @returns the lathe mesh
  63570. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  63571. */
  63572. MeshBuilder.CreateLathe = function (name, options, scene) {
  63573. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  63574. var closed = (options.closed === undefined) ? true : options.closed;
  63575. var shape = options.shape;
  63576. var radius = options.radius || 1;
  63577. var tessellation = options.tessellation || 64;
  63578. var clip = options.clip || 0;
  63579. var updatable = options.updatable;
  63580. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63581. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  63582. var pi2 = Math.PI * 2;
  63583. var paths = new Array();
  63584. var invertUV = options.invertUV || false;
  63585. var i = 0;
  63586. var p = 0;
  63587. var step = pi2 / tessellation * arc;
  63588. var rotated;
  63589. var path = new Array();
  63590. for (i = 0; i <= tessellation - clip; i++) {
  63591. var path = [];
  63592. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  63593. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  63594. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  63595. }
  63596. for (p = 0; p < shape.length; p++) {
  63597. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  63598. path.push(rotated);
  63599. }
  63600. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  63601. 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));
  63602. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  63603. }
  63604. paths.push(path);
  63605. }
  63606. // lathe ribbon
  63607. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  63608. return lathe;
  63609. };
  63610. /**
  63611. * Creates a plane mesh
  63612. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  63613. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  63614. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  63615. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63616. * * 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
  63617. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63618. * @param name defines the name of the mesh
  63619. * @param options defines the options used to create the mesh
  63620. * @param scene defines the hosting scene
  63621. * @returns the plane mesh
  63622. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  63623. */
  63624. MeshBuilder.CreatePlane = function (name, options, scene) {
  63625. var plane = new BABYLON.Mesh(name, scene);
  63626. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63627. plane._originalBuilderSideOrientation = options.sideOrientation;
  63628. var vertexData = BABYLON.VertexData.CreatePlane(options);
  63629. vertexData.applyToMesh(plane, options.updatable);
  63630. if (options.sourcePlane) {
  63631. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  63632. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  63633. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  63634. plane.rotate(vectorProduct, product);
  63635. }
  63636. return plane;
  63637. };
  63638. /**
  63639. * Creates a ground mesh
  63640. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  63641. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  63642. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63643. * @param name defines the name of the mesh
  63644. * @param options defines the options used to create the mesh
  63645. * @param scene defines the hosting scene
  63646. * @returns the ground mesh
  63647. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  63648. */
  63649. MeshBuilder.CreateGround = function (name, options, scene) {
  63650. var ground = new BABYLON.GroundMesh(name, scene);
  63651. ground._setReady(false);
  63652. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  63653. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  63654. ground._width = options.width || 1;
  63655. ground._height = options.height || 1;
  63656. ground._maxX = ground._width / 2;
  63657. ground._maxZ = ground._height / 2;
  63658. ground._minX = -ground._maxX;
  63659. ground._minZ = -ground._maxZ;
  63660. var vertexData = BABYLON.VertexData.CreateGround(options);
  63661. vertexData.applyToMesh(ground, options.updatable);
  63662. ground._setReady(true);
  63663. return ground;
  63664. };
  63665. /**
  63666. * Creates a tiled ground mesh
  63667. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  63668. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  63669. * * 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
  63670. * * 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
  63671. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63672. * @param name defines the name of the mesh
  63673. * @param options defines the options used to create the mesh
  63674. * @param scene defines the hosting scene
  63675. * @returns the tiled ground mesh
  63676. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  63677. */
  63678. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  63679. var tiledGround = new BABYLON.Mesh(name, scene);
  63680. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  63681. vertexData.applyToMesh(tiledGround, options.updatable);
  63682. return tiledGround;
  63683. };
  63684. /**
  63685. * Creates a ground mesh from a height map
  63686. * * The parameter `url` sets the URL of the height map image resource.
  63687. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  63688. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  63689. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  63690. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  63691. * * 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.
  63692. * * 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).
  63693. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  63694. * @param name defines the name of the mesh
  63695. * @param url defines the url to the height map
  63696. * @param options defines the options used to create the mesh
  63697. * @param scene defines the hosting scene
  63698. * @returns the ground mesh
  63699. * @see http://doc.babylonjs.com/babylon101/height_map
  63700. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  63701. */
  63702. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  63703. var width = options.width || 10.0;
  63704. var height = options.height || 10.0;
  63705. var subdivisions = options.subdivisions || 1 | 0;
  63706. var minHeight = options.minHeight || 0.0;
  63707. var maxHeight = options.maxHeight || 1.0;
  63708. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  63709. var updatable = options.updatable;
  63710. var onReady = options.onReady;
  63711. var ground = new BABYLON.GroundMesh(name, scene);
  63712. ground._subdivisionsX = subdivisions;
  63713. ground._subdivisionsY = subdivisions;
  63714. ground._width = width;
  63715. ground._height = height;
  63716. ground._maxX = ground._width / 2.0;
  63717. ground._maxZ = ground._height / 2.0;
  63718. ground._minX = -ground._maxX;
  63719. ground._minZ = -ground._maxZ;
  63720. ground._setReady(false);
  63721. var onload = function (img) {
  63722. // Getting height map data
  63723. var canvas = document.createElement("canvas");
  63724. var context = canvas.getContext("2d");
  63725. if (!context) {
  63726. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  63727. }
  63728. if (scene.isDisposed) {
  63729. return;
  63730. }
  63731. var bufferWidth = img.width;
  63732. var bufferHeight = img.height;
  63733. canvas.width = bufferWidth;
  63734. canvas.height = bufferHeight;
  63735. context.drawImage(img, 0, 0);
  63736. // Create VertexData from map data
  63737. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  63738. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  63739. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  63740. width: width, height: height,
  63741. subdivisions: subdivisions,
  63742. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  63743. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  63744. });
  63745. vertexData.applyToMesh(ground, updatable);
  63746. //execute ready callback, if set
  63747. if (onReady) {
  63748. onReady(ground);
  63749. }
  63750. ground._setReady(true);
  63751. };
  63752. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  63753. return ground;
  63754. };
  63755. /**
  63756. * Creates a polygon mesh
  63757. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  63758. * * 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
  63759. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63760. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63761. * * 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)
  63762. * * Remember you can only change the shape positions, not their number when updating a polygon
  63763. * @param name defines the name of the mesh
  63764. * @param options defines the options used to create the mesh
  63765. * @param scene defines the hosting scene
  63766. * @returns the polygon mesh
  63767. */
  63768. MeshBuilder.CreatePolygon = function (name, options, scene) {
  63769. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63770. var shape = options.shape;
  63771. var holes = options.holes || [];
  63772. var depth = options.depth || 0;
  63773. var contours = [];
  63774. var hole = [];
  63775. for (var i = 0; i < shape.length; i++) {
  63776. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  63777. }
  63778. var epsilon = 0.00000001;
  63779. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  63780. contours.pop();
  63781. }
  63782. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  63783. for (var hNb = 0; hNb < holes.length; hNb++) {
  63784. hole = [];
  63785. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  63786. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  63787. }
  63788. polygonTriangulation.addHole(hole);
  63789. }
  63790. var polygon = polygonTriangulation.build(options.updatable, depth);
  63791. polygon._originalBuilderSideOrientation = options.sideOrientation;
  63792. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  63793. vertexData.applyToMesh(polygon, options.updatable);
  63794. return polygon;
  63795. };
  63796. ;
  63797. /**
  63798. * Creates an extruded polygon mesh, with depth in the Y direction.
  63799. * * 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)
  63800. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  63801. * @param name defines the name of the mesh
  63802. * @param options defines the options used to create the mesh
  63803. * @param scene defines the hosting scene
  63804. * @returns the polygon mesh
  63805. */
  63806. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  63807. return MeshBuilder.CreatePolygon(name, options, scene);
  63808. };
  63809. ;
  63810. /**
  63811. * Creates a tube mesh.
  63812. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  63813. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  63814. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  63815. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  63816. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  63817. * * 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)
  63818. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  63819. * * 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
  63820. * * 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
  63821. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63822. * * 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
  63823. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  63824. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63825. * @param name defines the name of the mesh
  63826. * @param options defines the options used to create the mesh
  63827. * @param scene defines the hosting scene
  63828. * @returns the tube mesh
  63829. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  63830. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  63831. */
  63832. MeshBuilder.CreateTube = function (name, options, scene) {
  63833. var path = options.path;
  63834. var instance = options.instance;
  63835. var radius = 1.0;
  63836. if (instance) {
  63837. radius = instance.radius;
  63838. }
  63839. if (options.radius !== undefined) {
  63840. radius = options.radius;
  63841. }
  63842. ;
  63843. var tessellation = options.tessellation || 64 | 0;
  63844. var radiusFunction = options.radiusFunction || null;
  63845. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  63846. var invertUV = options.invertUV || false;
  63847. var updatable = options.updatable;
  63848. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63849. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  63850. // tube geometry
  63851. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  63852. var tangents = path3D.getTangents();
  63853. var normals = path3D.getNormals();
  63854. var distances = path3D.getDistances();
  63855. var pi2 = Math.PI * 2;
  63856. var step = pi2 / tessellation * arc;
  63857. var returnRadius = function () { return radius; };
  63858. var radiusFunctionFinal = radiusFunction || returnRadius;
  63859. var circlePath;
  63860. var rad;
  63861. var normal;
  63862. var rotated;
  63863. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  63864. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  63865. for (var i = 0; i < path.length; i++) {
  63866. rad = radiusFunctionFinal(i, distances[i]); // current radius
  63867. circlePath = Array(); // current circle array
  63868. normal = normals[i]; // current normal
  63869. for (var t = 0; t < tessellation; t++) {
  63870. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  63871. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  63872. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  63873. rotated.scaleInPlace(rad).addInPlace(path[i]);
  63874. circlePath[t] = rotated;
  63875. }
  63876. circlePaths[index] = circlePath;
  63877. index++;
  63878. }
  63879. // cap
  63880. var capPath = function (nbPoints, pathIndex) {
  63881. var pointCap = Array();
  63882. for (var i = 0; i < nbPoints; i++) {
  63883. pointCap.push(path[pathIndex]);
  63884. }
  63885. return pointCap;
  63886. };
  63887. switch (cap) {
  63888. case BABYLON.Mesh.NO_CAP:
  63889. break;
  63890. case BABYLON.Mesh.CAP_START:
  63891. circlePaths[0] = capPath(tessellation, 0);
  63892. circlePaths[1] = circlePaths[2].slice(0);
  63893. break;
  63894. case BABYLON.Mesh.CAP_END:
  63895. circlePaths[index] = circlePaths[index - 1].slice(0);
  63896. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  63897. break;
  63898. case BABYLON.Mesh.CAP_ALL:
  63899. circlePaths[0] = capPath(tessellation, 0);
  63900. circlePaths[1] = circlePaths[2].slice(0);
  63901. circlePaths[index] = circlePaths[index - 1].slice(0);
  63902. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  63903. break;
  63904. default:
  63905. break;
  63906. }
  63907. return circlePaths;
  63908. };
  63909. var path3D;
  63910. var pathArray;
  63911. if (instance) { // tube update
  63912. var arc = options.arc || instance.arc;
  63913. path3D = (instance.path3D).update(path);
  63914. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  63915. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  63916. instance.path3D = path3D;
  63917. instance.pathArray = pathArray;
  63918. instance.arc = arc;
  63919. instance.radius = radius;
  63920. return instance;
  63921. }
  63922. // tube creation
  63923. path3D = new BABYLON.Path3D(path);
  63924. var newPathArray = new Array();
  63925. cap = (cap < 0 || cap > 3) ? 0 : cap;
  63926. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  63927. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  63928. tube.pathArray = pathArray;
  63929. tube.path3D = path3D;
  63930. tube.tessellation = tessellation;
  63931. tube.cap = cap;
  63932. tube.arc = options.arc;
  63933. tube.radius = radius;
  63934. return tube;
  63935. };
  63936. /**
  63937. * Creates a polyhedron mesh
  63938. * * 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
  63939. * * The parameter `size` (positive float, default 1) sets the polygon size
  63940. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  63941. * * 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`
  63942. * * 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
  63943. * * 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)`)
  63944. * * 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
  63945. * * 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
  63946. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  63947. * * 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
  63948. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  63949. * @param name defines the name of the mesh
  63950. * @param options defines the options used to create the mesh
  63951. * @param scene defines the hosting scene
  63952. * @returns the polyhedron mesh
  63953. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  63954. */
  63955. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  63956. var polyhedron = new BABYLON.Mesh(name, scene);
  63957. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  63958. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  63959. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  63960. vertexData.applyToMesh(polyhedron, options.updatable);
  63961. return polyhedron;
  63962. };
  63963. /**
  63964. * Creates a decal mesh.
  63965. * 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
  63966. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  63967. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  63968. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  63969. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  63970. * @param name defines the name of the mesh
  63971. * @param sourceMesh defines the mesh where the decal must be applied
  63972. * @param options defines the options used to create the mesh
  63973. * @param scene defines the hosting scene
  63974. * @returns the decal mesh
  63975. * @see http://doc.babylonjs.com/how_to/decals
  63976. */
  63977. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  63978. var indices = sourceMesh.getIndices();
  63979. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63980. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  63981. var position = options.position || BABYLON.Vector3.Zero();
  63982. var normal = options.normal || BABYLON.Vector3.Up();
  63983. var size = options.size || BABYLON.Vector3.One();
  63984. var angle = options.angle || 0;
  63985. // Getting correct rotation
  63986. if (!normal) {
  63987. var target = new BABYLON.Vector3(0, 0, 1);
  63988. var camera = sourceMesh.getScene().activeCamera;
  63989. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  63990. normal = camera.globalPosition.subtract(cameraWorldTarget);
  63991. }
  63992. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  63993. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  63994. var pitch = Math.atan2(normal.y, len);
  63995. // Matrix
  63996. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  63997. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  63998. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  63999. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  64000. var vertexData = new BABYLON.VertexData();
  64001. vertexData.indices = [];
  64002. vertexData.positions = [];
  64003. vertexData.normals = [];
  64004. vertexData.uvs = [];
  64005. var currentVertexDataIndex = 0;
  64006. var extractDecalVector3 = function (indexId) {
  64007. var result = new BABYLON.PositionNormalVertex();
  64008. if (!indices || !positions || !normals) {
  64009. return result;
  64010. }
  64011. var vertexId = indices[indexId];
  64012. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  64013. // Send vector to decal local world
  64014. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  64015. // Get normal
  64016. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  64017. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  64018. return result;
  64019. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  64020. var clip = function (vertices, axis) {
  64021. if (vertices.length === 0) {
  64022. return vertices;
  64023. }
  64024. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  64025. var clipVertices = function (v0, v1) {
  64026. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  64027. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  64028. };
  64029. var result = new Array();
  64030. for (var index = 0; index < vertices.length; index += 3) {
  64031. var v1Out;
  64032. var v2Out;
  64033. var v3Out;
  64034. var total = 0;
  64035. var nV1 = null;
  64036. var nV2 = null;
  64037. var nV3 = null;
  64038. var nV4 = null;
  64039. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  64040. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  64041. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  64042. v1Out = d1 > 0;
  64043. v2Out = d2 > 0;
  64044. v3Out = d3 > 0;
  64045. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  64046. switch (total) {
  64047. case 0:
  64048. result.push(vertices[index]);
  64049. result.push(vertices[index + 1]);
  64050. result.push(vertices[index + 2]);
  64051. break;
  64052. case 1:
  64053. if (v1Out) {
  64054. nV1 = vertices[index + 1];
  64055. nV2 = vertices[index + 2];
  64056. nV3 = clipVertices(vertices[index], nV1);
  64057. nV4 = clipVertices(vertices[index], nV2);
  64058. }
  64059. if (v2Out) {
  64060. nV1 = vertices[index];
  64061. nV2 = vertices[index + 2];
  64062. nV3 = clipVertices(vertices[index + 1], nV1);
  64063. nV4 = clipVertices(vertices[index + 1], nV2);
  64064. result.push(nV3);
  64065. result.push(nV2.clone());
  64066. result.push(nV1.clone());
  64067. result.push(nV2.clone());
  64068. result.push(nV3.clone());
  64069. result.push(nV4);
  64070. break;
  64071. }
  64072. if (v3Out) {
  64073. nV1 = vertices[index];
  64074. nV2 = vertices[index + 1];
  64075. nV3 = clipVertices(vertices[index + 2], nV1);
  64076. nV4 = clipVertices(vertices[index + 2], nV2);
  64077. }
  64078. if (nV1 && nV2 && nV3 && nV4) {
  64079. result.push(nV1.clone());
  64080. result.push(nV2.clone());
  64081. result.push(nV3);
  64082. result.push(nV4);
  64083. result.push(nV3.clone());
  64084. result.push(nV2.clone());
  64085. }
  64086. break;
  64087. case 2:
  64088. if (!v1Out) {
  64089. nV1 = vertices[index].clone();
  64090. nV2 = clipVertices(nV1, vertices[index + 1]);
  64091. nV3 = clipVertices(nV1, vertices[index + 2]);
  64092. result.push(nV1);
  64093. result.push(nV2);
  64094. result.push(nV3);
  64095. }
  64096. if (!v2Out) {
  64097. nV1 = vertices[index + 1].clone();
  64098. nV2 = clipVertices(nV1, vertices[index + 2]);
  64099. nV3 = clipVertices(nV1, vertices[index]);
  64100. result.push(nV1);
  64101. result.push(nV2);
  64102. result.push(nV3);
  64103. }
  64104. if (!v3Out) {
  64105. nV1 = vertices[index + 2].clone();
  64106. nV2 = clipVertices(nV1, vertices[index]);
  64107. nV3 = clipVertices(nV1, vertices[index + 1]);
  64108. result.push(nV1);
  64109. result.push(nV2);
  64110. result.push(nV3);
  64111. }
  64112. break;
  64113. case 3:
  64114. break;
  64115. }
  64116. }
  64117. return result;
  64118. };
  64119. for (var index = 0; index < indices.length; index += 3) {
  64120. var faceVertices = new Array();
  64121. faceVertices.push(extractDecalVector3(index));
  64122. faceVertices.push(extractDecalVector3(index + 1));
  64123. faceVertices.push(extractDecalVector3(index + 2));
  64124. // Clip
  64125. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  64126. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  64127. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  64128. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  64129. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  64130. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  64131. if (faceVertices.length === 0) {
  64132. continue;
  64133. }
  64134. // Add UVs and get back to world
  64135. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  64136. var vertex = faceVertices[vIndex];
  64137. //TODO check for Int32Array | Uint32Array | Uint16Array
  64138. vertexData.indices.push(currentVertexDataIndex);
  64139. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  64140. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  64141. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  64142. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  64143. currentVertexDataIndex++;
  64144. }
  64145. }
  64146. // Return mesh
  64147. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  64148. vertexData.applyToMesh(decal);
  64149. decal.position = position.clone();
  64150. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  64151. return decal;
  64152. };
  64153. // Privates
  64154. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  64155. // extrusion geometry
  64156. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  64157. var tangents = path3D.getTangents();
  64158. var normals = path3D.getNormals();
  64159. var binormals = path3D.getBinormals();
  64160. var distances = path3D.getDistances();
  64161. var angle = 0;
  64162. var returnScale = function () { return scale !== null ? scale : 1; };
  64163. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  64164. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  64165. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  64166. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  64167. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  64168. for (var i = 0; i < curve.length; i++) {
  64169. var shapePath = new Array();
  64170. var angleStep = rotate(i, distances[i]);
  64171. var scaleRatio = scl(i, distances[i]);
  64172. for (var p = 0; p < shape.length; p++) {
  64173. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  64174. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  64175. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  64176. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  64177. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  64178. shapePath[p] = rotated;
  64179. }
  64180. shapePaths[index] = shapePath;
  64181. angle += angleStep;
  64182. index++;
  64183. }
  64184. // cap
  64185. var capPath = function (shapePath) {
  64186. var pointCap = Array();
  64187. var barycenter = BABYLON.Vector3.Zero();
  64188. var i;
  64189. for (i = 0; i < shapePath.length; i++) {
  64190. barycenter.addInPlace(shapePath[i]);
  64191. }
  64192. barycenter.scaleInPlace(1.0 / shapePath.length);
  64193. for (i = 0; i < shapePath.length; i++) {
  64194. pointCap.push(barycenter);
  64195. }
  64196. return pointCap;
  64197. };
  64198. switch (cap) {
  64199. case BABYLON.Mesh.NO_CAP:
  64200. break;
  64201. case BABYLON.Mesh.CAP_START:
  64202. shapePaths[0] = capPath(shapePaths[2]);
  64203. shapePaths[1] = shapePaths[2];
  64204. break;
  64205. case BABYLON.Mesh.CAP_END:
  64206. shapePaths[index] = shapePaths[index - 1];
  64207. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  64208. break;
  64209. case BABYLON.Mesh.CAP_ALL:
  64210. shapePaths[0] = capPath(shapePaths[2]);
  64211. shapePaths[1] = shapePaths[2];
  64212. shapePaths[index] = shapePaths[index - 1];
  64213. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  64214. break;
  64215. default:
  64216. break;
  64217. }
  64218. return shapePaths;
  64219. };
  64220. var path3D;
  64221. var pathArray;
  64222. if (instance) { // instance update
  64223. path3D = (instance.path3D).update(curve);
  64224. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  64225. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  64226. return instance;
  64227. }
  64228. // extruded shape creation
  64229. path3D = new BABYLON.Path3D(curve);
  64230. var newShapePaths = new Array();
  64231. cap = (cap < 0 || cap > 3) ? 0 : cap;
  64232. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  64233. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  64234. extrudedGeneric.pathArray = pathArray;
  64235. extrudedGeneric.path3D = path3D;
  64236. extrudedGeneric.cap = cap;
  64237. return extrudedGeneric;
  64238. };
  64239. return MeshBuilder;
  64240. }());
  64241. BABYLON.MeshBuilder = MeshBuilder;
  64242. })(BABYLON || (BABYLON = {}));
  64243. //# sourceMappingURL=babylon.meshBuilder.js.map
  64244. var BABYLON;
  64245. (function (BABYLON) {
  64246. /**
  64247. * Draco compression (https://google.github.io/draco/)
  64248. *
  64249. * This class wraps the Draco module.
  64250. *
  64251. * **Encoder**
  64252. *
  64253. * The encoder is not currently implemented.
  64254. *
  64255. * **Decoder**
  64256. *
  64257. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  64258. *
  64259. * To update the configuration, use the following code:
  64260. * ```javascript
  64261. * BABYLON.DracoCompression.Configuration = {
  64262. * decoder: {
  64263. * wasmUrl: "<url to the WebAssembly library>",
  64264. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  64265. * fallbackUrl: "<url to the fallback JavaScript library>",
  64266. * }
  64267. * };
  64268. * ```
  64269. *
  64270. * 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.
  64271. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  64272. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  64273. *
  64274. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  64275. * ```javascript
  64276. * var dracoCompression = new BABYLON.DracoCompression();
  64277. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  64278. * [BABYLON.VertexBuffer.PositionKind]: 0
  64279. * });
  64280. * ```
  64281. *
  64282. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  64283. */
  64284. var DracoCompression = /** @class */ (function () {
  64285. /**
  64286. * Constructor
  64287. */
  64288. function DracoCompression() {
  64289. }
  64290. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  64291. /**
  64292. * Returns true if the decoder is available.
  64293. */
  64294. get: function () {
  64295. if (typeof DracoDecoderModule !== "undefined") {
  64296. return true;
  64297. }
  64298. var decoder = DracoCompression.Configuration.decoder;
  64299. if (decoder) {
  64300. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  64301. return true;
  64302. }
  64303. if (decoder.fallbackUrl) {
  64304. return true;
  64305. }
  64306. }
  64307. return false;
  64308. },
  64309. enumerable: true,
  64310. configurable: true
  64311. });
  64312. /**
  64313. * Stop all async operations and release resources.
  64314. */
  64315. DracoCompression.prototype.dispose = function () {
  64316. };
  64317. /**
  64318. * Decode Draco compressed mesh data to vertex data.
  64319. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  64320. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  64321. * @returns A promise that resolves with the decoded vertex data
  64322. */
  64323. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  64324. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  64325. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  64326. var module = wrappedModule.module;
  64327. var vertexData = new BABYLON.VertexData();
  64328. var buffer = new module.DecoderBuffer();
  64329. buffer.Init(dataView, dataView.byteLength);
  64330. var decoder = new module.Decoder();
  64331. var geometry;
  64332. var status;
  64333. try {
  64334. var type = decoder.GetEncodedGeometryType(buffer);
  64335. switch (type) {
  64336. case module.TRIANGULAR_MESH:
  64337. geometry = new module.Mesh();
  64338. status = decoder.DecodeBufferToMesh(buffer, geometry);
  64339. break;
  64340. case module.POINT_CLOUD:
  64341. geometry = new module.PointCloud();
  64342. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  64343. break;
  64344. default:
  64345. throw new Error("Invalid geometry type " + type);
  64346. }
  64347. if (!status.ok() || !geometry.ptr) {
  64348. throw new Error(status.error_msg());
  64349. }
  64350. var numPoints = geometry.num_points();
  64351. if (type === module.TRIANGULAR_MESH) {
  64352. var numFaces = geometry.num_faces();
  64353. var faceIndices = new module.DracoInt32Array();
  64354. try {
  64355. var indices = new Uint32Array(numFaces * 3);
  64356. for (var i = 0; i < numFaces; i++) {
  64357. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  64358. var offset = i * 3;
  64359. indices[offset + 0] = faceIndices.GetValue(0);
  64360. indices[offset + 1] = faceIndices.GetValue(1);
  64361. indices[offset + 2] = faceIndices.GetValue(2);
  64362. }
  64363. vertexData.indices = indices;
  64364. }
  64365. finally {
  64366. module.destroy(faceIndices);
  64367. }
  64368. }
  64369. for (var kind in attributes) {
  64370. var uniqueId = attributes[kind];
  64371. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  64372. var dracoData = new module.DracoFloat32Array();
  64373. try {
  64374. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  64375. var babylonData = new Float32Array(numPoints * attribute.num_components());
  64376. for (var i = 0; i < babylonData.length; i++) {
  64377. babylonData[i] = dracoData.GetValue(i);
  64378. }
  64379. vertexData.set(babylonData, kind);
  64380. }
  64381. finally {
  64382. module.destroy(dracoData);
  64383. }
  64384. }
  64385. }
  64386. finally {
  64387. if (geometry) {
  64388. module.destroy(geometry);
  64389. }
  64390. module.destroy(decoder);
  64391. module.destroy(buffer);
  64392. }
  64393. return vertexData;
  64394. });
  64395. };
  64396. DracoCompression._GetDecoderModule = function () {
  64397. if (!DracoCompression._DecoderModulePromise) {
  64398. var promise = null;
  64399. var config_1 = {};
  64400. if (typeof DracoDecoderModule !== "undefined") {
  64401. promise = Promise.resolve();
  64402. }
  64403. else {
  64404. var decoder = DracoCompression.Configuration.decoder;
  64405. if (decoder) {
  64406. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  64407. promise = Promise.all([
  64408. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  64409. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  64410. config_1.wasmBinary = data;
  64411. })
  64412. ]);
  64413. }
  64414. else if (decoder.fallbackUrl) {
  64415. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  64416. }
  64417. }
  64418. }
  64419. if (!promise) {
  64420. throw new Error("Draco decoder module is not available");
  64421. }
  64422. DracoCompression._DecoderModulePromise = promise.then(function () {
  64423. return new Promise(function (resolve) {
  64424. config_1.onModuleLoaded = function (decoderModule) {
  64425. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  64426. resolve({ module: decoderModule });
  64427. };
  64428. DracoDecoderModule(config_1);
  64429. });
  64430. });
  64431. }
  64432. return DracoCompression._DecoderModulePromise;
  64433. };
  64434. DracoCompression._LoadScriptAsync = function (url) {
  64435. return new Promise(function (resolve, reject) {
  64436. BABYLON.Tools.LoadScript(url, function () {
  64437. resolve();
  64438. }, function (message) {
  64439. reject(new Error(message));
  64440. });
  64441. });
  64442. };
  64443. DracoCompression._LoadFileAsync = function (url) {
  64444. return new Promise(function (resolve, reject) {
  64445. BABYLON.Tools.LoadFile(url, function (data) {
  64446. resolve(data);
  64447. }, undefined, undefined, true, function (request, exception) {
  64448. reject(exception);
  64449. });
  64450. });
  64451. };
  64452. /**
  64453. * The configuration. Defaults to the following urls:
  64454. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  64455. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  64456. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  64457. */
  64458. DracoCompression.Configuration = {
  64459. decoder: {
  64460. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  64461. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  64462. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  64463. }
  64464. };
  64465. return DracoCompression;
  64466. }());
  64467. BABYLON.DracoCompression = DracoCompression;
  64468. })(BABYLON || (BABYLON = {}));
  64469. //# sourceMappingURL=babylon.dracoCompression.js.map
  64470. var BABYLON;
  64471. (function (BABYLON) {
  64472. var AudioEngine = /** @class */ (function () {
  64473. function AudioEngine() {
  64474. this._audioContext = null;
  64475. this._audioContextInitialized = false;
  64476. this.canUseWebAudio = false;
  64477. this.WarnedWebAudioUnsupported = false;
  64478. this.unlocked = false;
  64479. this.isMP3supported = false;
  64480. this.isOGGsupported = false;
  64481. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  64482. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  64483. this.canUseWebAudio = true;
  64484. }
  64485. var audioElem = document.createElement('audio');
  64486. try {
  64487. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  64488. this.isMP3supported = true;
  64489. }
  64490. }
  64491. catch (e) {
  64492. // protect error during capability check.
  64493. }
  64494. try {
  64495. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  64496. this.isOGGsupported = true;
  64497. }
  64498. }
  64499. catch (e) {
  64500. // protect error during capability check.
  64501. }
  64502. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  64503. this._unlockiOSaudio();
  64504. }
  64505. else {
  64506. this.unlocked = true;
  64507. }
  64508. }
  64509. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  64510. get: function () {
  64511. if (!this._audioContextInitialized) {
  64512. this._initializeAudioContext();
  64513. }
  64514. return this._audioContext;
  64515. },
  64516. enumerable: true,
  64517. configurable: true
  64518. });
  64519. AudioEngine.prototype._unlockiOSaudio = function () {
  64520. var _this = this;
  64521. var unlockaudio = function () {
  64522. if (!_this.audioContext) {
  64523. return;
  64524. }
  64525. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  64526. var source = _this.audioContext.createBufferSource();
  64527. source.buffer = buffer;
  64528. source.connect(_this.audioContext.destination);
  64529. source.start(0);
  64530. setTimeout(function () {
  64531. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  64532. _this.unlocked = true;
  64533. window.removeEventListener('touchend', unlockaudio, false);
  64534. if (_this.onAudioUnlocked) {
  64535. _this.onAudioUnlocked();
  64536. }
  64537. }
  64538. }, 0);
  64539. };
  64540. window.addEventListener('touchend', unlockaudio, false);
  64541. };
  64542. AudioEngine.prototype._initializeAudioContext = function () {
  64543. try {
  64544. if (this.canUseWebAudio) {
  64545. this._audioContext = new AudioContext();
  64546. // create a global volume gain node
  64547. this.masterGain = this._audioContext.createGain();
  64548. this.masterGain.gain.value = 1;
  64549. this.masterGain.connect(this._audioContext.destination);
  64550. this._audioContextInitialized = true;
  64551. }
  64552. }
  64553. catch (e) {
  64554. this.canUseWebAudio = false;
  64555. BABYLON.Tools.Error("Web Audio: " + e.message);
  64556. }
  64557. };
  64558. AudioEngine.prototype.dispose = function () {
  64559. if (this.canUseWebAudio && this._audioContextInitialized) {
  64560. if (this._connectedAnalyser && this._audioContext) {
  64561. this._connectedAnalyser.stopDebugCanvas();
  64562. this._connectedAnalyser.dispose();
  64563. this.masterGain.disconnect();
  64564. this.masterGain.connect(this._audioContext.destination);
  64565. this._connectedAnalyser = null;
  64566. }
  64567. this.masterGain.gain.value = 1;
  64568. }
  64569. this.WarnedWebAudioUnsupported = false;
  64570. };
  64571. AudioEngine.prototype.getGlobalVolume = function () {
  64572. if (this.canUseWebAudio && this._audioContextInitialized) {
  64573. return this.masterGain.gain.value;
  64574. }
  64575. else {
  64576. return -1;
  64577. }
  64578. };
  64579. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  64580. if (this.canUseWebAudio && this._audioContextInitialized) {
  64581. this.masterGain.gain.value = newVolume;
  64582. }
  64583. };
  64584. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  64585. if (this._connectedAnalyser) {
  64586. this._connectedAnalyser.stopDebugCanvas();
  64587. }
  64588. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  64589. this._connectedAnalyser = analyser;
  64590. this.masterGain.disconnect();
  64591. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  64592. }
  64593. };
  64594. return AudioEngine;
  64595. }());
  64596. BABYLON.AudioEngine = AudioEngine;
  64597. })(BABYLON || (BABYLON = {}));
  64598. //# sourceMappingURL=babylon.audioEngine.js.map
  64599. var BABYLON;
  64600. (function (BABYLON) {
  64601. var Sound = /** @class */ (function () {
  64602. /**
  64603. * Create a sound and attach it to a scene
  64604. * @param name Name of your sound
  64605. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  64606. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  64607. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  64608. */
  64609. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  64610. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  64611. var _this = this;
  64612. this.autoplay = false;
  64613. this.loop = false;
  64614. this.useCustomAttenuation = false;
  64615. this.spatialSound = false;
  64616. this.refDistance = 1;
  64617. this.rolloffFactor = 1;
  64618. this.maxDistance = 100;
  64619. this.distanceModel = "linear";
  64620. this._panningModel = "equalpower";
  64621. /**
  64622. * Observable event when the current playing sound finishes.
  64623. */
  64624. this.onEndedObservable = new BABYLON.Observable();
  64625. this._playbackRate = 1;
  64626. this._streaming = false;
  64627. this._startTime = 0;
  64628. this._startOffset = 0;
  64629. this._position = BABYLON.Vector3.Zero();
  64630. /** @hidden */
  64631. this._positionInEmitterSpace = false;
  64632. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  64633. this._volume = 1;
  64634. this._isReadyToPlay = false;
  64635. this.isPlaying = false;
  64636. this.isPaused = false;
  64637. this._isDirectional = false;
  64638. // Used if you'd like to create a directional sound.
  64639. // If not set, the sound will be omnidirectional
  64640. this._coneInnerAngle = 360;
  64641. this._coneOuterAngle = 360;
  64642. this._coneOuterGain = 0;
  64643. this._isOutputConnected = false;
  64644. this._urlType = "Unknown";
  64645. this.name = name;
  64646. this._scene = scene;
  64647. this._readyToPlayCallback = readyToPlayCallback;
  64648. // Default custom attenuation function is a linear attenuation
  64649. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  64650. if (currentDistance < maxDistance) {
  64651. return currentVolume * (1 - currentDistance / maxDistance);
  64652. }
  64653. else {
  64654. return 0;
  64655. }
  64656. };
  64657. if (options) {
  64658. this.autoplay = options.autoplay || false;
  64659. this.loop = options.loop || false;
  64660. // if volume === 0, we need another way to check this option
  64661. if (options.volume !== undefined) {
  64662. this._volume = options.volume;
  64663. }
  64664. this.spatialSound = options.spatialSound || false;
  64665. this.maxDistance = options.maxDistance || 100;
  64666. this.useCustomAttenuation = options.useCustomAttenuation || false;
  64667. this.rolloffFactor = options.rolloffFactor || 1;
  64668. this.refDistance = options.refDistance || 1;
  64669. this.distanceModel = options.distanceModel || "linear";
  64670. this._playbackRate = options.playbackRate || 1;
  64671. this._streaming = options.streaming || false;
  64672. }
  64673. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  64674. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  64675. this._soundGain.gain.value = this._volume;
  64676. this._inputAudioNode = this._soundGain;
  64677. this._outputAudioNode = this._soundGain;
  64678. if (this.spatialSound) {
  64679. this._createSpatialParameters();
  64680. }
  64681. this._scene.mainSoundTrack.AddSound(this);
  64682. var validParameter = true;
  64683. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  64684. if (urlOrArrayBuffer) {
  64685. try {
  64686. if (typeof (urlOrArrayBuffer) === "string") {
  64687. this._urlType = "String";
  64688. }
  64689. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  64690. this._urlType = "ArrayBuffer";
  64691. }
  64692. else if (urlOrArrayBuffer instanceof MediaStream) {
  64693. this._urlType = "MediaStream";
  64694. }
  64695. else if (Array.isArray(urlOrArrayBuffer)) {
  64696. this._urlType = "Array";
  64697. }
  64698. var urls = [];
  64699. var codecSupportedFound = false;
  64700. switch (this._urlType) {
  64701. case "MediaStream":
  64702. this._streaming = true;
  64703. this._isReadyToPlay = true;
  64704. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  64705. if (this.autoplay) {
  64706. this.play();
  64707. }
  64708. if (this._readyToPlayCallback) {
  64709. this._readyToPlayCallback();
  64710. }
  64711. break;
  64712. case "ArrayBuffer":
  64713. if (urlOrArrayBuffer.byteLength > 0) {
  64714. codecSupportedFound = true;
  64715. this._soundLoaded(urlOrArrayBuffer);
  64716. }
  64717. break;
  64718. case "String":
  64719. urls.push(urlOrArrayBuffer);
  64720. case "Array":
  64721. if (urls.length === 0)
  64722. urls = urlOrArrayBuffer;
  64723. // If we found a supported format, we load it immediately and stop the loop
  64724. for (var i = 0; i < urls.length; i++) {
  64725. var url = urls[i];
  64726. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  64727. codecSupportedFound = true;
  64728. }
  64729. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  64730. codecSupportedFound = true;
  64731. }
  64732. if (url.indexOf(".wav", url.length - 4) !== -1) {
  64733. codecSupportedFound = true;
  64734. }
  64735. if (url.indexOf("blob:") !== -1) {
  64736. codecSupportedFound = true;
  64737. }
  64738. if (codecSupportedFound) {
  64739. // Loading sound using XHR2
  64740. if (!this._streaming) {
  64741. this._scene._loadFile(url, function (data) {
  64742. _this._soundLoaded(data);
  64743. }, undefined, true, true, function (exception) {
  64744. if (exception) {
  64745. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  64746. }
  64747. BABYLON.Tools.Error("Sound creation aborted.");
  64748. _this._scene.mainSoundTrack.RemoveSound(_this);
  64749. });
  64750. }
  64751. // Streaming sound using HTML5 Audio tag
  64752. else {
  64753. this._htmlAudioElement = new Audio(url);
  64754. this._htmlAudioElement.controls = false;
  64755. this._htmlAudioElement.loop = this.loop;
  64756. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  64757. this._htmlAudioElement.preload = "auto";
  64758. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  64759. _this._isReadyToPlay = true;
  64760. if (_this.autoplay) {
  64761. _this.play();
  64762. }
  64763. if (_this._readyToPlayCallback) {
  64764. _this._readyToPlayCallback();
  64765. }
  64766. });
  64767. document.body.appendChild(this._htmlAudioElement);
  64768. }
  64769. break;
  64770. }
  64771. }
  64772. break;
  64773. default:
  64774. validParameter = false;
  64775. break;
  64776. }
  64777. if (!validParameter) {
  64778. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  64779. }
  64780. else {
  64781. if (!codecSupportedFound) {
  64782. this._isReadyToPlay = true;
  64783. // Simulating a ready to play event to avoid breaking code path
  64784. if (this._readyToPlayCallback) {
  64785. window.setTimeout(function () {
  64786. if (_this._readyToPlayCallback) {
  64787. _this._readyToPlayCallback();
  64788. }
  64789. }, 1000);
  64790. }
  64791. }
  64792. }
  64793. }
  64794. catch (ex) {
  64795. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  64796. this._scene.mainSoundTrack.RemoveSound(this);
  64797. }
  64798. }
  64799. }
  64800. else {
  64801. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  64802. this._scene.mainSoundTrack.AddSound(this);
  64803. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  64804. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  64805. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  64806. }
  64807. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  64808. if (this._readyToPlayCallback) {
  64809. window.setTimeout(function () {
  64810. if (_this._readyToPlayCallback) {
  64811. _this._readyToPlayCallback();
  64812. }
  64813. }, 1000);
  64814. }
  64815. }
  64816. }
  64817. Sound.prototype.dispose = function () {
  64818. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  64819. if (this.isPlaying) {
  64820. this.stop();
  64821. }
  64822. this._isReadyToPlay = false;
  64823. if (this.soundTrackId === -1) {
  64824. this._scene.mainSoundTrack.RemoveSound(this);
  64825. }
  64826. else {
  64827. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  64828. }
  64829. if (this._soundGain) {
  64830. this._soundGain.disconnect();
  64831. this._soundGain = null;
  64832. }
  64833. if (this._soundPanner) {
  64834. this._soundPanner.disconnect();
  64835. this._soundPanner = null;
  64836. }
  64837. if (this._soundSource) {
  64838. this._soundSource.disconnect();
  64839. this._soundSource = null;
  64840. }
  64841. this._audioBuffer = null;
  64842. if (this._htmlAudioElement) {
  64843. this._htmlAudioElement.pause();
  64844. this._htmlAudioElement.src = "";
  64845. document.body.removeChild(this._htmlAudioElement);
  64846. }
  64847. if (this._streamingSource) {
  64848. this._streamingSource.disconnect();
  64849. }
  64850. if (this._connectedMesh && this._registerFunc) {
  64851. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  64852. this._connectedMesh = null;
  64853. }
  64854. }
  64855. };
  64856. Sound.prototype.isReady = function () {
  64857. return this._isReadyToPlay;
  64858. };
  64859. Sound.prototype._soundLoaded = function (audioData) {
  64860. var _this = this;
  64861. if (!BABYLON.Engine.audioEngine.audioContext) {
  64862. return;
  64863. }
  64864. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  64865. _this._audioBuffer = buffer;
  64866. _this._isReadyToPlay = true;
  64867. if (_this.autoplay) {
  64868. _this.play();
  64869. }
  64870. if (_this._readyToPlayCallback) {
  64871. _this._readyToPlayCallback();
  64872. }
  64873. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  64874. };
  64875. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  64876. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  64877. this._audioBuffer = audioBuffer;
  64878. this._isReadyToPlay = true;
  64879. }
  64880. };
  64881. Sound.prototype.updateOptions = function (options) {
  64882. if (options) {
  64883. this.loop = options.loop || this.loop;
  64884. this.maxDistance = options.maxDistance || this.maxDistance;
  64885. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  64886. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  64887. this.refDistance = options.refDistance || this.refDistance;
  64888. this.distanceModel = options.distanceModel || this.distanceModel;
  64889. this._playbackRate = options.playbackRate || this._playbackRate;
  64890. this._updateSpatialParameters();
  64891. if (this.isPlaying) {
  64892. if (this._streaming && this._htmlAudioElement) {
  64893. this._htmlAudioElement.playbackRate = this._playbackRate;
  64894. }
  64895. else {
  64896. if (this._soundSource) {
  64897. this._soundSource.playbackRate.value = this._playbackRate;
  64898. }
  64899. }
  64900. }
  64901. }
  64902. };
  64903. Sound.prototype._createSpatialParameters = function () {
  64904. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  64905. if (this._scene.headphone) {
  64906. this._panningModel = "HRTF";
  64907. }
  64908. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  64909. this._updateSpatialParameters();
  64910. this._soundPanner.connect(this._outputAudioNode);
  64911. this._inputAudioNode = this._soundPanner;
  64912. }
  64913. };
  64914. Sound.prototype._updateSpatialParameters = function () {
  64915. if (this.spatialSound && this._soundPanner) {
  64916. if (this.useCustomAttenuation) {
  64917. // Tricks to disable in a way embedded Web Audio attenuation
  64918. this._soundPanner.distanceModel = "linear";
  64919. this._soundPanner.maxDistance = Number.MAX_VALUE;
  64920. this._soundPanner.refDistance = 1;
  64921. this._soundPanner.rolloffFactor = 1;
  64922. this._soundPanner.panningModel = this._panningModel;
  64923. }
  64924. else {
  64925. this._soundPanner.distanceModel = this.distanceModel;
  64926. this._soundPanner.maxDistance = this.maxDistance;
  64927. this._soundPanner.refDistance = this.refDistance;
  64928. this._soundPanner.rolloffFactor = this.rolloffFactor;
  64929. this._soundPanner.panningModel = this._panningModel;
  64930. }
  64931. }
  64932. };
  64933. Sound.prototype.switchPanningModelToHRTF = function () {
  64934. this._panningModel = "HRTF";
  64935. this._switchPanningModel();
  64936. };
  64937. Sound.prototype.switchPanningModelToEqualPower = function () {
  64938. this._panningModel = "equalpower";
  64939. this._switchPanningModel();
  64940. };
  64941. Sound.prototype._switchPanningModel = function () {
  64942. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  64943. this._soundPanner.panningModel = this._panningModel;
  64944. }
  64945. };
  64946. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  64947. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  64948. if (this._isOutputConnected) {
  64949. this._outputAudioNode.disconnect();
  64950. }
  64951. this._outputAudioNode.connect(soundTrackAudioNode);
  64952. this._isOutputConnected = true;
  64953. }
  64954. };
  64955. /**
  64956. * Transform this sound into a directional source
  64957. * @param coneInnerAngle Size of the inner cone in degree
  64958. * @param coneOuterAngle Size of the outer cone in degree
  64959. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  64960. */
  64961. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  64962. if (coneOuterAngle < coneInnerAngle) {
  64963. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  64964. return;
  64965. }
  64966. this._coneInnerAngle = coneInnerAngle;
  64967. this._coneOuterAngle = coneOuterAngle;
  64968. this._coneOuterGain = coneOuterGain;
  64969. this._isDirectional = true;
  64970. if (this.isPlaying && this.loop) {
  64971. this.stop();
  64972. this.play();
  64973. }
  64974. };
  64975. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  64976. /**
  64977. * Gets or sets the inner angle for the directional cone.
  64978. */
  64979. get: function () {
  64980. return this._coneInnerAngle;
  64981. },
  64982. /**
  64983. * Gets or sets the inner angle for the directional cone.
  64984. */
  64985. set: function (value) {
  64986. if (value != this._coneInnerAngle) {
  64987. if (this._coneOuterAngle < value) {
  64988. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  64989. return;
  64990. }
  64991. this._coneInnerAngle = value;
  64992. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  64993. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  64994. }
  64995. }
  64996. },
  64997. enumerable: true,
  64998. configurable: true
  64999. });
  65000. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  65001. /**
  65002. * Gets or sets the outer angle for the directional cone.
  65003. */
  65004. get: function () {
  65005. return this._coneOuterAngle;
  65006. },
  65007. /**
  65008. * Gets or sets the outer angle for the directional cone.
  65009. */
  65010. set: function (value) {
  65011. if (value != this._coneOuterAngle) {
  65012. if (value < this._coneInnerAngle) {
  65013. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  65014. return;
  65015. }
  65016. this._coneOuterAngle = value;
  65017. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  65018. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  65019. }
  65020. }
  65021. },
  65022. enumerable: true,
  65023. configurable: true
  65024. });
  65025. Sound.prototype.setPosition = function (newPosition) {
  65026. this._position = newPosition;
  65027. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  65028. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  65029. }
  65030. };
  65031. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  65032. this._localDirection = newLocalDirection;
  65033. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  65034. this._updateDirection();
  65035. }
  65036. };
  65037. Sound.prototype._updateDirection = function () {
  65038. if (!this._connectedMesh || !this._soundPanner) {
  65039. return;
  65040. }
  65041. var mat = this._connectedMesh.getWorldMatrix();
  65042. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  65043. direction.normalize();
  65044. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  65045. };
  65046. Sound.prototype.updateDistanceFromListener = function () {
  65047. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  65048. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  65049. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  65050. }
  65051. };
  65052. Sound.prototype.setAttenuationFunction = function (callback) {
  65053. this._customAttenuationFunction = callback;
  65054. };
  65055. /**
  65056. * Play the sound
  65057. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  65058. * @param offset (optional) Start the sound setting it at a specific time
  65059. */
  65060. Sound.prototype.play = function (time, offset) {
  65061. var _this = this;
  65062. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  65063. try {
  65064. if (this._startOffset < 0) {
  65065. time = -this._startOffset;
  65066. this._startOffset = 0;
  65067. }
  65068. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  65069. if (!this._soundSource || !this._streamingSource) {
  65070. if (this.spatialSound && this._soundPanner) {
  65071. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  65072. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  65073. }
  65074. if (this._isDirectional) {
  65075. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  65076. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  65077. this._soundPanner.coneOuterGain = this._coneOuterGain;
  65078. if (this._connectedMesh) {
  65079. this._updateDirection();
  65080. }
  65081. else {
  65082. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  65083. }
  65084. }
  65085. }
  65086. }
  65087. if (this._streaming) {
  65088. if (!this._streamingSource) {
  65089. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  65090. this._htmlAudioElement.onended = function () { _this._onended(); };
  65091. this._htmlAudioElement.playbackRate = this._playbackRate;
  65092. }
  65093. this._streamingSource.disconnect();
  65094. this._streamingSource.connect(this._inputAudioNode);
  65095. if (this._htmlAudioElement) {
  65096. this._htmlAudioElement.play();
  65097. }
  65098. }
  65099. else {
  65100. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  65101. this._soundSource.buffer = this._audioBuffer;
  65102. this._soundSource.connect(this._inputAudioNode);
  65103. this._soundSource.loop = this.loop;
  65104. this._soundSource.playbackRate.value = this._playbackRate;
  65105. this._soundSource.onended = function () { _this._onended(); };
  65106. if (this._soundSource.buffer) {
  65107. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  65108. }
  65109. }
  65110. this._startTime = startTime;
  65111. this.isPlaying = true;
  65112. this.isPaused = false;
  65113. }
  65114. catch (ex) {
  65115. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  65116. }
  65117. }
  65118. };
  65119. Sound.prototype._onended = function () {
  65120. this.isPlaying = false;
  65121. if (this.onended) {
  65122. this.onended();
  65123. }
  65124. this.onEndedObservable.notifyObservers(this);
  65125. };
  65126. /**
  65127. * Stop the sound
  65128. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  65129. */
  65130. Sound.prototype.stop = function (time) {
  65131. if (this.isPlaying) {
  65132. if (this._streaming) {
  65133. if (this._htmlAudioElement) {
  65134. this._htmlAudioElement.pause();
  65135. // Test needed for Firefox or it will generate an Invalid State Error
  65136. if (this._htmlAudioElement.currentTime > 0) {
  65137. this._htmlAudioElement.currentTime = 0;
  65138. }
  65139. }
  65140. else {
  65141. this._streamingSource.disconnect();
  65142. }
  65143. }
  65144. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  65145. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  65146. this._soundSource.stop(stopTime);
  65147. this._soundSource.onended = function () { };
  65148. if (!this.isPaused) {
  65149. this._startOffset = 0;
  65150. }
  65151. }
  65152. this.isPlaying = false;
  65153. }
  65154. };
  65155. Sound.prototype.pause = function () {
  65156. if (this.isPlaying) {
  65157. this.isPaused = true;
  65158. if (this._streaming) {
  65159. if (this._htmlAudioElement) {
  65160. this._htmlAudioElement.pause();
  65161. }
  65162. else {
  65163. this._streamingSource.disconnect();
  65164. }
  65165. }
  65166. else if (BABYLON.Engine.audioEngine.audioContext) {
  65167. this.stop(0);
  65168. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  65169. }
  65170. }
  65171. };
  65172. Sound.prototype.setVolume = function (newVolume, time) {
  65173. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  65174. if (time && BABYLON.Engine.audioEngine.audioContext) {
  65175. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  65176. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  65177. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  65178. }
  65179. else {
  65180. this._soundGain.gain.value = newVolume;
  65181. }
  65182. }
  65183. this._volume = newVolume;
  65184. };
  65185. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  65186. this._playbackRate = newPlaybackRate;
  65187. if (this.isPlaying) {
  65188. if (this._streaming && this._htmlAudioElement) {
  65189. this._htmlAudioElement.playbackRate = this._playbackRate;
  65190. }
  65191. else if (this._soundSource) {
  65192. this._soundSource.playbackRate.value = this._playbackRate;
  65193. }
  65194. }
  65195. };
  65196. Sound.prototype.getVolume = function () {
  65197. return this._volume;
  65198. };
  65199. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  65200. var _this = this;
  65201. if (this._connectedMesh && this._registerFunc) {
  65202. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  65203. this._registerFunc = null;
  65204. }
  65205. this._connectedMesh = meshToConnectTo;
  65206. if (!this.spatialSound) {
  65207. this.spatialSound = true;
  65208. this._createSpatialParameters();
  65209. if (this.isPlaying && this.loop) {
  65210. this.stop();
  65211. this.play();
  65212. }
  65213. }
  65214. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  65215. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  65216. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  65217. };
  65218. Sound.prototype.detachFromMesh = function () {
  65219. if (this._connectedMesh && this._registerFunc) {
  65220. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  65221. this._registerFunc = null;
  65222. this._connectedMesh = null;
  65223. }
  65224. };
  65225. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  65226. if (!node.getBoundingInfo) {
  65227. return;
  65228. }
  65229. var mesh = node;
  65230. if (this._positionInEmitterSpace) {
  65231. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  65232. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  65233. }
  65234. else {
  65235. var boundingInfo = mesh.getBoundingInfo();
  65236. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  65237. }
  65238. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  65239. this._updateDirection();
  65240. }
  65241. };
  65242. Sound.prototype.clone = function () {
  65243. var _this = this;
  65244. if (!this._streaming) {
  65245. var setBufferAndRun = function () {
  65246. if (_this._isReadyToPlay) {
  65247. clonedSound._audioBuffer = _this.getAudioBuffer();
  65248. clonedSound._isReadyToPlay = true;
  65249. if (clonedSound.autoplay) {
  65250. clonedSound.play();
  65251. }
  65252. }
  65253. else {
  65254. window.setTimeout(setBufferAndRun, 300);
  65255. }
  65256. };
  65257. var currentOptions = {
  65258. autoplay: this.autoplay, loop: this.loop,
  65259. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  65260. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  65261. refDistance: this.refDistance, distanceModel: this.distanceModel
  65262. };
  65263. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  65264. if (this.useCustomAttenuation) {
  65265. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  65266. }
  65267. clonedSound.setPosition(this._position);
  65268. clonedSound.setPlaybackRate(this._playbackRate);
  65269. setBufferAndRun();
  65270. return clonedSound;
  65271. }
  65272. // Can't clone a streaming sound
  65273. else {
  65274. return null;
  65275. }
  65276. };
  65277. Sound.prototype.getAudioBuffer = function () {
  65278. return this._audioBuffer;
  65279. };
  65280. Sound.prototype.serialize = function () {
  65281. var serializationObject = {
  65282. name: this.name,
  65283. url: this.name,
  65284. autoplay: this.autoplay,
  65285. loop: this.loop,
  65286. volume: this._volume,
  65287. spatialSound: this.spatialSound,
  65288. maxDistance: this.maxDistance,
  65289. rolloffFactor: this.rolloffFactor,
  65290. refDistance: this.refDistance,
  65291. distanceModel: this.distanceModel,
  65292. playbackRate: this._playbackRate,
  65293. panningModel: this._panningModel,
  65294. soundTrackId: this.soundTrackId
  65295. };
  65296. if (this.spatialSound) {
  65297. if (this._connectedMesh)
  65298. serializationObject.connectedMeshId = this._connectedMesh.id;
  65299. serializationObject.position = this._position.asArray();
  65300. serializationObject.refDistance = this.refDistance;
  65301. serializationObject.distanceModel = this.distanceModel;
  65302. serializationObject.isDirectional = this._isDirectional;
  65303. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  65304. serializationObject.coneInnerAngle = this._coneInnerAngle;
  65305. serializationObject.coneOuterAngle = this._coneOuterAngle;
  65306. serializationObject.coneOuterGain = this._coneOuterGain;
  65307. }
  65308. return serializationObject;
  65309. };
  65310. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  65311. var soundName = parsedSound.name;
  65312. var soundUrl;
  65313. if (parsedSound.url) {
  65314. soundUrl = rootUrl + parsedSound.url;
  65315. }
  65316. else {
  65317. soundUrl = rootUrl + soundName;
  65318. }
  65319. var options = {
  65320. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  65321. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  65322. rolloffFactor: parsedSound.rolloffFactor,
  65323. refDistance: parsedSound.refDistance,
  65324. distanceModel: parsedSound.distanceModel,
  65325. playbackRate: parsedSound.playbackRate
  65326. };
  65327. var newSound;
  65328. if (!sourceSound) {
  65329. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  65330. scene._addPendingData(newSound);
  65331. }
  65332. else {
  65333. var setBufferAndRun = function () {
  65334. if (sourceSound._isReadyToPlay) {
  65335. newSound._audioBuffer = sourceSound.getAudioBuffer();
  65336. newSound._isReadyToPlay = true;
  65337. if (newSound.autoplay) {
  65338. newSound.play();
  65339. }
  65340. }
  65341. else {
  65342. window.setTimeout(setBufferAndRun, 300);
  65343. }
  65344. };
  65345. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  65346. setBufferAndRun();
  65347. }
  65348. if (parsedSound.position) {
  65349. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  65350. newSound.setPosition(soundPosition);
  65351. }
  65352. if (parsedSound.isDirectional) {
  65353. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  65354. if (parsedSound.localDirectionToMesh) {
  65355. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  65356. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  65357. }
  65358. }
  65359. if (parsedSound.connectedMeshId) {
  65360. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  65361. if (connectedMesh) {
  65362. newSound.attachToMesh(connectedMesh);
  65363. }
  65364. }
  65365. return newSound;
  65366. };
  65367. return Sound;
  65368. }());
  65369. BABYLON.Sound = Sound;
  65370. })(BABYLON || (BABYLON = {}));
  65371. //# sourceMappingURL=babylon.sound.js.map
  65372. var BABYLON;
  65373. (function (BABYLON) {
  65374. var SoundTrack = /** @class */ (function () {
  65375. function SoundTrack(scene, options) {
  65376. this.id = -1;
  65377. this._isMainTrack = false;
  65378. this._isInitialized = false;
  65379. this._scene = scene;
  65380. this.soundCollection = new Array();
  65381. this._options = options;
  65382. if (!this._isMainTrack) {
  65383. this._scene.soundTracks.push(this);
  65384. this.id = this._scene.soundTracks.length - 1;
  65385. }
  65386. }
  65387. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  65388. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  65389. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  65390. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  65391. if (this._options) {
  65392. if (this._options.volume) {
  65393. this._outputAudioNode.gain.value = this._options.volume;
  65394. }
  65395. if (this._options.mainTrack) {
  65396. this._isMainTrack = this._options.mainTrack;
  65397. }
  65398. }
  65399. this._isInitialized = true;
  65400. }
  65401. };
  65402. SoundTrack.prototype.dispose = function () {
  65403. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  65404. if (this._connectedAnalyser) {
  65405. this._connectedAnalyser.stopDebugCanvas();
  65406. }
  65407. while (this.soundCollection.length) {
  65408. this.soundCollection[0].dispose();
  65409. }
  65410. if (this._outputAudioNode) {
  65411. this._outputAudioNode.disconnect();
  65412. }
  65413. this._outputAudioNode = null;
  65414. }
  65415. };
  65416. SoundTrack.prototype.AddSound = function (sound) {
  65417. if (!this._isInitialized) {
  65418. this._initializeSoundTrackAudioGraph();
  65419. }
  65420. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  65421. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  65422. }
  65423. if (sound.soundTrackId) {
  65424. if (sound.soundTrackId === -1) {
  65425. this._scene.mainSoundTrack.RemoveSound(sound);
  65426. }
  65427. else {
  65428. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  65429. }
  65430. }
  65431. this.soundCollection.push(sound);
  65432. sound.soundTrackId = this.id;
  65433. };
  65434. SoundTrack.prototype.RemoveSound = function (sound) {
  65435. var index = this.soundCollection.indexOf(sound);
  65436. if (index !== -1) {
  65437. this.soundCollection.splice(index, 1);
  65438. }
  65439. };
  65440. SoundTrack.prototype.setVolume = function (newVolume) {
  65441. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  65442. this._outputAudioNode.gain.value = newVolume;
  65443. }
  65444. };
  65445. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  65446. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65447. for (var i = 0; i < this.soundCollection.length; i++) {
  65448. this.soundCollection[i].switchPanningModelToHRTF();
  65449. }
  65450. }
  65451. };
  65452. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  65453. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  65454. for (var i = 0; i < this.soundCollection.length; i++) {
  65455. this.soundCollection[i].switchPanningModelToEqualPower();
  65456. }
  65457. }
  65458. };
  65459. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  65460. if (this._connectedAnalyser) {
  65461. this._connectedAnalyser.stopDebugCanvas();
  65462. }
  65463. this._connectedAnalyser = analyser;
  65464. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  65465. this._outputAudioNode.disconnect();
  65466. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  65467. }
  65468. };
  65469. return SoundTrack;
  65470. }());
  65471. BABYLON.SoundTrack = SoundTrack;
  65472. })(BABYLON || (BABYLON = {}));
  65473. //# sourceMappingURL=babylon.soundtrack.js.map
  65474. var BABYLON;
  65475. (function (BABYLON) {
  65476. /**
  65477. * Class used to work with sound analyzer using fast fourier transform (FFT)
  65478. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  65479. */
  65480. var Analyser = /** @class */ (function () {
  65481. /**
  65482. * Creates a new analyser
  65483. * @param scene defines hosting scene
  65484. */
  65485. function Analyser(scene) {
  65486. /**
  65487. * Gets or sets the smoothing
  65488. * @ignorenaming
  65489. */
  65490. this.SMOOTHING = 0.75;
  65491. /**
  65492. * Gets or sets the FFT table size
  65493. * @ignorenaming
  65494. */
  65495. this.FFT_SIZE = 512;
  65496. /**
  65497. * Gets or sets the bar graph amplitude
  65498. * @ignorenaming
  65499. */
  65500. this.BARGRAPHAMPLITUDE = 256;
  65501. /**
  65502. * Gets or sets the position of the debug canvas
  65503. * @ignorenaming
  65504. */
  65505. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  65506. /**
  65507. * Gets or sets the debug canvas size
  65508. * @ignorenaming
  65509. */
  65510. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  65511. this._scene = scene;
  65512. this._audioEngine = BABYLON.Engine.audioEngine;
  65513. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  65514. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  65515. this._webAudioAnalyser.minDecibels = -140;
  65516. this._webAudioAnalyser.maxDecibels = 0;
  65517. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  65518. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  65519. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  65520. }
  65521. }
  65522. /**
  65523. * Get the number of data values you will have to play with for the visualization
  65524. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  65525. * @returns a number
  65526. */
  65527. Analyser.prototype.getFrequencyBinCount = function () {
  65528. if (this._audioEngine.canUseWebAudio) {
  65529. return this._webAudioAnalyser.frequencyBinCount;
  65530. }
  65531. else {
  65532. return 0;
  65533. }
  65534. };
  65535. /**
  65536. * Gets the current frequency data as a byte array
  65537. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  65538. * @returns a Uint8Array
  65539. */
  65540. Analyser.prototype.getByteFrequencyData = function () {
  65541. if (this._audioEngine.canUseWebAudio) {
  65542. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  65543. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  65544. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  65545. }
  65546. return this._byteFreqs;
  65547. };
  65548. /**
  65549. * Gets the current waveform as a byte array
  65550. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  65551. * @returns a Uint8Array
  65552. */
  65553. Analyser.prototype.getByteTimeDomainData = function () {
  65554. if (this._audioEngine.canUseWebAudio) {
  65555. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  65556. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  65557. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  65558. }
  65559. return this._byteTime;
  65560. };
  65561. /**
  65562. * Gets the current frequency data as a float array
  65563. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  65564. * @returns a Float32Array
  65565. */
  65566. Analyser.prototype.getFloatFrequencyData = function () {
  65567. if (this._audioEngine.canUseWebAudio) {
  65568. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  65569. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  65570. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  65571. }
  65572. return this._floatFreqs;
  65573. };
  65574. /**
  65575. * Renders the debug canvas
  65576. */
  65577. Analyser.prototype.drawDebugCanvas = function () {
  65578. var _this = this;
  65579. if (this._audioEngine.canUseWebAudio) {
  65580. if (!this._debugCanvas) {
  65581. this._debugCanvas = document.createElement("canvas");
  65582. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  65583. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  65584. this._debugCanvas.style.position = "absolute";
  65585. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  65586. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  65587. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  65588. document.body.appendChild(this._debugCanvas);
  65589. this._registerFunc = function () {
  65590. _this.drawDebugCanvas();
  65591. };
  65592. this._scene.registerBeforeRender(this._registerFunc);
  65593. }
  65594. if (this._registerFunc && this._debugCanvasContext) {
  65595. var workingArray = this.getByteFrequencyData();
  65596. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  65597. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  65598. // Draw the frequency domain chart.
  65599. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  65600. var value = workingArray[i];
  65601. var percent = value / this.BARGRAPHAMPLITUDE;
  65602. var height = this.DEBUGCANVASSIZE.height * percent;
  65603. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  65604. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  65605. var hue = i / this.getFrequencyBinCount() * 360;
  65606. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  65607. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  65608. }
  65609. }
  65610. }
  65611. };
  65612. /**
  65613. * Stops rendering the debug canvas and removes it
  65614. */
  65615. Analyser.prototype.stopDebugCanvas = function () {
  65616. if (this._debugCanvas) {
  65617. if (this._registerFunc) {
  65618. this._scene.unregisterBeforeRender(this._registerFunc);
  65619. this._registerFunc = null;
  65620. }
  65621. document.body.removeChild(this._debugCanvas);
  65622. this._debugCanvas = null;
  65623. this._debugCanvasContext = null;
  65624. }
  65625. };
  65626. /**
  65627. * Connects two audio nodes
  65628. * @param inputAudioNode defines first node to connect
  65629. * @param outputAudioNode defines second node to connect
  65630. */
  65631. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  65632. if (this._audioEngine.canUseWebAudio) {
  65633. inputAudioNode.connect(this._webAudioAnalyser);
  65634. this._webAudioAnalyser.connect(outputAudioNode);
  65635. }
  65636. };
  65637. /**
  65638. * Releases all associated resources
  65639. */
  65640. Analyser.prototype.dispose = function () {
  65641. if (this._audioEngine.canUseWebAudio) {
  65642. this._webAudioAnalyser.disconnect();
  65643. }
  65644. };
  65645. return Analyser;
  65646. }());
  65647. BABYLON.Analyser = Analyser;
  65648. })(BABYLON || (BABYLON = {}));
  65649. //# sourceMappingURL=babylon.analyser.js.map
  65650. var BABYLON;
  65651. (function (BABYLON) {
  65652. /**
  65653. * Wraps one or more Sound objects and selects one with random weight for playback.
  65654. */
  65655. var WeightedSound = /** @class */ (function () {
  65656. /**
  65657. * Creates a new WeightedSound from the list of sounds given.
  65658. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  65659. * @param sounds Array of Sounds that will be selected from.
  65660. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  65661. */
  65662. function WeightedSound(loop, sounds, weights) {
  65663. var _this = this;
  65664. /** When true a Sound will be selected and played when the current playing Sound completes. */
  65665. this.loop = false;
  65666. this._coneInnerAngle = 360;
  65667. this._coneOuterAngle = 360;
  65668. this._volume = 1;
  65669. /** A Sound is currently playing. */
  65670. this.isPlaying = false;
  65671. /** A Sound is currently paused. */
  65672. this.isPaused = false;
  65673. this._sounds = [];
  65674. this._weights = [];
  65675. if (sounds.length !== weights.length) {
  65676. throw new Error('Sounds length does not equal weights length');
  65677. }
  65678. this.loop = loop;
  65679. this._weights = weights;
  65680. // Normalize the weights
  65681. var weightSum = 0;
  65682. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  65683. var weight = weights_1[_i];
  65684. weightSum += weight;
  65685. }
  65686. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  65687. for (var i = 0; i < this._weights.length; i++) {
  65688. this._weights[i] *= invWeightSum;
  65689. }
  65690. this._sounds = sounds;
  65691. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  65692. var sound = _b[_a];
  65693. sound.onEndedObservable.add(function () { _this._onended(); });
  65694. }
  65695. }
  65696. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  65697. /**
  65698. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  65699. */
  65700. get: function () {
  65701. return this._coneInnerAngle;
  65702. },
  65703. /**
  65704. * The size of cone in degress for a directional sound in which there will be no attenuation.
  65705. */
  65706. set: function (value) {
  65707. if (value !== this._coneInnerAngle) {
  65708. if (this._coneOuterAngle < value) {
  65709. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  65710. return;
  65711. }
  65712. this._coneInnerAngle = value;
  65713. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  65714. var sound = _a[_i];
  65715. sound.directionalConeInnerAngle = value;
  65716. }
  65717. }
  65718. },
  65719. enumerable: true,
  65720. configurable: true
  65721. });
  65722. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  65723. /**
  65724. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  65725. * Listener angles between innerAngle and outerAngle will falloff linearly.
  65726. */
  65727. get: function () {
  65728. return this._coneOuterAngle;
  65729. },
  65730. /**
  65731. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  65732. * Listener angles between innerAngle and outerAngle will falloff linearly.
  65733. */
  65734. set: function (value) {
  65735. if (value !== this._coneOuterAngle) {
  65736. if (value < this._coneInnerAngle) {
  65737. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  65738. return;
  65739. }
  65740. this._coneOuterAngle = value;
  65741. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  65742. var sound = _a[_i];
  65743. sound.directionalConeOuterAngle = value;
  65744. }
  65745. }
  65746. },
  65747. enumerable: true,
  65748. configurable: true
  65749. });
  65750. Object.defineProperty(WeightedSound.prototype, "volume", {
  65751. /**
  65752. * Playback volume.
  65753. */
  65754. get: function () {
  65755. return this._volume;
  65756. },
  65757. /**
  65758. * Playback volume.
  65759. */
  65760. set: function (value) {
  65761. if (value !== this._volume) {
  65762. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  65763. var sound = _a[_i];
  65764. sound.setVolume(value);
  65765. }
  65766. }
  65767. },
  65768. enumerable: true,
  65769. configurable: true
  65770. });
  65771. WeightedSound.prototype._onended = function () {
  65772. if (this._currentIndex !== undefined) {
  65773. this._sounds[this._currentIndex].autoplay = false;
  65774. }
  65775. if (this.loop && this.isPlaying) {
  65776. this.play();
  65777. }
  65778. else {
  65779. this.isPlaying = false;
  65780. }
  65781. };
  65782. /**
  65783. * Suspend playback
  65784. */
  65785. WeightedSound.prototype.pause = function () {
  65786. this.isPaused = true;
  65787. if (this._currentIndex !== undefined) {
  65788. this._sounds[this._currentIndex].pause();
  65789. }
  65790. };
  65791. /**
  65792. * Stop playback
  65793. */
  65794. WeightedSound.prototype.stop = function () {
  65795. this.isPlaying = false;
  65796. if (this._currentIndex !== undefined) {
  65797. this._sounds[this._currentIndex].stop();
  65798. }
  65799. };
  65800. /**
  65801. * Start playback.
  65802. * @param startOffset Position the clip head at a specific time in seconds.
  65803. */
  65804. WeightedSound.prototype.play = function (startOffset) {
  65805. if (!this.isPaused) {
  65806. this.stop();
  65807. var randomValue = Math.random();
  65808. var total = 0;
  65809. for (var i = 0; i < this._weights.length; i++) {
  65810. total += this._weights[i];
  65811. if (randomValue <= total) {
  65812. this._currentIndex = i;
  65813. break;
  65814. }
  65815. }
  65816. }
  65817. var sound = this._sounds[this._currentIndex];
  65818. if (sound.isReady()) {
  65819. sound.play(0, this.isPaused ? undefined : startOffset);
  65820. }
  65821. else {
  65822. sound.autoplay = true;
  65823. }
  65824. this.isPlaying = true;
  65825. this.isPaused = false;
  65826. };
  65827. return WeightedSound;
  65828. }());
  65829. BABYLON.WeightedSound = WeightedSound;
  65830. })(BABYLON || (BABYLON = {}));
  65831. //# sourceMappingURL=babylon.weightedsound.js.map
  65832. var BABYLON;
  65833. (function (BABYLON) {
  65834. var CubeTexture = /** @class */ (function (_super) {
  65835. __extends(CubeTexture, _super);
  65836. /**
  65837. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  65838. * as prefiltered data.
  65839. * @param rootUrl defines the url of the texture or the root name of the six images
  65840. * @param scene defines the scene the texture is attached to
  65841. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  65842. * @param noMipmap defines if mipmaps should be created or not
  65843. * @param files defines the six files to load for the different faces
  65844. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  65845. * @param onError defines a callback triggered in case of error during load
  65846. * @param format defines the internal format to use for the texture once loaded
  65847. * @param prefiltered defines whether or not the texture is created from prefiltered data
  65848. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  65849. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  65850. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  65851. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  65852. * @return the cube texture
  65853. */
  65854. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  65855. if (extensions === void 0) { extensions = null; }
  65856. if (noMipmap === void 0) { noMipmap = false; }
  65857. if (files === void 0) { files = null; }
  65858. if (onLoad === void 0) { onLoad = null; }
  65859. if (onError === void 0) { onError = null; }
  65860. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  65861. if (prefiltered === void 0) { prefiltered = false; }
  65862. if (forcedExtension === void 0) { forcedExtension = null; }
  65863. if (createPolynomials === void 0) { createPolynomials = false; }
  65864. if (lodScale === void 0) { lodScale = 0.8; }
  65865. if (lodOffset === void 0) { lodOffset = 0; }
  65866. var _this = _super.call(this, scene) || this;
  65867. /**
  65868. * Gets or sets the center of the bounding box associated with the cube texture
  65869. * It must define where the camera used to render the texture was set
  65870. */
  65871. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  65872. _this._rotationY = 0;
  65873. /** @hidden */
  65874. _this._prefiltered = false;
  65875. _this.name = rootUrl;
  65876. _this.url = rootUrl;
  65877. _this._noMipmap = noMipmap;
  65878. _this.hasAlpha = false;
  65879. _this._format = format;
  65880. _this.isCube = true;
  65881. _this._textureMatrix = BABYLON.Matrix.Identity();
  65882. _this._createPolynomials = createPolynomials;
  65883. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  65884. if (!rootUrl && !files) {
  65885. return _this;
  65886. }
  65887. var lastDot = rootUrl.lastIndexOf(".");
  65888. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  65889. var isDDS = (extension === ".dds");
  65890. var isEnv = (extension === ".env");
  65891. if (isEnv) {
  65892. _this.gammaSpace = false;
  65893. _this._prefiltered = false;
  65894. }
  65895. else {
  65896. _this._prefiltered = prefiltered;
  65897. if (prefiltered) {
  65898. _this.gammaSpace = false;
  65899. }
  65900. }
  65901. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  65902. if (!files) {
  65903. if (!isEnv && !isDDS && !extensions) {
  65904. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  65905. }
  65906. files = [];
  65907. if (extensions) {
  65908. for (var index = 0; index < extensions.length; index++) {
  65909. files.push(rootUrl + extensions[index]);
  65910. }
  65911. }
  65912. }
  65913. _this._files = files;
  65914. if (!_this._texture) {
  65915. if (!scene.useDelayedTextureLoading) {
  65916. if (prefiltered) {
  65917. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  65918. }
  65919. else {
  65920. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  65921. }
  65922. }
  65923. else {
  65924. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  65925. }
  65926. }
  65927. else if (onLoad) {
  65928. if (_this._texture.isReady) {
  65929. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  65930. }
  65931. else {
  65932. _this._texture.onLoadedObservable.add(onLoad);
  65933. }
  65934. }
  65935. return _this;
  65936. }
  65937. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  65938. get: function () {
  65939. return this._boundingBoxSize;
  65940. },
  65941. /**
  65942. * Gets or sets the size of the bounding box associated with the cube texture
  65943. * When defined, the cubemap will switch to local mode
  65944. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  65945. * @example https://www.babylonjs-playground.com/#RNASML
  65946. */
  65947. set: function (value) {
  65948. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  65949. return;
  65950. }
  65951. this._boundingBoxSize = value;
  65952. var scene = this.getScene();
  65953. if (scene) {
  65954. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  65955. }
  65956. },
  65957. enumerable: true,
  65958. configurable: true
  65959. });
  65960. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  65961. /**
  65962. * Gets texture matrix rotation angle around Y axis radians.
  65963. */
  65964. get: function () {
  65965. return this._rotationY;
  65966. },
  65967. /**
  65968. * Sets texture matrix rotation angle around Y axis in radians.
  65969. */
  65970. set: function (value) {
  65971. this._rotationY = value;
  65972. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  65973. },
  65974. enumerable: true,
  65975. configurable: true
  65976. });
  65977. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  65978. var rootUrlKey = "";
  65979. files.forEach(function (url) { return rootUrlKey += url; });
  65980. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  65981. };
  65982. /**
  65983. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  65984. * @param url defines the url of the prefiltered texture
  65985. * @param scene defines the scene the texture is attached to
  65986. * @param forcedExtension defines the extension of the file if different from the url
  65987. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  65988. * @return the prefiltered texture
  65989. */
  65990. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  65991. if (forcedExtension === void 0) { forcedExtension = null; }
  65992. if (createPolynomials === void 0) { createPolynomials = true; }
  65993. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  65994. };
  65995. // Methods
  65996. CubeTexture.prototype.delayLoad = function () {
  65997. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  65998. return;
  65999. }
  66000. var scene = this.getScene();
  66001. if (!scene) {
  66002. return;
  66003. }
  66004. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  66005. this._texture = this._getFromCache(this.url, this._noMipmap);
  66006. if (!this._texture) {
  66007. if (this._prefiltered) {
  66008. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  66009. }
  66010. else {
  66011. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  66012. }
  66013. }
  66014. };
  66015. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  66016. return this._textureMatrix;
  66017. };
  66018. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  66019. this._textureMatrix = value;
  66020. };
  66021. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  66022. var texture = BABYLON.SerializationHelper.Parse(function () {
  66023. var prefiltered = false;
  66024. if (parsedTexture.prefiltered) {
  66025. prefiltered = parsedTexture.prefiltered;
  66026. }
  66027. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  66028. }, parsedTexture, scene);
  66029. // Local Cubemaps
  66030. if (parsedTexture.boundingBoxPosition) {
  66031. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  66032. }
  66033. if (parsedTexture.boundingBoxSize) {
  66034. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  66035. }
  66036. // Animations
  66037. if (parsedTexture.animations) {
  66038. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  66039. var parsedAnimation = parsedTexture.animations[animationIndex];
  66040. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  66041. }
  66042. }
  66043. return texture;
  66044. };
  66045. CubeTexture.prototype.clone = function () {
  66046. var _this = this;
  66047. return BABYLON.SerializationHelper.Clone(function () {
  66048. var scene = _this.getScene();
  66049. if (!scene) {
  66050. return _this;
  66051. }
  66052. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  66053. }, this);
  66054. };
  66055. __decorate([
  66056. BABYLON.serialize("rotationY")
  66057. ], CubeTexture.prototype, "_rotationY", void 0);
  66058. return CubeTexture;
  66059. }(BABYLON.BaseTexture));
  66060. BABYLON.CubeTexture = CubeTexture;
  66061. })(BABYLON || (BABYLON = {}));
  66062. //# sourceMappingURL=babylon.cubeTexture.js.map
  66063. var BABYLON;
  66064. (function (BABYLON) {
  66065. /**
  66066. * Raw cube texture where the raw buffers are passed in
  66067. */
  66068. var RawCubeTexture = /** @class */ (function (_super) {
  66069. __extends(RawCubeTexture, _super);
  66070. /**
  66071. * Creates a cube texture where the raw buffers are passed in.
  66072. * @param scene defines the scene the texture is attached to
  66073. * @param data defines the array of data to use to create each face
  66074. * @param size defines the size of the textures
  66075. * @param format defines the format of the data
  66076. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  66077. * @param generateMipMaps defines if the engine should generate the mip levels
  66078. * @param invertY defines if data must be stored with Y axis inverted
  66079. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  66080. * @param compression defines the compression used (null by default)
  66081. */
  66082. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  66083. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  66084. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66085. if (generateMipMaps === void 0) { generateMipMaps = false; }
  66086. if (invertY === void 0) { invertY = false; }
  66087. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66088. if (compression === void 0) { compression = null; }
  66089. var _this = _super.call(this, "", scene) || this;
  66090. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  66091. return _this;
  66092. }
  66093. /**
  66094. * Updates the raw cube texture.
  66095. * @param data defines the data to store
  66096. * @param format defines the data format
  66097. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  66098. * @param invertY defines if data must be stored with Y axis inverted
  66099. * @param compression defines the compression used (null by default)
  66100. * @param level defines which level of the texture to update
  66101. */
  66102. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  66103. if (compression === void 0) { compression = null; }
  66104. if (level === void 0) { level = 0; }
  66105. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  66106. };
  66107. /**
  66108. * Updates a raw cube texture with RGBD encoded data.
  66109. * @param data defines the array of data [mipmap][face] to use to create each face
  66110. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  66111. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  66112. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  66113. * @returns a promsie that resolves when the operation is complete
  66114. */
  66115. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  66116. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  66117. if (lodScale === void 0) { lodScale = 0.8; }
  66118. if (lodOffset === void 0) { lodOffset = 0; }
  66119. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  66120. };
  66121. /**
  66122. * Clones the raw cube texture.
  66123. * @return a new cube texture
  66124. */
  66125. RawCubeTexture.prototype.clone = function () {
  66126. var _this = this;
  66127. return BABYLON.SerializationHelper.Clone(function () {
  66128. var scene = _this.getScene();
  66129. var internalTexture = _this._texture;
  66130. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  66131. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  66132. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  66133. }
  66134. return texture;
  66135. }, this);
  66136. };
  66137. /** @hidden */
  66138. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  66139. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  66140. internalTexture._bufferViewArrayArray = data;
  66141. internalTexture._lodGenerationScale = lodScale;
  66142. internalTexture._lodGenerationOffset = lodOffset;
  66143. internalTexture._sphericalPolynomial = sphericalPolynomial;
  66144. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  66145. internalTexture.isReady = true;
  66146. });
  66147. };
  66148. return RawCubeTexture;
  66149. }(BABYLON.CubeTexture));
  66150. BABYLON.RawCubeTexture = RawCubeTexture;
  66151. })(BABYLON || (BABYLON = {}));
  66152. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  66153. var BABYLON;
  66154. (function (BABYLON) {
  66155. var RenderTargetTexture = /** @class */ (function (_super) {
  66156. __extends(RenderTargetTexture, _super);
  66157. /**
  66158. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  66159. * or used a shadow, depth texture...
  66160. * @param name The friendly name of the texture
  66161. * @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)
  66162. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  66163. * @param generateMipMaps True if mip maps need to be generated after render.
  66164. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  66165. * @param type The type of the buffer in the RTT (int, half float, float...)
  66166. * @param isCube True if a cube texture needs to be created
  66167. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  66168. * @param generateDepthBuffer True to generate a depth buffer
  66169. * @param generateStencilBuffer True to generate a stencil buffer
  66170. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  66171. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  66172. */
  66173. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  66174. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  66175. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66176. if (isCube === void 0) { isCube = false; }
  66177. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  66178. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  66179. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  66180. if (isMulti === void 0) { isMulti = false; }
  66181. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  66182. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  66183. _this.isCube = isCube;
  66184. _this.renderParticles = true;
  66185. _this.renderSprites = false;
  66186. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  66187. _this.ignoreCameraViewport = false;
  66188. // Events
  66189. /**
  66190. * An event triggered when the texture is unbind.
  66191. */
  66192. _this.onBeforeBindObservable = new BABYLON.Observable();
  66193. /**
  66194. * An event triggered when the texture is unbind.
  66195. */
  66196. _this.onAfterUnbindObservable = new BABYLON.Observable();
  66197. /**
  66198. * An event triggered before rendering the texture
  66199. */
  66200. _this.onBeforeRenderObservable = new BABYLON.Observable();
  66201. /**
  66202. * An event triggered after rendering the texture
  66203. */
  66204. _this.onAfterRenderObservable = new BABYLON.Observable();
  66205. /**
  66206. * An event triggered after the texture clear
  66207. */
  66208. _this.onClearObservable = new BABYLON.Observable();
  66209. _this._currentRefreshId = -1;
  66210. _this._refreshRate = 1;
  66211. _this._samples = 1;
  66212. /**
  66213. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  66214. * It must define where the camera used to render the texture is set
  66215. */
  66216. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  66217. scene = _this.getScene();
  66218. if (!scene) {
  66219. return _this;
  66220. }
  66221. _this.renderList = new Array();
  66222. _this._engine = scene.getEngine();
  66223. _this.name = name;
  66224. _this.isRenderTarget = true;
  66225. _this._initialSizeParameter = size;
  66226. _this._processSizeParameter(size);
  66227. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  66228. });
  66229. _this._generateMipMaps = generateMipMaps ? true : false;
  66230. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  66231. // Rendering groups
  66232. _this._renderingManager = new BABYLON.RenderingManager(scene);
  66233. _this._renderingManager._useSceneAutoClearSetup = true;
  66234. if (isMulti) {
  66235. return _this;
  66236. }
  66237. _this._renderTargetOptions = {
  66238. generateMipMaps: generateMipMaps,
  66239. type: type,
  66240. format: format,
  66241. samplingMode: samplingMode,
  66242. generateDepthBuffer: generateDepthBuffer,
  66243. generateStencilBuffer: generateStencilBuffer
  66244. };
  66245. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  66246. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66247. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66248. }
  66249. if (isCube) {
  66250. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  66251. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  66252. _this._textureMatrix = BABYLON.Matrix.Identity();
  66253. }
  66254. else {
  66255. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  66256. }
  66257. return _this;
  66258. }
  66259. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  66260. get: function () {
  66261. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  66262. },
  66263. enumerable: true,
  66264. configurable: true
  66265. });
  66266. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  66267. get: function () {
  66268. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  66269. },
  66270. enumerable: true,
  66271. configurable: true
  66272. });
  66273. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  66274. get: function () {
  66275. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  66276. },
  66277. enumerable: true,
  66278. configurable: true
  66279. });
  66280. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  66281. /**
  66282. * Use this list to define the list of mesh you want to render.
  66283. */
  66284. get: function () {
  66285. return this._renderList;
  66286. },
  66287. set: function (value) {
  66288. this._renderList = value;
  66289. if (this._renderList) {
  66290. this._hookArray(this._renderList);
  66291. }
  66292. },
  66293. enumerable: true,
  66294. configurable: true
  66295. });
  66296. RenderTargetTexture.prototype._hookArray = function (array) {
  66297. var _this = this;
  66298. var oldPush = array.push;
  66299. array.push = function () {
  66300. var items = [];
  66301. for (var _i = 0; _i < arguments.length; _i++) {
  66302. items[_i] = arguments[_i];
  66303. }
  66304. var result = oldPush.apply(array, items);
  66305. _this.getScene().meshes.forEach(function (mesh) {
  66306. mesh._markSubMeshesAsLightDirty();
  66307. });
  66308. return result;
  66309. };
  66310. var oldSplice = array.splice;
  66311. array.splice = function (index, deleteCount) {
  66312. var deleted = oldSplice.apply(array, [index, deleteCount]);
  66313. _this.getScene().meshes.forEach(function (mesh) {
  66314. mesh._markSubMeshesAsLightDirty();
  66315. });
  66316. return deleted;
  66317. };
  66318. };
  66319. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  66320. set: function (callback) {
  66321. if (this._onAfterUnbindObserver) {
  66322. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  66323. }
  66324. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  66325. },
  66326. enumerable: true,
  66327. configurable: true
  66328. });
  66329. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  66330. set: function (callback) {
  66331. if (this._onBeforeRenderObserver) {
  66332. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  66333. }
  66334. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  66335. },
  66336. enumerable: true,
  66337. configurable: true
  66338. });
  66339. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  66340. set: function (callback) {
  66341. if (this._onAfterRenderObserver) {
  66342. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  66343. }
  66344. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  66345. },
  66346. enumerable: true,
  66347. configurable: true
  66348. });
  66349. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  66350. set: function (callback) {
  66351. if (this._onClearObserver) {
  66352. this.onClearObservable.remove(this._onClearObserver);
  66353. }
  66354. this._onClearObserver = this.onClearObservable.add(callback);
  66355. },
  66356. enumerable: true,
  66357. configurable: true
  66358. });
  66359. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  66360. get: function () {
  66361. return this._renderTargetOptions;
  66362. },
  66363. enumerable: true,
  66364. configurable: true
  66365. });
  66366. RenderTargetTexture.prototype._onRatioRescale = function () {
  66367. if (this._sizeRatio) {
  66368. this.resize(this._initialSizeParameter);
  66369. }
  66370. };
  66371. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  66372. get: function () {
  66373. return this._boundingBoxSize;
  66374. },
  66375. /**
  66376. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  66377. * When defined, the cubemap will switch to local mode
  66378. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  66379. * @example https://www.babylonjs-playground.com/#RNASML
  66380. */
  66381. set: function (value) {
  66382. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  66383. return;
  66384. }
  66385. this._boundingBoxSize = value;
  66386. var scene = this.getScene();
  66387. if (scene) {
  66388. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  66389. }
  66390. },
  66391. enumerable: true,
  66392. configurable: true
  66393. });
  66394. /**
  66395. * Creates a depth stencil texture.
  66396. * This is only available in WebGL 2 or with the depth texture extension available.
  66397. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  66398. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  66399. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  66400. */
  66401. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  66402. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  66403. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  66404. if (generateStencil === void 0) { generateStencil = false; }
  66405. if (!this.getScene()) {
  66406. return;
  66407. }
  66408. var engine = this.getScene().getEngine();
  66409. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  66410. bilinearFiltering: bilinearFiltering,
  66411. comparisonFunction: comparisonFunction,
  66412. generateStencil: generateStencil,
  66413. isCube: this.isCube
  66414. });
  66415. engine.setFrameBufferDepthStencilTexture(this);
  66416. };
  66417. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  66418. if (size.ratio) {
  66419. this._sizeRatio = size.ratio;
  66420. this._size = {
  66421. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  66422. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  66423. };
  66424. }
  66425. else {
  66426. this._size = size;
  66427. }
  66428. };
  66429. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  66430. get: function () {
  66431. return this._samples;
  66432. },
  66433. set: function (value) {
  66434. if (this._samples === value) {
  66435. return;
  66436. }
  66437. var scene = this.getScene();
  66438. if (!scene) {
  66439. return;
  66440. }
  66441. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  66442. },
  66443. enumerable: true,
  66444. configurable: true
  66445. });
  66446. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  66447. this._currentRefreshId = -1;
  66448. };
  66449. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  66450. get: function () {
  66451. return this._refreshRate;
  66452. },
  66453. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  66454. set: function (value) {
  66455. this._refreshRate = value;
  66456. this.resetRefreshCounter();
  66457. },
  66458. enumerable: true,
  66459. configurable: true
  66460. });
  66461. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  66462. if (!this._postProcessManager) {
  66463. var scene = this.getScene();
  66464. if (!scene) {
  66465. return;
  66466. }
  66467. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  66468. this._postProcesses = new Array();
  66469. }
  66470. this._postProcesses.push(postProcess);
  66471. this._postProcesses[0].autoClear = false;
  66472. };
  66473. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  66474. if (!this._postProcesses) {
  66475. return;
  66476. }
  66477. if (dispose) {
  66478. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  66479. var postProcess = _a[_i];
  66480. postProcess.dispose();
  66481. }
  66482. }
  66483. this._postProcesses = [];
  66484. };
  66485. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  66486. if (!this._postProcesses) {
  66487. return;
  66488. }
  66489. var index = this._postProcesses.indexOf(postProcess);
  66490. if (index === -1) {
  66491. return;
  66492. }
  66493. this._postProcesses.splice(index, 1);
  66494. if (this._postProcesses.length > 0) {
  66495. this._postProcesses[0].autoClear = false;
  66496. }
  66497. };
  66498. /** @hidden */
  66499. RenderTargetTexture.prototype._shouldRender = function () {
  66500. if (this._currentRefreshId === -1) { // At least render once
  66501. this._currentRefreshId = 1;
  66502. return true;
  66503. }
  66504. if (this.refreshRate === this._currentRefreshId) {
  66505. this._currentRefreshId = 1;
  66506. return true;
  66507. }
  66508. this._currentRefreshId++;
  66509. return false;
  66510. };
  66511. RenderTargetTexture.prototype.getRenderSize = function () {
  66512. if (this._size.width) {
  66513. return this._size.width;
  66514. }
  66515. return this._size;
  66516. };
  66517. RenderTargetTexture.prototype.getRenderWidth = function () {
  66518. if (this._size.width) {
  66519. return this._size.width;
  66520. }
  66521. return this._size;
  66522. };
  66523. RenderTargetTexture.prototype.getRenderHeight = function () {
  66524. if (this._size.width) {
  66525. return this._size.height;
  66526. }
  66527. return this._size;
  66528. };
  66529. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  66530. get: function () {
  66531. return true;
  66532. },
  66533. enumerable: true,
  66534. configurable: true
  66535. });
  66536. RenderTargetTexture.prototype.scale = function (ratio) {
  66537. var newSize = this.getRenderSize() * ratio;
  66538. this.resize(newSize);
  66539. };
  66540. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  66541. if (this.isCube) {
  66542. return this._textureMatrix;
  66543. }
  66544. return _super.prototype.getReflectionTextureMatrix.call(this);
  66545. };
  66546. RenderTargetTexture.prototype.resize = function (size) {
  66547. this.releaseInternalTexture();
  66548. var scene = this.getScene();
  66549. if (!scene) {
  66550. return;
  66551. }
  66552. this._processSizeParameter(size);
  66553. if (this.isCube) {
  66554. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  66555. }
  66556. else {
  66557. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  66558. }
  66559. };
  66560. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  66561. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  66562. if (dumpForDebug === void 0) { dumpForDebug = false; }
  66563. var scene = this.getScene();
  66564. if (!scene) {
  66565. return;
  66566. }
  66567. var engine = scene.getEngine();
  66568. if (this.useCameraPostProcesses !== undefined) {
  66569. useCameraPostProcess = this.useCameraPostProcesses;
  66570. }
  66571. if (this._waitingRenderList) {
  66572. this.renderList = [];
  66573. for (var index = 0; index < this._waitingRenderList.length; index++) {
  66574. var id = this._waitingRenderList[index];
  66575. var mesh_1 = scene.getMeshByID(id);
  66576. if (mesh_1) {
  66577. this.renderList.push(mesh_1);
  66578. }
  66579. }
  66580. delete this._waitingRenderList;
  66581. }
  66582. // Is predicate defined?
  66583. if (this.renderListPredicate) {
  66584. if (this.renderList) {
  66585. this.renderList.splice(0); // Clear previous renderList
  66586. }
  66587. else {
  66588. this.renderList = [];
  66589. }
  66590. var scene = this.getScene();
  66591. if (!scene) {
  66592. return;
  66593. }
  66594. var sceneMeshes = scene.meshes;
  66595. for (var index = 0; index < sceneMeshes.length; index++) {
  66596. var mesh = sceneMeshes[index];
  66597. if (this.renderListPredicate(mesh)) {
  66598. this.renderList.push(mesh);
  66599. }
  66600. }
  66601. }
  66602. this.onBeforeBindObservable.notifyObservers(this);
  66603. // Set custom projection.
  66604. // Needs to be before binding to prevent changing the aspect ratio.
  66605. var camera;
  66606. if (this.activeCamera) {
  66607. camera = this.activeCamera;
  66608. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  66609. if (this.activeCamera !== scene.activeCamera) {
  66610. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  66611. }
  66612. }
  66613. else {
  66614. camera = scene.activeCamera;
  66615. if (camera) {
  66616. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  66617. }
  66618. }
  66619. // Prepare renderingManager
  66620. this._renderingManager.reset();
  66621. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  66622. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  66623. var sceneRenderId = scene.getRenderId();
  66624. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  66625. var mesh = currentRenderList[meshIndex];
  66626. if (mesh) {
  66627. if (!mesh.isReady(this.refreshRate === 0)) {
  66628. this.resetRefreshCounter();
  66629. continue;
  66630. }
  66631. mesh._preActivateForIntermediateRendering(sceneRenderId);
  66632. var isMasked = void 0;
  66633. if (!this.renderList && camera) {
  66634. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  66635. }
  66636. else {
  66637. isMasked = false;
  66638. }
  66639. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  66640. mesh._activate(sceneRenderId);
  66641. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  66642. var subMesh = mesh.subMeshes[subIndex];
  66643. scene._activeIndices.addCount(subMesh.indexCount, false);
  66644. this._renderingManager.dispatch(subMesh, mesh);
  66645. }
  66646. }
  66647. }
  66648. }
  66649. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  66650. var particleSystem = scene.particleSystems[particleIndex];
  66651. var emitter = particleSystem.emitter;
  66652. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  66653. continue;
  66654. }
  66655. if (currentRenderList.indexOf(emitter) >= 0) {
  66656. this._renderingManager.dispatchParticles(particleSystem);
  66657. }
  66658. }
  66659. if (this.isCube) {
  66660. for (var face = 0; face < 6; face++) {
  66661. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  66662. scene.incrementRenderId();
  66663. scene.resetCachedMaterial();
  66664. }
  66665. }
  66666. else {
  66667. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  66668. }
  66669. this.onAfterUnbindObservable.notifyObservers(this);
  66670. if (scene.activeCamera) {
  66671. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  66672. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  66673. }
  66674. engine.setViewport(scene.activeCamera.viewport);
  66675. }
  66676. scene.resetCachedMaterial();
  66677. };
  66678. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  66679. var minimum = 128;
  66680. var x = renderDimension * scale;
  66681. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  66682. // Ensure we don't exceed the render dimension (while staying POT)
  66683. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  66684. };
  66685. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  66686. var _this = this;
  66687. if (!this._texture) {
  66688. return;
  66689. }
  66690. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  66691. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  66692. });
  66693. };
  66694. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  66695. var scene = this.getScene();
  66696. if (!scene) {
  66697. return;
  66698. }
  66699. var engine = scene.getEngine();
  66700. if (!this._texture) {
  66701. return;
  66702. }
  66703. // Bind
  66704. if (this._postProcessManager) {
  66705. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  66706. }
  66707. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  66708. if (this._texture) {
  66709. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  66710. }
  66711. }
  66712. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  66713. // Clear
  66714. if (this.onClearObservable.hasObservers()) {
  66715. this.onClearObservable.notifyObservers(engine);
  66716. }
  66717. else {
  66718. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  66719. }
  66720. if (!this._doNotChangeAspectRatio) {
  66721. scene.updateTransformMatrix(true);
  66722. }
  66723. // Render
  66724. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  66725. if (this._postProcessManager) {
  66726. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  66727. }
  66728. else if (useCameraPostProcess) {
  66729. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  66730. }
  66731. if (!this._doNotChangeAspectRatio) {
  66732. scene.updateTransformMatrix(true);
  66733. }
  66734. // Dump ?
  66735. if (dumpForDebug) {
  66736. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  66737. }
  66738. // Unbind
  66739. if (!this.isCube || faceIndex === 5) {
  66740. if (this.isCube) {
  66741. if (faceIndex === 5) {
  66742. engine.generateMipMapsForCubemap(this._texture);
  66743. }
  66744. }
  66745. this.unbindFrameBuffer(engine, faceIndex);
  66746. }
  66747. else {
  66748. this.onAfterRenderObservable.notifyObservers(faceIndex);
  66749. }
  66750. };
  66751. /**
  66752. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  66753. * This allowed control for front to back rendering or reversly depending of the special needs.
  66754. *
  66755. * @param renderingGroupId The rendering group id corresponding to its index
  66756. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  66757. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  66758. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  66759. */
  66760. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  66761. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  66762. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  66763. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  66764. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  66765. };
  66766. /**
  66767. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  66768. *
  66769. * @param renderingGroupId The rendering group id corresponding to its index
  66770. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  66771. */
  66772. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  66773. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  66774. this._renderingManager._useSceneAutoClearSetup = false;
  66775. };
  66776. RenderTargetTexture.prototype.clone = function () {
  66777. var textureSize = this.getSize();
  66778. 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);
  66779. // Base texture
  66780. newTexture.hasAlpha = this.hasAlpha;
  66781. newTexture.level = this.level;
  66782. // RenderTarget Texture
  66783. newTexture.coordinatesMode = this.coordinatesMode;
  66784. if (this.renderList) {
  66785. newTexture.renderList = this.renderList.slice(0);
  66786. }
  66787. return newTexture;
  66788. };
  66789. RenderTargetTexture.prototype.serialize = function () {
  66790. if (!this.name) {
  66791. return null;
  66792. }
  66793. var serializationObject = _super.prototype.serialize.call(this);
  66794. serializationObject.renderTargetSize = this.getRenderSize();
  66795. serializationObject.renderList = [];
  66796. if (this.renderList) {
  66797. for (var index = 0; index < this.renderList.length; index++) {
  66798. serializationObject.renderList.push(this.renderList[index].id);
  66799. }
  66800. }
  66801. return serializationObject;
  66802. };
  66803. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  66804. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  66805. var objBuffer = this.getInternalTexture();
  66806. var scene = this.getScene();
  66807. if (objBuffer && scene) {
  66808. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  66809. }
  66810. };
  66811. RenderTargetTexture.prototype.dispose = function () {
  66812. if (this._postProcessManager) {
  66813. this._postProcessManager.dispose();
  66814. this._postProcessManager = null;
  66815. }
  66816. this.clearPostProcesses(true);
  66817. if (this._resizeObserver) {
  66818. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  66819. this._resizeObserver = null;
  66820. }
  66821. this.renderList = null;
  66822. // Remove from custom render targets
  66823. var scene = this.getScene();
  66824. if (!scene) {
  66825. return;
  66826. }
  66827. var index = scene.customRenderTargets.indexOf(this);
  66828. if (index >= 0) {
  66829. scene.customRenderTargets.splice(index, 1);
  66830. }
  66831. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  66832. var camera = _a[_i];
  66833. index = camera.customRenderTargets.indexOf(this);
  66834. if (index >= 0) {
  66835. camera.customRenderTargets.splice(index, 1);
  66836. }
  66837. }
  66838. _super.prototype.dispose.call(this);
  66839. };
  66840. /** @hidden */
  66841. RenderTargetTexture.prototype._rebuild = function () {
  66842. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  66843. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  66844. }
  66845. if (this._postProcessManager) {
  66846. this._postProcessManager._rebuild();
  66847. }
  66848. };
  66849. /**
  66850. * Clear the info related to rendering groups preventing retention point in material dispose.
  66851. */
  66852. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  66853. if (this._renderingManager) {
  66854. this._renderingManager.freeRenderingGroups();
  66855. }
  66856. };
  66857. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  66858. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  66859. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  66860. return RenderTargetTexture;
  66861. }(BABYLON.Texture));
  66862. BABYLON.RenderTargetTexture = RenderTargetTexture;
  66863. })(BABYLON || (BABYLON = {}));
  66864. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  66865. var BABYLON;
  66866. (function (BABYLON) {
  66867. ;
  66868. var MultiRenderTarget = /** @class */ (function (_super) {
  66869. __extends(MultiRenderTarget, _super);
  66870. function MultiRenderTarget(name, size, count, scene, options) {
  66871. var _this = this;
  66872. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  66873. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  66874. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  66875. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  66876. _this._engine = scene.getEngine();
  66877. if (!_this.isSupported) {
  66878. _this.dispose();
  66879. return;
  66880. }
  66881. var types = [];
  66882. var samplingModes = [];
  66883. for (var i = 0; i < count; i++) {
  66884. if (options && options.types && options.types[i] !== undefined) {
  66885. types.push(options.types[i]);
  66886. }
  66887. else {
  66888. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  66889. }
  66890. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  66891. samplingModes.push(options.samplingModes[i]);
  66892. }
  66893. else {
  66894. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66895. }
  66896. }
  66897. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  66898. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  66899. _this._size = size;
  66900. _this._multiRenderTargetOptions = {
  66901. samplingModes: samplingModes,
  66902. generateMipMaps: generateMipMaps,
  66903. generateDepthBuffer: generateDepthBuffer,
  66904. generateStencilBuffer: generateStencilBuffer,
  66905. generateDepthTexture: generateDepthTexture,
  66906. types: types,
  66907. textureCount: count
  66908. };
  66909. _this._createInternalTextures();
  66910. _this._createTextures();
  66911. return _this;
  66912. }
  66913. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  66914. get: function () {
  66915. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  66916. },
  66917. enumerable: true,
  66918. configurable: true
  66919. });
  66920. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  66921. get: function () {
  66922. return this._textures;
  66923. },
  66924. enumerable: true,
  66925. configurable: true
  66926. });
  66927. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  66928. get: function () {
  66929. return this._textures[this._textures.length - 1];
  66930. },
  66931. enumerable: true,
  66932. configurable: true
  66933. });
  66934. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  66935. set: function (wrap) {
  66936. if (this._textures) {
  66937. for (var i = 0; i < this._textures.length; i++) {
  66938. this._textures[i].wrapU = wrap;
  66939. }
  66940. }
  66941. },
  66942. enumerable: true,
  66943. configurable: true
  66944. });
  66945. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  66946. set: function (wrap) {
  66947. if (this._textures) {
  66948. for (var i = 0; i < this._textures.length; i++) {
  66949. this._textures[i].wrapV = wrap;
  66950. }
  66951. }
  66952. },
  66953. enumerable: true,
  66954. configurable: true
  66955. });
  66956. /** @hidden */
  66957. MultiRenderTarget.prototype._rebuild = function () {
  66958. this.releaseInternalTextures();
  66959. this._createInternalTextures();
  66960. for (var i = 0; i < this._internalTextures.length; i++) {
  66961. var texture = this._textures[i];
  66962. texture._texture = this._internalTextures[i];
  66963. }
  66964. // Keeps references to frame buffer and stencil/depth buffer
  66965. this._texture = this._internalTextures[0];
  66966. };
  66967. MultiRenderTarget.prototype._createInternalTextures = function () {
  66968. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  66969. };
  66970. MultiRenderTarget.prototype._createTextures = function () {
  66971. this._textures = [];
  66972. for (var i = 0; i < this._internalTextures.length; i++) {
  66973. var texture = new BABYLON.Texture(null, this.getScene());
  66974. texture._texture = this._internalTextures[i];
  66975. this._textures.push(texture);
  66976. }
  66977. // Keeps references to frame buffer and stencil/depth buffer
  66978. this._texture = this._internalTextures[0];
  66979. };
  66980. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  66981. get: function () {
  66982. return this._samples;
  66983. },
  66984. set: function (value) {
  66985. if (this._samples === value) {
  66986. return;
  66987. }
  66988. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  66989. },
  66990. enumerable: true,
  66991. configurable: true
  66992. });
  66993. MultiRenderTarget.prototype.resize = function (size) {
  66994. this.releaseInternalTextures();
  66995. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  66996. this._createInternalTextures();
  66997. };
  66998. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  66999. var _this = this;
  67000. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  67001. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  67002. });
  67003. };
  67004. MultiRenderTarget.prototype.dispose = function () {
  67005. this.releaseInternalTextures();
  67006. _super.prototype.dispose.call(this);
  67007. };
  67008. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  67009. if (!this._internalTextures) {
  67010. return;
  67011. }
  67012. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  67013. if (this._internalTextures[i] !== undefined) {
  67014. this._internalTextures[i].dispose();
  67015. this._internalTextures.splice(i, 1);
  67016. }
  67017. }
  67018. };
  67019. return MultiRenderTarget;
  67020. }(BABYLON.RenderTargetTexture));
  67021. BABYLON.MultiRenderTarget = MultiRenderTarget;
  67022. })(BABYLON || (BABYLON = {}));
  67023. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  67024. var BABYLON;
  67025. (function (BABYLON) {
  67026. var MirrorTexture = /** @class */ (function (_super) {
  67027. __extends(MirrorTexture, _super);
  67028. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  67029. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67030. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  67031. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  67032. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  67033. _this.scene = scene;
  67034. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  67035. _this._transformMatrix = BABYLON.Matrix.Zero();
  67036. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  67037. _this._adaptiveBlurKernel = 0;
  67038. _this._blurKernelX = 0;
  67039. _this._blurKernelY = 0;
  67040. _this._blurRatio = 1.0;
  67041. _this.ignoreCameraViewport = true;
  67042. _this._updateGammaSpace();
  67043. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  67044. _this._updateGammaSpace;
  67045. });
  67046. _this.onBeforeRenderObservable.add(function () {
  67047. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  67048. _this._savedViewMatrix = scene.getViewMatrix();
  67049. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  67050. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  67051. scene.clipPlane = _this.mirrorPlane;
  67052. scene.getEngine().cullBackFaces = false;
  67053. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  67054. });
  67055. _this.onAfterRenderObservable.add(function () {
  67056. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  67057. scene.getEngine().cullBackFaces = true;
  67058. scene._mirroredCameraPosition = null;
  67059. delete scene.clipPlane;
  67060. });
  67061. return _this;
  67062. }
  67063. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  67064. get: function () {
  67065. return this._blurRatio;
  67066. },
  67067. set: function (value) {
  67068. if (this._blurRatio === value) {
  67069. return;
  67070. }
  67071. this._blurRatio = value;
  67072. this._preparePostProcesses();
  67073. },
  67074. enumerable: true,
  67075. configurable: true
  67076. });
  67077. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  67078. set: function (value) {
  67079. this._adaptiveBlurKernel = value;
  67080. this._autoComputeBlurKernel();
  67081. },
  67082. enumerable: true,
  67083. configurable: true
  67084. });
  67085. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  67086. set: function (value) {
  67087. this.blurKernelX = value;
  67088. this.blurKernelY = value;
  67089. },
  67090. enumerable: true,
  67091. configurable: true
  67092. });
  67093. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  67094. get: function () {
  67095. return this._blurKernelX;
  67096. },
  67097. set: function (value) {
  67098. if (this._blurKernelX === value) {
  67099. return;
  67100. }
  67101. this._blurKernelX = value;
  67102. this._preparePostProcesses();
  67103. },
  67104. enumerable: true,
  67105. configurable: true
  67106. });
  67107. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  67108. get: function () {
  67109. return this._blurKernelY;
  67110. },
  67111. set: function (value) {
  67112. if (this._blurKernelY === value) {
  67113. return;
  67114. }
  67115. this._blurKernelY = value;
  67116. this._preparePostProcesses();
  67117. },
  67118. enumerable: true,
  67119. configurable: true
  67120. });
  67121. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  67122. var engine = this.getScene().getEngine();
  67123. var dw = this.getRenderWidth() / engine.getRenderWidth();
  67124. var dh = this.getRenderHeight() / engine.getRenderHeight();
  67125. this.blurKernelX = this._adaptiveBlurKernel * dw;
  67126. this.blurKernelY = this._adaptiveBlurKernel * dh;
  67127. };
  67128. MirrorTexture.prototype._onRatioRescale = function () {
  67129. if (this._sizeRatio) {
  67130. this.resize(this._initialSizeParameter);
  67131. if (!this._adaptiveBlurKernel) {
  67132. this._preparePostProcesses();
  67133. }
  67134. }
  67135. if (this._adaptiveBlurKernel) {
  67136. this._autoComputeBlurKernel();
  67137. }
  67138. };
  67139. MirrorTexture.prototype._updateGammaSpace = function () {
  67140. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  67141. };
  67142. MirrorTexture.prototype._preparePostProcesses = function () {
  67143. this.clearPostProcesses(true);
  67144. if (this._blurKernelX && this._blurKernelY) {
  67145. var engine = this.getScene().getEngine();
  67146. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67147. 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);
  67148. this._blurX.autoClear = false;
  67149. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  67150. this._blurX.inputTexture = this._texture;
  67151. }
  67152. else {
  67153. this._blurX.alwaysForcePOT = true;
  67154. }
  67155. 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);
  67156. this._blurY.autoClear = false;
  67157. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  67158. this.addPostProcess(this._blurX);
  67159. this.addPostProcess(this._blurY);
  67160. }
  67161. else {
  67162. if (this._blurY) {
  67163. this.removePostProcess(this._blurY);
  67164. this._blurY.dispose();
  67165. this._blurY = null;
  67166. }
  67167. if (this._blurX) {
  67168. this.removePostProcess(this._blurX);
  67169. this._blurX.dispose();
  67170. this._blurX = null;
  67171. }
  67172. }
  67173. };
  67174. MirrorTexture.prototype.clone = function () {
  67175. var scene = this.getScene();
  67176. if (!scene) {
  67177. return this;
  67178. }
  67179. var textureSize = this.getSize();
  67180. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  67181. // Base texture
  67182. newTexture.hasAlpha = this.hasAlpha;
  67183. newTexture.level = this.level;
  67184. // Mirror Texture
  67185. newTexture.mirrorPlane = this.mirrorPlane.clone();
  67186. if (this.renderList) {
  67187. newTexture.renderList = this.renderList.slice(0);
  67188. }
  67189. return newTexture;
  67190. };
  67191. MirrorTexture.prototype.serialize = function () {
  67192. if (!this.name) {
  67193. return null;
  67194. }
  67195. var serializationObject = _super.prototype.serialize.call(this);
  67196. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  67197. return serializationObject;
  67198. };
  67199. MirrorTexture.prototype.dispose = function () {
  67200. _super.prototype.dispose.call(this);
  67201. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  67202. };
  67203. return MirrorTexture;
  67204. }(BABYLON.RenderTargetTexture));
  67205. BABYLON.MirrorTexture = MirrorTexture;
  67206. })(BABYLON || (BABYLON = {}));
  67207. //# sourceMappingURL=babylon.mirrorTexture.js.map
  67208. var BABYLON;
  67209. (function (BABYLON) {
  67210. /**
  67211. * Creates a refraction texture used by refraction channel of the standard material.
  67212. * @param name the texture name
  67213. * @param size size of the underlying texture
  67214. * @param scene root scene
  67215. */
  67216. var RefractionTexture = /** @class */ (function (_super) {
  67217. __extends(RefractionTexture, _super);
  67218. function RefractionTexture(name, size, scene, generateMipMaps) {
  67219. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  67220. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  67221. _this.depth = 2.0;
  67222. _this.onBeforeRenderObservable.add(function () {
  67223. scene.clipPlane = _this.refractionPlane;
  67224. });
  67225. _this.onAfterRenderObservable.add(function () {
  67226. delete scene.clipPlane;
  67227. });
  67228. return _this;
  67229. }
  67230. RefractionTexture.prototype.clone = function () {
  67231. var scene = this.getScene();
  67232. if (!scene) {
  67233. return this;
  67234. }
  67235. var textureSize = this.getSize();
  67236. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  67237. // Base texture
  67238. newTexture.hasAlpha = this.hasAlpha;
  67239. newTexture.level = this.level;
  67240. // Refraction Texture
  67241. newTexture.refractionPlane = this.refractionPlane.clone();
  67242. if (this.renderList) {
  67243. newTexture.renderList = this.renderList.slice(0);
  67244. }
  67245. newTexture.depth = this.depth;
  67246. return newTexture;
  67247. };
  67248. RefractionTexture.prototype.serialize = function () {
  67249. if (!this.name) {
  67250. return null;
  67251. }
  67252. var serializationObject = _super.prototype.serialize.call(this);
  67253. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  67254. serializationObject.depth = this.depth;
  67255. return serializationObject;
  67256. };
  67257. return RefractionTexture;
  67258. }(BABYLON.RenderTargetTexture));
  67259. BABYLON.RefractionTexture = RefractionTexture;
  67260. })(BABYLON || (BABYLON = {}));
  67261. //# sourceMappingURL=babylon.refractionTexture.js.map
  67262. var BABYLON;
  67263. (function (BABYLON) {
  67264. /**
  67265. * A class extending {BABYLON.Texture} allowing drawing on a texture
  67266. * @see http://doc.babylonjs.com/how_to/dynamictexture
  67267. */
  67268. var DynamicTexture = /** @class */ (function (_super) {
  67269. __extends(DynamicTexture, _super);
  67270. /**
  67271. * Creates a {BABYLON.DynamicTexture}
  67272. * @param name defines the name of the texture
  67273. * @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
  67274. * @param scene defines the scene where you want the texture
  67275. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  67276. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  67277. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  67278. */
  67279. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  67280. if (scene === void 0) { scene = null; }
  67281. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67282. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  67283. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  67284. _this.name = name;
  67285. _this._engine = _this.getScene().getEngine();
  67286. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67287. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67288. _this._generateMipMaps = generateMipMaps;
  67289. if (options.getContext) {
  67290. _this._canvas = options;
  67291. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  67292. }
  67293. else {
  67294. _this._canvas = document.createElement("canvas");
  67295. if (options.width || options.width === 0) {
  67296. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  67297. }
  67298. else {
  67299. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  67300. }
  67301. }
  67302. var textureSize = _this.getSize();
  67303. _this._canvas.width = textureSize.width;
  67304. _this._canvas.height = textureSize.height;
  67305. _this._context = _this._canvas.getContext("2d");
  67306. return _this;
  67307. }
  67308. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  67309. /**
  67310. * Gets the current state of canRescale
  67311. */
  67312. get: function () {
  67313. return true;
  67314. },
  67315. enumerable: true,
  67316. configurable: true
  67317. });
  67318. DynamicTexture.prototype._recreate = function (textureSize) {
  67319. this._canvas.width = textureSize.width;
  67320. this._canvas.height = textureSize.height;
  67321. this.releaseInternalTexture();
  67322. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  67323. };
  67324. /**
  67325. * Scales the texture
  67326. * @param ratio the scale factor to apply to both width and height
  67327. */
  67328. DynamicTexture.prototype.scale = function (ratio) {
  67329. var textureSize = this.getSize();
  67330. textureSize.width *= ratio;
  67331. textureSize.height *= ratio;
  67332. this._recreate(textureSize);
  67333. };
  67334. /**
  67335. * Resizes the texture
  67336. * @param width the new width
  67337. * @param height the new height
  67338. */
  67339. DynamicTexture.prototype.scaleTo = function (width, height) {
  67340. var textureSize = this.getSize();
  67341. textureSize.width = width;
  67342. textureSize.height = height;
  67343. this._recreate(textureSize);
  67344. };
  67345. /**
  67346. * Gets the context of the canvas used by the texture
  67347. * @returns the canvas context of the dynamic texture
  67348. */
  67349. DynamicTexture.prototype.getContext = function () {
  67350. return this._context;
  67351. };
  67352. /**
  67353. * Clears the texture
  67354. */
  67355. DynamicTexture.prototype.clear = function () {
  67356. var size = this.getSize();
  67357. this._context.fillRect(0, 0, size.width, size.height);
  67358. };
  67359. /**
  67360. * Updates the texture
  67361. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  67362. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  67363. */
  67364. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  67365. if (premulAlpha === void 0) { premulAlpha = false; }
  67366. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  67367. };
  67368. /**
  67369. * Draws text onto the texture
  67370. * @param text defines the text to be drawn
  67371. * @param x defines the placement of the text from the left
  67372. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  67373. * @param font defines the font to be used with font-style, font-size, font-name
  67374. * @param color defines the color used for the text
  67375. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  67376. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  67377. * @param update defines whether texture is immediately update (default is true)
  67378. */
  67379. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  67380. if (update === void 0) { update = true; }
  67381. var size = this.getSize();
  67382. if (clearColor) {
  67383. this._context.fillStyle = clearColor;
  67384. this._context.fillRect(0, 0, size.width, size.height);
  67385. }
  67386. this._context.font = font;
  67387. if (x === null || x === undefined) {
  67388. var textSize = this._context.measureText(text);
  67389. x = (size.width - textSize.width) / 2;
  67390. }
  67391. if (y === null || y === undefined) {
  67392. var fontSize = parseInt((font.replace(/\D/g, '')));
  67393. y = (size.height / 2) + (fontSize / 3.65);
  67394. }
  67395. this._context.fillStyle = color;
  67396. this._context.fillText(text, x, y);
  67397. if (update) {
  67398. this.update(invertY);
  67399. }
  67400. };
  67401. /**
  67402. * Clones the texture
  67403. * @returns the clone of the texture.
  67404. */
  67405. DynamicTexture.prototype.clone = function () {
  67406. var scene = this.getScene();
  67407. if (!scene) {
  67408. return this;
  67409. }
  67410. var textureSize = this.getSize();
  67411. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  67412. // Base texture
  67413. newTexture.hasAlpha = this.hasAlpha;
  67414. newTexture.level = this.level;
  67415. // Dynamic Texture
  67416. newTexture.wrapU = this.wrapU;
  67417. newTexture.wrapV = this.wrapV;
  67418. return newTexture;
  67419. };
  67420. /**
  67421. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  67422. * @returns a serialized dynamic texture object
  67423. */
  67424. DynamicTexture.prototype.serialize = function () {
  67425. var scene = this.getScene();
  67426. if (scene && !scene.isReady()) {
  67427. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  67428. }
  67429. var serializationObject = _super.prototype.serialize.call(this);
  67430. serializationObject.base64String = this._canvas.toDataURL();
  67431. serializationObject.invertY = this._invertY;
  67432. serializationObject.samplingMode = this.samplingMode;
  67433. return serializationObject;
  67434. };
  67435. /** @hidden */
  67436. DynamicTexture.prototype._rebuild = function () {
  67437. this.update();
  67438. };
  67439. return DynamicTexture;
  67440. }(BABYLON.Texture));
  67441. BABYLON.DynamicTexture = DynamicTexture;
  67442. })(BABYLON || (BABYLON = {}));
  67443. //# sourceMappingURL=babylon.dynamicTexture.js.map
  67444. var BABYLON;
  67445. (function (BABYLON) {
  67446. var VideoTexture = /** @class */ (function (_super) {
  67447. __extends(VideoTexture, _super);
  67448. /**
  67449. * Creates a video texture.
  67450. * Sample : https://doc.babylonjs.com/how_to/video_texture
  67451. * @param {string | null} name optional name, will detect from video source, if not defined
  67452. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  67453. * @param {BABYLON.Scene} scene is obviously the current scene.
  67454. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  67455. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  67456. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  67457. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  67458. */
  67459. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  67460. if (generateMipMaps === void 0) { generateMipMaps = false; }
  67461. if (invertY === void 0) { invertY = false; }
  67462. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67463. if (settings === void 0) { settings = {
  67464. autoPlay: true,
  67465. loop: true,
  67466. autoUpdateTexture: true,
  67467. }; }
  67468. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  67469. _this._onUserActionRequestedObservable = null;
  67470. _this._stillImageCaptured = false;
  67471. _this._poster = false;
  67472. _this._createInternalTexture = function () {
  67473. if (_this._texture != null) {
  67474. if (_this._poster) {
  67475. _this._texture.dispose();
  67476. _this._poster = false;
  67477. }
  67478. else {
  67479. return;
  67480. }
  67481. }
  67482. if (!_this._engine.needPOTTextures ||
  67483. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  67484. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  67485. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  67486. }
  67487. else {
  67488. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67489. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67490. _this._generateMipMaps = false;
  67491. }
  67492. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  67493. if (!_this.video.autoplay) {
  67494. var oldHandler_1 = _this.video.onplaying;
  67495. var error_1 = false;
  67496. _this.video.onplaying = function () {
  67497. _this.video.onplaying = oldHandler_1;
  67498. _this._texture.isReady = true;
  67499. _this._updateInternalTexture();
  67500. if (!error_1) {
  67501. _this.video.pause();
  67502. }
  67503. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  67504. _this.onLoadObservable.notifyObservers(_this);
  67505. }
  67506. };
  67507. var playing = _this.video.play();
  67508. if (playing) {
  67509. playing.then(function () {
  67510. // Everything is good.
  67511. })
  67512. .catch(function () {
  67513. error_1 = true;
  67514. // On Chrome for instance, new policies might prevent playing without user interaction.
  67515. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  67516. _this._onUserActionRequestedObservable.notifyObservers(_this);
  67517. }
  67518. });
  67519. }
  67520. else {
  67521. _this.video.onplaying = oldHandler_1;
  67522. _this._texture.isReady = true;
  67523. _this._updateInternalTexture();
  67524. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  67525. _this.onLoadObservable.notifyObservers(_this);
  67526. }
  67527. }
  67528. }
  67529. else {
  67530. _this._texture.isReady = true;
  67531. _this._updateInternalTexture();
  67532. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  67533. _this.onLoadObservable.notifyObservers(_this);
  67534. }
  67535. }
  67536. };
  67537. _this.reset = function () {
  67538. if (_this._texture == null) {
  67539. return;
  67540. }
  67541. if (!_this._poster) {
  67542. _this._texture.dispose();
  67543. _this._texture = null;
  67544. }
  67545. };
  67546. _this._updateInternalTexture = function (e) {
  67547. if (_this._texture == null || !_this._texture.isReady) {
  67548. return;
  67549. }
  67550. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  67551. return;
  67552. }
  67553. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  67554. };
  67555. _this._engine = _this.getScene().getEngine();
  67556. _this._generateMipMaps = generateMipMaps;
  67557. _this._samplingMode = samplingMode;
  67558. _this.autoUpdateTexture = settings.autoUpdateTexture;
  67559. _this.name = name || _this._getName(src);
  67560. _this.video = _this._getVideo(src);
  67561. if (settings.poster) {
  67562. _this.video.poster = settings.poster;
  67563. }
  67564. if (settings.autoPlay !== undefined) {
  67565. _this.video.autoplay = settings.autoPlay;
  67566. }
  67567. if (settings.loop !== undefined) {
  67568. _this.video.loop = settings.loop;
  67569. }
  67570. _this.video.setAttribute("playsinline", "");
  67571. _this.video.addEventListener("canplay", _this._createInternalTexture);
  67572. _this.video.addEventListener("paused", _this._updateInternalTexture);
  67573. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  67574. _this.video.addEventListener("emptied", _this.reset);
  67575. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  67576. _this._createInternalTexture();
  67577. }
  67578. if (settings.poster) {
  67579. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  67580. _this._poster = true;
  67581. }
  67582. return _this;
  67583. }
  67584. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  67585. get: function () {
  67586. if (!this._onUserActionRequestedObservable) {
  67587. this._onUserActionRequestedObservable = new BABYLON.Observable();
  67588. }
  67589. return this._onUserActionRequestedObservable;
  67590. },
  67591. enumerable: true,
  67592. configurable: true
  67593. });
  67594. VideoTexture.prototype._getName = function (src) {
  67595. if (src instanceof HTMLVideoElement) {
  67596. return src.currentSrc;
  67597. }
  67598. if (typeof src === "object") {
  67599. return src.toString();
  67600. }
  67601. return src;
  67602. };
  67603. ;
  67604. VideoTexture.prototype._getVideo = function (src) {
  67605. if (src instanceof HTMLVideoElement) {
  67606. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  67607. return src;
  67608. }
  67609. var video = document.createElement("video");
  67610. if (typeof src === "string") {
  67611. BABYLON.Tools.SetCorsBehavior(src, video);
  67612. video.src = src;
  67613. }
  67614. else {
  67615. BABYLON.Tools.SetCorsBehavior(src[0], video);
  67616. src.forEach(function (url) {
  67617. var source = document.createElement("source");
  67618. source.src = url;
  67619. video.appendChild(source);
  67620. });
  67621. }
  67622. return video;
  67623. };
  67624. ;
  67625. /**
  67626. * @hidden Internal method to initiate `update`.
  67627. */
  67628. VideoTexture.prototype._rebuild = function () {
  67629. this.update();
  67630. };
  67631. /**
  67632. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  67633. */
  67634. VideoTexture.prototype.update = function () {
  67635. if (!this.autoUpdateTexture) {
  67636. // Expecting user to call `updateTexture` manually
  67637. return;
  67638. }
  67639. this.updateTexture(true);
  67640. };
  67641. /**
  67642. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  67643. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  67644. */
  67645. VideoTexture.prototype.updateTexture = function (isVisible) {
  67646. if (!isVisible) {
  67647. return;
  67648. }
  67649. if (this.video.paused && this._stillImageCaptured) {
  67650. return;
  67651. }
  67652. this._stillImageCaptured = true;
  67653. this._updateInternalTexture();
  67654. };
  67655. /**
  67656. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  67657. * @param url New url.
  67658. */
  67659. VideoTexture.prototype.updateURL = function (url) {
  67660. this.video.src = url;
  67661. };
  67662. VideoTexture.prototype.dispose = function () {
  67663. _super.prototype.dispose.call(this);
  67664. if (this._onUserActionRequestedObservable) {
  67665. this._onUserActionRequestedObservable.clear();
  67666. this._onUserActionRequestedObservable = null;
  67667. }
  67668. this.video.removeEventListener("canplay", this._createInternalTexture);
  67669. this.video.removeEventListener("paused", this._updateInternalTexture);
  67670. this.video.removeEventListener("seeked", this._updateInternalTexture);
  67671. this.video.removeEventListener("emptied", this.reset);
  67672. this.video.pause();
  67673. };
  67674. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  67675. var video = document.createElement("video");
  67676. video.setAttribute('autoplay', '');
  67677. video.setAttribute('muted', '');
  67678. video.setAttribute('playsinline', '');
  67679. var constraintsDeviceId;
  67680. if (constraints && constraints.deviceId) {
  67681. constraintsDeviceId = {
  67682. exact: constraints.deviceId,
  67683. };
  67684. }
  67685. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  67686. if (navigator.mediaDevices) {
  67687. navigator.mediaDevices.getUserMedia({ video: constraints })
  67688. .then(function (stream) {
  67689. if (video.mozSrcObject !== undefined) {
  67690. // hack for Firefox < 19
  67691. video.mozSrcObject = stream;
  67692. }
  67693. else {
  67694. video.srcObject = stream;
  67695. }
  67696. var onPlaying = function () {
  67697. if (onReady) {
  67698. onReady(new VideoTexture("video", video, scene, true, true));
  67699. }
  67700. video.removeEventListener("playing", onPlaying);
  67701. };
  67702. video.addEventListener("playing", onPlaying);
  67703. video.play();
  67704. })
  67705. .catch(function (err) {
  67706. BABYLON.Tools.Error(err.name);
  67707. });
  67708. }
  67709. else {
  67710. navigator.getUserMedia =
  67711. navigator.getUserMedia ||
  67712. navigator.webkitGetUserMedia ||
  67713. navigator.mozGetUserMedia ||
  67714. navigator.msGetUserMedia;
  67715. if (navigator.getUserMedia) {
  67716. navigator.getUserMedia({
  67717. video: {
  67718. deviceId: constraintsDeviceId,
  67719. width: {
  67720. min: (constraints && constraints.minWidth) || 256,
  67721. max: (constraints && constraints.maxWidth) || 640,
  67722. },
  67723. height: {
  67724. min: (constraints && constraints.minHeight) || 256,
  67725. max: (constraints && constraints.maxHeight) || 480,
  67726. },
  67727. },
  67728. }, function (stream) {
  67729. if (video.mozSrcObject !== undefined) {
  67730. // hack for Firefox < 19
  67731. video.mozSrcObject = stream;
  67732. }
  67733. else {
  67734. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  67735. }
  67736. video.play();
  67737. if (onReady) {
  67738. onReady(new VideoTexture("video", video, scene, true, true));
  67739. }
  67740. }, function (e) {
  67741. BABYLON.Tools.Error(e.name);
  67742. });
  67743. }
  67744. }
  67745. };
  67746. return VideoTexture;
  67747. }(BABYLON.Texture));
  67748. BABYLON.VideoTexture = VideoTexture;
  67749. })(BABYLON || (BABYLON = {}));
  67750. //# sourceMappingURL=babylon.videoTexture.js.map
  67751. var BABYLON;
  67752. (function (BABYLON) {
  67753. var RawTexture = /** @class */ (function (_super) {
  67754. __extends(RawTexture, _super);
  67755. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  67756. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67757. if (invertY === void 0) { invertY = false; }
  67758. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67759. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67760. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  67761. _this.format = format;
  67762. _this._engine = scene.getEngine();
  67763. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  67764. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67765. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67766. return _this;
  67767. }
  67768. RawTexture.prototype.update = function (data) {
  67769. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  67770. };
  67771. // Statics
  67772. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  67773. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67774. if (invertY === void 0) { invertY = false; }
  67775. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67776. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  67777. };
  67778. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  67779. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67780. if (invertY === void 0) { invertY = false; }
  67781. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67782. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  67783. };
  67784. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  67785. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67786. if (invertY === void 0) { invertY = false; }
  67787. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67788. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  67789. };
  67790. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  67791. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67792. if (invertY === void 0) { invertY = false; }
  67793. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67794. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67795. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  67796. };
  67797. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  67798. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67799. if (invertY === void 0) { invertY = false; }
  67800. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67801. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67802. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  67803. };
  67804. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  67805. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67806. if (invertY === void 0) { invertY = false; }
  67807. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67808. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  67809. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  67810. };
  67811. return RawTexture;
  67812. }(BABYLON.Texture));
  67813. BABYLON.RawTexture = RawTexture;
  67814. })(BABYLON || (BABYLON = {}));
  67815. //# sourceMappingURL=babylon.rawTexture.js.map
  67816. var BABYLON;
  67817. (function (BABYLON) {
  67818. /**
  67819. * Class used to store 3D textures containing user data
  67820. */
  67821. var RawTexture3D = /** @class */ (function (_super) {
  67822. __extends(RawTexture3D, _super);
  67823. /**
  67824. * Create a new RawTexture3D
  67825. * @param data defines the data of the texture
  67826. * @param width defines the width of the texture
  67827. * @param height defines the height of the texture
  67828. * @param depth defines the depth of the texture
  67829. * @param format defines the texture format to use
  67830. * @param scene defines the hosting scene
  67831. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  67832. * @param invertY defines if texture must be stored with Y axis inverted
  67833. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  67834. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  67835. */
  67836. function RawTexture3D(data, width, height, depth,
  67837. /** Gets or sets the texture format to use */
  67838. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  67839. if (generateMipMaps === void 0) { generateMipMaps = true; }
  67840. if (invertY === void 0) { invertY = false; }
  67841. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  67842. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67843. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  67844. _this.format = format;
  67845. _this._engine = scene.getEngine();
  67846. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  67847. _this.is3D = true;
  67848. return _this;
  67849. }
  67850. /**
  67851. * Update the texture with new data
  67852. * @param data defines the data to store in the texture
  67853. */
  67854. RawTexture3D.prototype.update = function (data) {
  67855. if (!this._texture) {
  67856. return;
  67857. }
  67858. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  67859. };
  67860. return RawTexture3D;
  67861. }(BABYLON.Texture));
  67862. BABYLON.RawTexture3D = RawTexture3D;
  67863. })(BABYLON || (BABYLON = {}));
  67864. //# sourceMappingURL=babylon.rawTexture3D.js.map
  67865. var BABYLON;
  67866. (function (BABYLON) {
  67867. /**
  67868. * PostProcessManager is used to manage one or more post processes or post process pipelines
  67869. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  67870. */
  67871. var PostProcessManager = /** @class */ (function () {
  67872. /**
  67873. * Creates a new instance PostProcess
  67874. * @param scene The scene that the post process is associated with.
  67875. */
  67876. function PostProcessManager(scene) {
  67877. this._vertexBuffers = {};
  67878. this._scene = scene;
  67879. }
  67880. PostProcessManager.prototype._prepareBuffers = function () {
  67881. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  67882. return;
  67883. }
  67884. // VBO
  67885. var vertices = [];
  67886. vertices.push(1, 1);
  67887. vertices.push(-1, 1);
  67888. vertices.push(-1, -1);
  67889. vertices.push(1, -1);
  67890. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  67891. this._buildIndexBuffer();
  67892. };
  67893. PostProcessManager.prototype._buildIndexBuffer = function () {
  67894. // Indices
  67895. var indices = [];
  67896. indices.push(0);
  67897. indices.push(1);
  67898. indices.push(2);
  67899. indices.push(0);
  67900. indices.push(2);
  67901. indices.push(3);
  67902. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  67903. };
  67904. /**
  67905. * Rebuilds the vertex buffers of the manager.
  67906. * @hidden
  67907. */
  67908. PostProcessManager.prototype._rebuild = function () {
  67909. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  67910. if (!vb) {
  67911. return;
  67912. }
  67913. vb._rebuild();
  67914. this._buildIndexBuffer();
  67915. };
  67916. // Methods
  67917. /**
  67918. * Prepares a frame to be run through a post process.
  67919. * @param sourceTexture The input texture to the post procesess. (default: null)
  67920. * @param postProcesses An array of post processes to be run. (default: null)
  67921. * @returns True if the post processes were able to be run.
  67922. * @hidden
  67923. */
  67924. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  67925. if (sourceTexture === void 0) { sourceTexture = null; }
  67926. if (postProcesses === void 0) { postProcesses = null; }
  67927. var camera = this._scene.activeCamera;
  67928. if (!camera) {
  67929. return false;
  67930. }
  67931. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  67932. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  67933. return false;
  67934. }
  67935. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  67936. return true;
  67937. };
  67938. /**
  67939. * Manually render a set of post processes to a texture.
  67940. * @param postProcesses An array of post processes to be run.
  67941. * @param targetTexture The target texture to render to.
  67942. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  67943. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  67944. * @param lodLevel defines which lod of the texture to render to
  67945. */
  67946. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  67947. if (targetTexture === void 0) { targetTexture = null; }
  67948. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  67949. if (faceIndex === void 0) { faceIndex = 0; }
  67950. if (lodLevel === void 0) { lodLevel = 0; }
  67951. var engine = this._scene.getEngine();
  67952. for (var index = 0; index < postProcesses.length; index++) {
  67953. if (index < postProcesses.length - 1) {
  67954. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  67955. }
  67956. else {
  67957. if (targetTexture) {
  67958. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  67959. }
  67960. else {
  67961. engine.restoreDefaultFramebuffer();
  67962. }
  67963. }
  67964. var pp = postProcesses[index];
  67965. var effect = pp.apply();
  67966. if (effect) {
  67967. pp.onBeforeRenderObservable.notifyObservers(effect);
  67968. // VBOs
  67969. this._prepareBuffers();
  67970. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  67971. // Draw order
  67972. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  67973. pp.onAfterRenderObservable.notifyObservers(effect);
  67974. }
  67975. }
  67976. // Restore depth buffer
  67977. engine.setDepthBuffer(true);
  67978. engine.setDepthWrite(true);
  67979. };
  67980. /**
  67981. * Finalize the result of the output of the postprocesses.
  67982. * @param doNotPresent If true the result will not be displayed to the screen.
  67983. * @param targetTexture The target texture to render to.
  67984. * @param faceIndex The index of the face to bind the target texture to.
  67985. * @param postProcesses The array of post processes to render.
  67986. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  67987. * @hidden
  67988. */
  67989. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  67990. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  67991. var camera = this._scene.activeCamera;
  67992. if (!camera) {
  67993. return;
  67994. }
  67995. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  67996. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  67997. return;
  67998. }
  67999. var engine = this._scene.getEngine();
  68000. for (var index = 0, len = postProcesses.length; index < len; index++) {
  68001. var pp = postProcesses[index];
  68002. if (index < len - 1) {
  68003. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  68004. }
  68005. else {
  68006. if (targetTexture) {
  68007. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  68008. pp._outputTexture = targetTexture;
  68009. }
  68010. else {
  68011. engine.restoreDefaultFramebuffer();
  68012. pp._outputTexture = null;
  68013. }
  68014. }
  68015. if (doNotPresent) {
  68016. break;
  68017. }
  68018. var effect = pp.apply();
  68019. if (effect) {
  68020. pp.onBeforeRenderObservable.notifyObservers(effect);
  68021. // VBOs
  68022. this._prepareBuffers();
  68023. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  68024. // Draw order
  68025. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  68026. pp.onAfterRenderObservable.notifyObservers(effect);
  68027. }
  68028. }
  68029. // Restore states
  68030. engine.setDepthBuffer(true);
  68031. engine.setDepthWrite(true);
  68032. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  68033. };
  68034. /**
  68035. * Disposes of the post process manager.
  68036. */
  68037. PostProcessManager.prototype.dispose = function () {
  68038. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68039. if (buffer) {
  68040. buffer.dispose();
  68041. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  68042. }
  68043. if (this._indexBuffer) {
  68044. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  68045. this._indexBuffer = null;
  68046. }
  68047. };
  68048. return PostProcessManager;
  68049. }());
  68050. BABYLON.PostProcessManager = PostProcessManager;
  68051. })(BABYLON || (BABYLON = {}));
  68052. //# sourceMappingURL=babylon.postProcessManager.js.map
  68053. var BABYLON;
  68054. (function (BABYLON) {
  68055. /**
  68056. * PostProcess can be used to apply a shader to a texture after it has been rendered
  68057. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  68058. */
  68059. var PostProcess = /** @class */ (function () {
  68060. /**
  68061. * Creates a new instance PostProcess
  68062. * @param name The name of the PostProcess.
  68063. * @param fragmentUrl The url of the fragment shader to be used.
  68064. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  68065. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  68066. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  68067. * @param camera The camera to apply the render pass to.
  68068. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68069. * @param engine The engine which the post process will be applied. (default: current engine)
  68070. * @param reusable If the post process can be reused on the same frame. (default: false)
  68071. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  68072. * @param textureType Type of textures used when performing the post process. (default: 0)
  68073. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  68074. * @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
  68075. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  68076. */
  68077. function PostProcess(
  68078. /** Name of the PostProcess. */
  68079. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  68080. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  68081. if (defines === void 0) { defines = null; }
  68082. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68083. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  68084. if (blockCompilation === void 0) { blockCompilation = false; }
  68085. this.name = name;
  68086. /**
  68087. * Width of the texture to apply the post process on
  68088. */
  68089. this.width = -1;
  68090. /**
  68091. * Height of the texture to apply the post process on
  68092. */
  68093. this.height = -1;
  68094. /**
  68095. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  68096. * @hidden
  68097. */
  68098. this._outputTexture = null;
  68099. /**
  68100. * If the buffer needs to be cleared before applying the post process. (default: true)
  68101. * Should be set to false if shader will overwrite all previous pixels.
  68102. */
  68103. this.autoClear = true;
  68104. /**
  68105. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  68106. */
  68107. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  68108. /**
  68109. * Animations to be used for the post processing
  68110. */
  68111. this.animations = new Array();
  68112. /**
  68113. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  68114. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  68115. */
  68116. this.enablePixelPerfectMode = false;
  68117. /**
  68118. * Force the postprocess to be applied without taking in account viewport
  68119. */
  68120. this.forceFullscreenViewport = true;
  68121. /**
  68122. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  68123. *
  68124. * | Value | Type | Description |
  68125. * | ----- | ----------------------------------- | ----------- |
  68126. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  68127. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  68128. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  68129. *
  68130. */
  68131. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  68132. /**
  68133. * Force textures to be a power of two (default: false)
  68134. */
  68135. this.alwaysForcePOT = false;
  68136. /**
  68137. * Number of sample textures (default: 1)
  68138. */
  68139. this.samples = 1;
  68140. /**
  68141. * Modify the scale of the post process to be the same as the viewport (default: false)
  68142. */
  68143. this.adaptScaleToCurrentViewport = false;
  68144. this._reusable = false;
  68145. /**
  68146. * Smart array of input and output textures for the post process.
  68147. * @hidden
  68148. */
  68149. this._textures = new BABYLON.SmartArray(2);
  68150. /**
  68151. * The index in _textures that corresponds to the output texture.
  68152. * @hidden
  68153. */
  68154. this._currentRenderTextureInd = 0;
  68155. this._scaleRatio = new BABYLON.Vector2(1, 1);
  68156. this._texelSize = BABYLON.Vector2.Zero();
  68157. // Events
  68158. /**
  68159. * An event triggered when the postprocess is activated.
  68160. */
  68161. this.onActivateObservable = new BABYLON.Observable();
  68162. /**
  68163. * An event triggered when the postprocess changes its size.
  68164. */
  68165. this.onSizeChangedObservable = new BABYLON.Observable();
  68166. /**
  68167. * An event triggered when the postprocess applies its effect.
  68168. */
  68169. this.onApplyObservable = new BABYLON.Observable();
  68170. /**
  68171. * An event triggered before rendering the postprocess
  68172. */
  68173. this.onBeforeRenderObservable = new BABYLON.Observable();
  68174. /**
  68175. * An event triggered after rendering the postprocess
  68176. */
  68177. this.onAfterRenderObservable = new BABYLON.Observable();
  68178. if (camera != null) {
  68179. this._camera = camera;
  68180. this._scene = camera.getScene();
  68181. camera.attachPostProcess(this);
  68182. this._engine = this._scene.getEngine();
  68183. this._scene.postProcesses.push(this);
  68184. }
  68185. else if (engine) {
  68186. this._engine = engine;
  68187. this._engine.postProcesses.push(this);
  68188. }
  68189. this._options = options;
  68190. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  68191. this._reusable = reusable || false;
  68192. this._textureType = textureType;
  68193. this._samplers = samplers || [];
  68194. this._samplers.push("textureSampler");
  68195. this._fragmentUrl = fragmentUrl;
  68196. this._vertexUrl = vertexUrl;
  68197. this._parameters = parameters || [];
  68198. this._parameters.push("scale");
  68199. this._indexParameters = indexParameters;
  68200. if (!blockCompilation) {
  68201. this.updateEffect(defines);
  68202. }
  68203. }
  68204. Object.defineProperty(PostProcess.prototype, "onActivate", {
  68205. /**
  68206. * A function that is added to the onActivateObservable
  68207. */
  68208. set: function (callback) {
  68209. if (this._onActivateObserver) {
  68210. this.onActivateObservable.remove(this._onActivateObserver);
  68211. }
  68212. if (callback) {
  68213. this._onActivateObserver = this.onActivateObservable.add(callback);
  68214. }
  68215. },
  68216. enumerable: true,
  68217. configurable: true
  68218. });
  68219. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  68220. /**
  68221. * A function that is added to the onSizeChangedObservable
  68222. */
  68223. set: function (callback) {
  68224. if (this._onSizeChangedObserver) {
  68225. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  68226. }
  68227. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  68228. },
  68229. enumerable: true,
  68230. configurable: true
  68231. });
  68232. Object.defineProperty(PostProcess.prototype, "onApply", {
  68233. /**
  68234. * A function that is added to the onApplyObservable
  68235. */
  68236. set: function (callback) {
  68237. if (this._onApplyObserver) {
  68238. this.onApplyObservable.remove(this._onApplyObserver);
  68239. }
  68240. this._onApplyObserver = this.onApplyObservable.add(callback);
  68241. },
  68242. enumerable: true,
  68243. configurable: true
  68244. });
  68245. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  68246. /**
  68247. * A function that is added to the onBeforeRenderObservable
  68248. */
  68249. set: function (callback) {
  68250. if (this._onBeforeRenderObserver) {
  68251. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  68252. }
  68253. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  68254. },
  68255. enumerable: true,
  68256. configurable: true
  68257. });
  68258. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  68259. /**
  68260. * A function that is added to the onAfterRenderObservable
  68261. */
  68262. set: function (callback) {
  68263. if (this._onAfterRenderObserver) {
  68264. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  68265. }
  68266. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  68267. },
  68268. enumerable: true,
  68269. configurable: true
  68270. });
  68271. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  68272. /**
  68273. * 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
  68274. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  68275. */
  68276. get: function () {
  68277. return this._textures.data[this._currentRenderTextureInd];
  68278. },
  68279. set: function (value) {
  68280. this._forcedOutputTexture = value;
  68281. },
  68282. enumerable: true,
  68283. configurable: true
  68284. });
  68285. /**
  68286. * Gets the camera which post process is applied to.
  68287. * @returns The camera the post process is applied to.
  68288. */
  68289. PostProcess.prototype.getCamera = function () {
  68290. return this._camera;
  68291. };
  68292. Object.defineProperty(PostProcess.prototype, "texelSize", {
  68293. /**
  68294. * Gets the texel size of the postprocess.
  68295. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  68296. */
  68297. get: function () {
  68298. if (this._shareOutputWithPostProcess) {
  68299. return this._shareOutputWithPostProcess.texelSize;
  68300. }
  68301. if (this._forcedOutputTexture) {
  68302. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  68303. }
  68304. return this._texelSize;
  68305. },
  68306. enumerable: true,
  68307. configurable: true
  68308. });
  68309. /**
  68310. * Gets the engine which this post process belongs to.
  68311. * @returns The engine the post process was enabled with.
  68312. */
  68313. PostProcess.prototype.getEngine = function () {
  68314. return this._engine;
  68315. };
  68316. /**
  68317. * The effect that is created when initializing the post process.
  68318. * @returns The created effect corrisponding the the postprocess.
  68319. */
  68320. PostProcess.prototype.getEffect = function () {
  68321. return this._effect;
  68322. };
  68323. /**
  68324. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  68325. * @param postProcess The post process to share the output with.
  68326. * @returns This post process.
  68327. */
  68328. PostProcess.prototype.shareOutputWith = function (postProcess) {
  68329. this._disposeTextures();
  68330. this._shareOutputWithPostProcess = postProcess;
  68331. return this;
  68332. };
  68333. /**
  68334. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  68335. * This should be called if the post process that shares output with this post process is disabled/disposed.
  68336. */
  68337. PostProcess.prototype.useOwnOutput = function () {
  68338. if (this._textures.length == 0) {
  68339. this._textures = new BABYLON.SmartArray(2);
  68340. }
  68341. this._shareOutputWithPostProcess = null;
  68342. };
  68343. /**
  68344. * Updates the effect with the current post process compile time values and recompiles the shader.
  68345. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  68346. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  68347. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  68348. * @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
  68349. * @param onCompiled Called when the shader has been compiled.
  68350. * @param onError Called if there is an error when compiling a shader.
  68351. */
  68352. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  68353. if (defines === void 0) { defines = null; }
  68354. if (uniforms === void 0) { uniforms = null; }
  68355. if (samplers === void 0) { samplers = null; }
  68356. 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);
  68357. };
  68358. /**
  68359. * The post process is reusable if it can be used multiple times within one frame.
  68360. * @returns If the post process is reusable
  68361. */
  68362. PostProcess.prototype.isReusable = function () {
  68363. return this._reusable;
  68364. };
  68365. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  68366. PostProcess.prototype.markTextureDirty = function () {
  68367. this.width = -1;
  68368. };
  68369. /**
  68370. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  68371. * 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.
  68372. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  68373. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  68374. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  68375. * @returns The target texture that was bound to be written to.
  68376. */
  68377. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  68378. var _this = this;
  68379. if (sourceTexture === void 0) { sourceTexture = null; }
  68380. camera = camera || this._camera;
  68381. var scene = camera.getScene();
  68382. var engine = scene.getEngine();
  68383. var maxSize = engine.getCaps().maxTextureSize;
  68384. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  68385. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  68386. // 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
  68387. var webVRCamera = camera.parent;
  68388. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  68389. requiredWidth /= 2;
  68390. }
  68391. var desiredWidth = (this._options.width || requiredWidth);
  68392. var desiredHeight = this._options.height || requiredHeight;
  68393. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  68394. if (this.adaptScaleToCurrentViewport) {
  68395. var currentViewport = engine.currentViewport;
  68396. if (currentViewport) {
  68397. desiredWidth *= currentViewport.width;
  68398. desiredHeight *= currentViewport.height;
  68399. }
  68400. }
  68401. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  68402. if (!this._options.width) {
  68403. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  68404. }
  68405. if (!this._options.height) {
  68406. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  68407. }
  68408. }
  68409. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  68410. if (this._textures.length > 0) {
  68411. for (var i = 0; i < this._textures.length; i++) {
  68412. this._engine._releaseTexture(this._textures.data[i]);
  68413. }
  68414. this._textures.reset();
  68415. }
  68416. this.width = desiredWidth;
  68417. this.height = desiredHeight;
  68418. var textureSize = { width: this.width, height: this.height };
  68419. var textureOptions = {
  68420. generateMipMaps: false,
  68421. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  68422. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  68423. samplingMode: this.renderTargetSamplingMode,
  68424. type: this._textureType
  68425. };
  68426. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  68427. if (this._reusable) {
  68428. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  68429. }
  68430. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  68431. this.onSizeChangedObservable.notifyObservers(this);
  68432. }
  68433. this._textures.forEach(function (texture) {
  68434. if (texture.samples !== _this.samples) {
  68435. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  68436. }
  68437. });
  68438. }
  68439. var target;
  68440. if (this._shareOutputWithPostProcess) {
  68441. target = this._shareOutputWithPostProcess.inputTexture;
  68442. }
  68443. else if (this._forcedOutputTexture) {
  68444. target = this._forcedOutputTexture;
  68445. this.width = this._forcedOutputTexture.width;
  68446. this.height = this._forcedOutputTexture.height;
  68447. }
  68448. else {
  68449. target = this.inputTexture;
  68450. }
  68451. // Bind the input of this post process to be used as the output of the previous post process.
  68452. if (this.enablePixelPerfectMode) {
  68453. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  68454. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  68455. }
  68456. else {
  68457. this._scaleRatio.copyFromFloats(1, 1);
  68458. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  68459. }
  68460. this.onActivateObservable.notifyObservers(camera);
  68461. // Clear
  68462. if (scene._allowPostProcessClear && this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  68463. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  68464. }
  68465. if (this._reusable) {
  68466. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  68467. }
  68468. return target;
  68469. };
  68470. Object.defineProperty(PostProcess.prototype, "isSupported", {
  68471. /**
  68472. * If the post process is supported.
  68473. */
  68474. get: function () {
  68475. return this._effect.isSupported;
  68476. },
  68477. enumerable: true,
  68478. configurable: true
  68479. });
  68480. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  68481. /**
  68482. * The aspect ratio of the output texture.
  68483. */
  68484. get: function () {
  68485. if (this._shareOutputWithPostProcess) {
  68486. return this._shareOutputWithPostProcess.aspectRatio;
  68487. }
  68488. if (this._forcedOutputTexture) {
  68489. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  68490. }
  68491. return this.width / this.height;
  68492. },
  68493. enumerable: true,
  68494. configurable: true
  68495. });
  68496. /**
  68497. * Get a value indicating if the post-process is ready to be used
  68498. * @returns true if the post-process is ready (shader is compiled)
  68499. */
  68500. PostProcess.prototype.isReady = function () {
  68501. return this._effect && this._effect.isReady();
  68502. };
  68503. /**
  68504. * Binds all textures and uniforms to the shader, this will be run on every pass.
  68505. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  68506. */
  68507. PostProcess.prototype.apply = function () {
  68508. // Check
  68509. if (!this._effect || !this._effect.isReady())
  68510. return null;
  68511. // States
  68512. this._engine.enableEffect(this._effect);
  68513. this._engine.setState(false);
  68514. this._engine.setDepthBuffer(false);
  68515. this._engine.setDepthWrite(false);
  68516. // Alpha
  68517. this._engine.setAlphaMode(this.alphaMode);
  68518. if (this.alphaConstants) {
  68519. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  68520. }
  68521. // Bind the output texture of the preivous post process as the input to this post process.
  68522. var source;
  68523. if (this._shareOutputWithPostProcess) {
  68524. source = this._shareOutputWithPostProcess.inputTexture;
  68525. }
  68526. else if (this._forcedOutputTexture) {
  68527. source = this._forcedOutputTexture;
  68528. }
  68529. else {
  68530. source = this.inputTexture;
  68531. }
  68532. this._effect._bindTexture("textureSampler", source);
  68533. // Parameters
  68534. this._effect.setVector2("scale", this._scaleRatio);
  68535. this.onApplyObservable.notifyObservers(this._effect);
  68536. return this._effect;
  68537. };
  68538. PostProcess.prototype._disposeTextures = function () {
  68539. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  68540. return;
  68541. }
  68542. if (this._textures.length > 0) {
  68543. for (var i = 0; i < this._textures.length; i++) {
  68544. this._engine._releaseTexture(this._textures.data[i]);
  68545. }
  68546. }
  68547. this._textures.dispose();
  68548. };
  68549. /**
  68550. * Disposes the post process.
  68551. * @param camera The camera to dispose the post process on.
  68552. */
  68553. PostProcess.prototype.dispose = function (camera) {
  68554. camera = camera || this._camera;
  68555. this._disposeTextures();
  68556. if (this._scene) {
  68557. var index_1 = this._scene.postProcesses.indexOf(this);
  68558. if (index_1 !== -1) {
  68559. this._scene.postProcesses.splice(index_1, 1);
  68560. }
  68561. }
  68562. else {
  68563. var index_2 = this._engine.postProcesses.indexOf(this);
  68564. if (index_2 !== -1) {
  68565. this._engine.postProcesses.splice(index_2, 1);
  68566. }
  68567. }
  68568. if (!camera) {
  68569. return;
  68570. }
  68571. camera.detachPostProcess(this);
  68572. var index = camera._postProcesses.indexOf(this);
  68573. if (index === 0 && camera._postProcesses.length > 0) {
  68574. var firstPostProcess = this._camera._getFirstPostProcess();
  68575. if (firstPostProcess) {
  68576. firstPostProcess.markTextureDirty();
  68577. }
  68578. }
  68579. this.onActivateObservable.clear();
  68580. this.onAfterRenderObservable.clear();
  68581. this.onApplyObservable.clear();
  68582. this.onBeforeRenderObservable.clear();
  68583. this.onSizeChangedObservable.clear();
  68584. };
  68585. return PostProcess;
  68586. }());
  68587. BABYLON.PostProcess = PostProcess;
  68588. })(BABYLON || (BABYLON = {}));
  68589. //# sourceMappingURL=babylon.postProcess.js.map
  68590. var BABYLON;
  68591. (function (BABYLON) {
  68592. var PassPostProcess = /** @class */ (function (_super) {
  68593. __extends(PassPostProcess, _super);
  68594. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  68595. if (camera === void 0) { camera = null; }
  68596. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68597. if (blockCompilation === void 0) { blockCompilation = false; }
  68598. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  68599. }
  68600. return PassPostProcess;
  68601. }(BABYLON.PostProcess));
  68602. BABYLON.PassPostProcess = PassPostProcess;
  68603. })(BABYLON || (BABYLON = {}));
  68604. //# sourceMappingURL=babylon.passPostProcess.js.map
  68605. var __assign = (this && this.__assign) || function () {
  68606. __assign = Object.assign || function(t) {
  68607. for (var s, i = 1, n = arguments.length; i < n; i++) {
  68608. s = arguments[i];
  68609. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  68610. t[p] = s[p];
  68611. }
  68612. return t;
  68613. };
  68614. return __assign.apply(this, arguments);
  68615. };
  68616. var BABYLON;
  68617. (function (BABYLON) {
  68618. /**
  68619. * Default implementation IShadowGenerator.
  68620. * This is the main object responsible of generating shadows in the framework.
  68621. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  68622. */
  68623. var ShadowGenerator = /** @class */ (function () {
  68624. /**
  68625. * Creates a ShadowGenerator object.
  68626. * A ShadowGenerator is the required tool to use the shadows.
  68627. * Each light casting shadows needs to use its own ShadowGenerator.
  68628. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  68629. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  68630. * @param light The light object generating the shadows.
  68631. * @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.
  68632. */
  68633. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  68634. this._bias = 0.00005;
  68635. this._normalBias = 0;
  68636. this._blurBoxOffset = 1;
  68637. this._blurScale = 2;
  68638. this._blurKernel = 1;
  68639. this._useKernelBlur = false;
  68640. this._filter = ShadowGenerator.FILTER_NONE;
  68641. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  68642. this._contactHardeningLightSizeUVRatio = 0.1;
  68643. this._darkness = 0;
  68644. this._transparencyShadow = false;
  68645. /**
  68646. * Controls the extent to which the shadows fade out at the edge of the frustum
  68647. * Used only by directionals and spots
  68648. */
  68649. this.frustumEdgeFalloff = 0;
  68650. /**
  68651. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  68652. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  68653. * It might on the other hand introduce peter panning.
  68654. */
  68655. this.forceBackFacesOnly = false;
  68656. this._lightDirection = BABYLON.Vector3.Zero();
  68657. this._viewMatrix = BABYLON.Matrix.Zero();
  68658. this._projectionMatrix = BABYLON.Matrix.Zero();
  68659. this._transformMatrix = BABYLON.Matrix.Zero();
  68660. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  68661. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  68662. this._currentFaceIndex = 0;
  68663. this._currentFaceIndexCache = 0;
  68664. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  68665. this._mapSize = mapSize;
  68666. this._light = light;
  68667. this._scene = light.getScene();
  68668. light._shadowGenerator = this;
  68669. // Texture type fallback from float to int if not supported.
  68670. var caps = this._scene.getEngine().getCaps();
  68671. if (!useFullFloatFirst) {
  68672. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  68673. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68674. }
  68675. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  68676. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  68677. }
  68678. else {
  68679. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  68680. }
  68681. }
  68682. else {
  68683. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  68684. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  68685. }
  68686. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  68687. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68688. }
  68689. else {
  68690. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  68691. }
  68692. }
  68693. this._initializeGenerator();
  68694. this._applyFilterValues();
  68695. }
  68696. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  68697. /**
  68698. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  68699. */
  68700. get: function () {
  68701. return this._bias;
  68702. },
  68703. /**
  68704. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  68705. */
  68706. set: function (bias) {
  68707. this._bias = bias;
  68708. },
  68709. enumerable: true,
  68710. configurable: true
  68711. });
  68712. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  68713. /**
  68714. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  68715. */
  68716. get: function () {
  68717. return this._normalBias;
  68718. },
  68719. /**
  68720. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  68721. */
  68722. set: function (normalBias) {
  68723. this._normalBias = normalBias;
  68724. },
  68725. enumerable: true,
  68726. configurable: true
  68727. });
  68728. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  68729. /**
  68730. * Gets the blur box offset: offset applied during the blur pass.
  68731. * Only usefull if useKernelBlur = false
  68732. */
  68733. get: function () {
  68734. return this._blurBoxOffset;
  68735. },
  68736. /**
  68737. * Sets the blur box offset: offset applied during the blur pass.
  68738. * Only usefull if useKernelBlur = false
  68739. */
  68740. set: function (value) {
  68741. if (this._blurBoxOffset === value) {
  68742. return;
  68743. }
  68744. this._blurBoxOffset = value;
  68745. this._disposeBlurPostProcesses();
  68746. },
  68747. enumerable: true,
  68748. configurable: true
  68749. });
  68750. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  68751. /**
  68752. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  68753. * 2 means half of the size.
  68754. */
  68755. get: function () {
  68756. return this._blurScale;
  68757. },
  68758. /**
  68759. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  68760. * 2 means half of the size.
  68761. */
  68762. set: function (value) {
  68763. if (this._blurScale === value) {
  68764. return;
  68765. }
  68766. this._blurScale = value;
  68767. this._disposeBlurPostProcesses();
  68768. },
  68769. enumerable: true,
  68770. configurable: true
  68771. });
  68772. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  68773. /**
  68774. * Gets the blur kernel: kernel size of the blur pass.
  68775. * Only usefull if useKernelBlur = true
  68776. */
  68777. get: function () {
  68778. return this._blurKernel;
  68779. },
  68780. /**
  68781. * Sets the blur kernel: kernel size of the blur pass.
  68782. * Only usefull if useKernelBlur = true
  68783. */
  68784. set: function (value) {
  68785. if (this._blurKernel === value) {
  68786. return;
  68787. }
  68788. this._blurKernel = value;
  68789. this._disposeBlurPostProcesses();
  68790. },
  68791. enumerable: true,
  68792. configurable: true
  68793. });
  68794. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  68795. /**
  68796. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  68797. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  68798. */
  68799. get: function () {
  68800. return this._useKernelBlur;
  68801. },
  68802. /**
  68803. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  68804. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  68805. */
  68806. set: function (value) {
  68807. if (this._useKernelBlur === value) {
  68808. return;
  68809. }
  68810. this._useKernelBlur = value;
  68811. this._disposeBlurPostProcesses();
  68812. },
  68813. enumerable: true,
  68814. configurable: true
  68815. });
  68816. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  68817. /**
  68818. * Gets the depth scale used in ESM mode.
  68819. */
  68820. get: function () {
  68821. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  68822. },
  68823. /**
  68824. * Sets the depth scale used in ESM mode.
  68825. * This can override the scale stored on the light.
  68826. */
  68827. set: function (value) {
  68828. this._depthScale = value;
  68829. },
  68830. enumerable: true,
  68831. configurable: true
  68832. });
  68833. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  68834. /**
  68835. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  68836. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  68837. */
  68838. get: function () {
  68839. return this._filter;
  68840. },
  68841. /**
  68842. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  68843. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  68844. */
  68845. set: function (value) {
  68846. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  68847. if (this._light.needCube()) {
  68848. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  68849. this.useExponentialShadowMap = true;
  68850. return;
  68851. }
  68852. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  68853. this.useCloseExponentialShadowMap = true;
  68854. return;
  68855. }
  68856. // PCF on cubemap would also be expensive
  68857. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  68858. this.usePoissonSampling = true;
  68859. return;
  68860. }
  68861. }
  68862. // Weblg1 fallback for PCF.
  68863. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  68864. if (this._scene.getEngine().webGLVersion === 1) {
  68865. this.usePoissonSampling = true;
  68866. return;
  68867. }
  68868. }
  68869. if (this._filter === value) {
  68870. return;
  68871. }
  68872. this._filter = value;
  68873. this._disposeBlurPostProcesses();
  68874. this._applyFilterValues();
  68875. this._light._markMeshesAsLightDirty();
  68876. },
  68877. enumerable: true,
  68878. configurable: true
  68879. });
  68880. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  68881. /**
  68882. * Gets if the current filter is set to Poisson Sampling.
  68883. */
  68884. get: function () {
  68885. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  68886. },
  68887. /**
  68888. * Sets the current filter to Poisson Sampling.
  68889. */
  68890. set: function (value) {
  68891. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  68892. return;
  68893. }
  68894. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  68895. },
  68896. enumerable: true,
  68897. configurable: true
  68898. });
  68899. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  68900. /**
  68901. * Gets if the current filter is set to VSM.
  68902. * DEPRECATED. Should use useExponentialShadowMap instead.
  68903. */
  68904. get: function () {
  68905. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  68906. return this.useExponentialShadowMap;
  68907. },
  68908. /**
  68909. * Sets the current filter is to VSM.
  68910. * DEPRECATED. Should use useExponentialShadowMap instead.
  68911. */
  68912. set: function (value) {
  68913. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  68914. this.useExponentialShadowMap = value;
  68915. },
  68916. enumerable: true,
  68917. configurable: true
  68918. });
  68919. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  68920. /**
  68921. * Gets if the current filter is set to blurred VSM.
  68922. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  68923. */
  68924. get: function () {
  68925. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  68926. return this.useBlurExponentialShadowMap;
  68927. },
  68928. /**
  68929. * Sets the current filter is to blurred VSM.
  68930. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  68931. */
  68932. set: function (value) {
  68933. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  68934. this.useBlurExponentialShadowMap = value;
  68935. },
  68936. enumerable: true,
  68937. configurable: true
  68938. });
  68939. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  68940. /**
  68941. * Gets if the current filter is set to ESM.
  68942. */
  68943. get: function () {
  68944. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  68945. },
  68946. /**
  68947. * Sets the current filter is to ESM.
  68948. */
  68949. set: function (value) {
  68950. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  68951. return;
  68952. }
  68953. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  68954. },
  68955. enumerable: true,
  68956. configurable: true
  68957. });
  68958. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  68959. /**
  68960. * Gets if the current filter is set to filtered ESM.
  68961. */
  68962. get: function () {
  68963. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  68964. },
  68965. /**
  68966. * Gets if the current filter is set to filtered ESM.
  68967. */
  68968. set: function (value) {
  68969. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  68970. return;
  68971. }
  68972. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  68973. },
  68974. enumerable: true,
  68975. configurable: true
  68976. });
  68977. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  68978. /**
  68979. * Gets if the current filter is set to "close ESM" (using the inverse of the
  68980. * exponential to prevent steep falloff artifacts).
  68981. */
  68982. get: function () {
  68983. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  68984. },
  68985. /**
  68986. * Sets the current filter to "close ESM" (using the inverse of the
  68987. * exponential to prevent steep falloff artifacts).
  68988. */
  68989. set: function (value) {
  68990. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  68991. return;
  68992. }
  68993. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  68994. },
  68995. enumerable: true,
  68996. configurable: true
  68997. });
  68998. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  68999. /**
  69000. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  69001. * exponential to prevent steep falloff artifacts).
  69002. */
  69003. get: function () {
  69004. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  69005. },
  69006. /**
  69007. * Sets the current filter to filtered "close ESM" (using the inverse of the
  69008. * exponential to prevent steep falloff artifacts).
  69009. */
  69010. set: function (value) {
  69011. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  69012. return;
  69013. }
  69014. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  69015. },
  69016. enumerable: true,
  69017. configurable: true
  69018. });
  69019. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  69020. /**
  69021. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  69022. */
  69023. get: function () {
  69024. return this.filter === ShadowGenerator.FILTER_PCF;
  69025. },
  69026. /**
  69027. * Sets the current filter to "PCF" (percentage closer filtering).
  69028. */
  69029. set: function (value) {
  69030. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  69031. return;
  69032. }
  69033. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  69034. },
  69035. enumerable: true,
  69036. configurable: true
  69037. });
  69038. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  69039. /**
  69040. * Gets the PCF or PCSS Quality.
  69041. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  69042. */
  69043. get: function () {
  69044. return this._filteringQuality;
  69045. },
  69046. /**
  69047. * Sets the PCF or PCSS Quality.
  69048. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  69049. */
  69050. set: function (filteringQuality) {
  69051. this._filteringQuality = filteringQuality;
  69052. },
  69053. enumerable: true,
  69054. configurable: true
  69055. });
  69056. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  69057. /**
  69058. * Gets if the current filter is set to "PCSS" (contact hardening).
  69059. */
  69060. get: function () {
  69061. return this.filter === ShadowGenerator.FILTER_PCSS;
  69062. },
  69063. /**
  69064. * Sets the current filter to "PCSS" (contact hardening).
  69065. */
  69066. set: function (value) {
  69067. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  69068. return;
  69069. }
  69070. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  69071. },
  69072. enumerable: true,
  69073. configurable: true
  69074. });
  69075. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  69076. /**
  69077. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  69078. * Using a ratio helps keeping shape stability independently of the map size.
  69079. *
  69080. * It does not account for the light projection as it was having too much
  69081. * instability during the light setup or during light position changes.
  69082. *
  69083. * Only valid if useContactHardeningShadow is true.
  69084. */
  69085. get: function () {
  69086. return this._contactHardeningLightSizeUVRatio;
  69087. },
  69088. /**
  69089. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  69090. * Using a ratio helps keeping shape stability independently of the map size.
  69091. *
  69092. * It does not account for the light projection as it was having too much
  69093. * instability during the light setup or during light position changes.
  69094. *
  69095. * Only valid if useContactHardeningShadow is true.
  69096. */
  69097. set: function (contactHardeningLightSizeUVRatio) {
  69098. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  69099. },
  69100. enumerable: true,
  69101. configurable: true
  69102. });
  69103. /**
  69104. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  69105. * 0 means strongest and 1 would means no shadow.
  69106. * @returns the darkness.
  69107. */
  69108. ShadowGenerator.prototype.getDarkness = function () {
  69109. return this._darkness;
  69110. };
  69111. /**
  69112. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  69113. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  69114. * @returns the shadow generator allowing fluent coding.
  69115. */
  69116. ShadowGenerator.prototype.setDarkness = function (darkness) {
  69117. if (darkness >= 1.0)
  69118. this._darkness = 1.0;
  69119. else if (darkness <= 0.0)
  69120. this._darkness = 0.0;
  69121. else
  69122. this._darkness = darkness;
  69123. return this;
  69124. };
  69125. /**
  69126. * Sets the ability to have transparent shadow (boolean).
  69127. * @param transparent True if transparent else False
  69128. * @returns the shadow generator allowing fluent coding
  69129. */
  69130. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  69131. this._transparencyShadow = transparent;
  69132. return this;
  69133. };
  69134. /**
  69135. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  69136. * @returns The render target texture if present otherwise, null
  69137. */
  69138. ShadowGenerator.prototype.getShadowMap = function () {
  69139. return this._shadowMap;
  69140. };
  69141. /**
  69142. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  69143. * @returns The render target texture if the shadow map is present otherwise, null
  69144. */
  69145. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  69146. if (this._shadowMap2) {
  69147. return this._shadowMap2;
  69148. }
  69149. return this._shadowMap;
  69150. };
  69151. /**
  69152. * Helper function to add a mesh and its descendants to the list of shadow casters.
  69153. * @param mesh Mesh to add
  69154. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  69155. * @returns the Shadow Generator itself
  69156. */
  69157. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  69158. if (includeDescendants === void 0) { includeDescendants = true; }
  69159. var _a;
  69160. if (!this._shadowMap) {
  69161. return this;
  69162. }
  69163. if (!this._shadowMap.renderList) {
  69164. this._shadowMap.renderList = [];
  69165. }
  69166. this._shadowMap.renderList.push(mesh);
  69167. if (includeDescendants) {
  69168. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  69169. }
  69170. return this;
  69171. };
  69172. /**
  69173. * Helper function to remove a mesh and its descendants from the list of shadow casters
  69174. * @param mesh Mesh to remove
  69175. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  69176. * @returns the Shadow Generator itself
  69177. */
  69178. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  69179. if (includeDescendants === void 0) { includeDescendants = true; }
  69180. if (!this._shadowMap || !this._shadowMap.renderList) {
  69181. return this;
  69182. }
  69183. var index = this._shadowMap.renderList.indexOf(mesh);
  69184. if (index !== -1) {
  69185. this._shadowMap.renderList.splice(index, 1);
  69186. }
  69187. if (includeDescendants) {
  69188. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  69189. var child = _a[_i];
  69190. this.removeShadowCaster(child);
  69191. }
  69192. }
  69193. return this;
  69194. };
  69195. /**
  69196. * Returns the associated light object.
  69197. * @returns the light generating the shadow
  69198. */
  69199. ShadowGenerator.prototype.getLight = function () {
  69200. return this._light;
  69201. };
  69202. ShadowGenerator.prototype._initializeGenerator = function () {
  69203. this._light._markMeshesAsLightDirty();
  69204. this._initializeShadowMap();
  69205. };
  69206. ShadowGenerator.prototype._initializeShadowMap = function () {
  69207. var _this = this;
  69208. // Render target
  69209. var engine = this._scene.getEngine();
  69210. if (engine.webGLVersion > 1) {
  69211. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  69212. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  69213. }
  69214. else {
  69215. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  69216. }
  69217. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69218. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69219. this._shadowMap.anisotropicFilteringLevel = 1;
  69220. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  69221. this._shadowMap.renderParticles = false;
  69222. this._shadowMap.ignoreCameraViewport = true;
  69223. // Record Face Index before render.
  69224. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  69225. _this._currentFaceIndex = faceIndex;
  69226. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  69227. engine.setColorWrite(false);
  69228. }
  69229. });
  69230. // Custom render function.
  69231. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  69232. // Blur if required afer render.
  69233. this._shadowMap.onAfterUnbindObservable.add(function () {
  69234. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  69235. engine.setColorWrite(true);
  69236. }
  69237. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  69238. return;
  69239. }
  69240. var shadowMap = _this.getShadowMapForRendering();
  69241. if (shadowMap) {
  69242. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  69243. }
  69244. });
  69245. // Clear according to the chosen filter.
  69246. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  69247. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  69248. this._shadowMap.onClearObservable.add(function (engine) {
  69249. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  69250. engine.clear(clearOne, false, true, false);
  69251. }
  69252. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  69253. engine.clear(clearZero, true, true, false);
  69254. }
  69255. else {
  69256. engine.clear(clearOne, true, true, false);
  69257. }
  69258. });
  69259. };
  69260. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  69261. var _this = this;
  69262. var engine = this._scene.getEngine();
  69263. var targetSize = this._mapSize / this.blurScale;
  69264. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  69265. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  69266. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69267. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69268. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  69269. }
  69270. if (this.useKernelBlur) {
  69271. 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);
  69272. this._kernelBlurXPostprocess.width = targetSize;
  69273. this._kernelBlurXPostprocess.height = targetSize;
  69274. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  69275. effect.setTexture("textureSampler", _this._shadowMap);
  69276. });
  69277. 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);
  69278. this._kernelBlurXPostprocess.autoClear = false;
  69279. this._kernelBlurYPostprocess.autoClear = false;
  69280. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  69281. this._kernelBlurXPostprocess.packedFloat = true;
  69282. this._kernelBlurYPostprocess.packedFloat = true;
  69283. }
  69284. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  69285. }
  69286. else {
  69287. 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);
  69288. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  69289. effect.setFloat2("screenSize", targetSize, targetSize);
  69290. effect.setTexture("textureSampler", _this._shadowMap);
  69291. });
  69292. this._boxBlurPostprocess.autoClear = false;
  69293. this._blurPostProcesses = [this._boxBlurPostprocess];
  69294. }
  69295. };
  69296. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  69297. var index;
  69298. var engine = this._scene.getEngine();
  69299. if (depthOnlySubMeshes.length) {
  69300. engine.setColorWrite(false);
  69301. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  69302. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  69303. }
  69304. engine.setColorWrite(true);
  69305. }
  69306. for (index = 0; index < opaqueSubMeshes.length; index++) {
  69307. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  69308. }
  69309. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  69310. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  69311. }
  69312. if (this._transparencyShadow) {
  69313. for (index = 0; index < transparentSubMeshes.length; index++) {
  69314. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  69315. }
  69316. }
  69317. };
  69318. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  69319. var _this = this;
  69320. var mesh = subMesh.getRenderingMesh();
  69321. var scene = this._scene;
  69322. var engine = scene.getEngine();
  69323. var material = subMesh.getMaterial();
  69324. if (!material) {
  69325. return;
  69326. }
  69327. // Culling
  69328. engine.setState(material.backFaceCulling);
  69329. // Managing instances
  69330. var batch = mesh._getInstancesRenderList(subMesh._id);
  69331. if (batch.mustReturn) {
  69332. return;
  69333. }
  69334. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  69335. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  69336. engine.enableEffect(this._effect);
  69337. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  69338. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  69339. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  69340. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  69341. this._effect.setVector3("lightData", this._cachedDirection);
  69342. }
  69343. else {
  69344. this._effect.setVector3("lightData", this._cachedPosition);
  69345. }
  69346. if (scene.activeCamera) {
  69347. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  69348. }
  69349. // Alpha test
  69350. if (material && material.needAlphaTesting()) {
  69351. var alphaTexture = material.getAlphaTestTexture();
  69352. if (alphaTexture) {
  69353. this._effect.setTexture("diffuseSampler", alphaTexture);
  69354. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  69355. }
  69356. }
  69357. // Bones
  69358. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69359. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  69360. }
  69361. // Morph targets
  69362. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  69363. if (this.forceBackFacesOnly) {
  69364. engine.setState(true, 0, false, true);
  69365. }
  69366. // Draw
  69367. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  69368. if (this.forceBackFacesOnly) {
  69369. engine.setState(true, 0, false, false);
  69370. }
  69371. }
  69372. else {
  69373. // Need to reset refresh rate of the shadowMap
  69374. if (this._shadowMap) {
  69375. this._shadowMap.resetRefreshCounter();
  69376. }
  69377. }
  69378. };
  69379. ShadowGenerator.prototype._applyFilterValues = function () {
  69380. if (!this._shadowMap) {
  69381. return;
  69382. }
  69383. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  69384. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  69385. }
  69386. else {
  69387. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  69388. }
  69389. };
  69390. /**
  69391. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  69392. * @param onCompiled Callback triggered at the and of the effects compilation
  69393. * @param options Sets of optional options forcing the compilation with different modes
  69394. */
  69395. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  69396. var _this = this;
  69397. var localOptions = __assign({ useInstances: false }, options);
  69398. var shadowMap = this.getShadowMap();
  69399. if (!shadowMap) {
  69400. if (onCompiled) {
  69401. onCompiled(this);
  69402. }
  69403. return;
  69404. }
  69405. var renderList = shadowMap.renderList;
  69406. if (!renderList) {
  69407. if (onCompiled) {
  69408. onCompiled(this);
  69409. }
  69410. return;
  69411. }
  69412. var subMeshes = new Array();
  69413. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  69414. var mesh = renderList_1[_i];
  69415. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  69416. }
  69417. if (subMeshes.length === 0) {
  69418. if (onCompiled) {
  69419. onCompiled(this);
  69420. }
  69421. return;
  69422. }
  69423. var currentIndex = 0;
  69424. var checkReady = function () {
  69425. if (!_this._scene || !_this._scene.getEngine()) {
  69426. return;
  69427. }
  69428. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  69429. currentIndex++;
  69430. if (currentIndex >= subMeshes.length) {
  69431. if (onCompiled) {
  69432. onCompiled(_this);
  69433. }
  69434. return;
  69435. }
  69436. }
  69437. setTimeout(checkReady, 16);
  69438. };
  69439. checkReady();
  69440. };
  69441. /**
  69442. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  69443. * @param options Sets of optional options forcing the compilation with different modes
  69444. * @returns A promise that resolves when the compilation completes
  69445. */
  69446. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  69447. var _this = this;
  69448. return new Promise(function (resolve) {
  69449. _this.forceCompilation(function () {
  69450. resolve();
  69451. }, options);
  69452. });
  69453. };
  69454. /**
  69455. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  69456. * @param subMesh The submesh we want to render in the shadow map
  69457. * @param useInstances Defines wether will draw in the map using instances
  69458. * @returns true if ready otherwise, false
  69459. */
  69460. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  69461. var defines = [];
  69462. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  69463. defines.push("#define FLOAT");
  69464. }
  69465. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  69466. defines.push("#define ESM");
  69467. }
  69468. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  69469. defines.push("#define DEPTHTEXTURE");
  69470. }
  69471. var attribs = [BABYLON.VertexBuffer.PositionKind];
  69472. var mesh = subMesh.getMesh();
  69473. var material = subMesh.getMaterial();
  69474. // Normal bias.
  69475. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  69476. attribs.push(BABYLON.VertexBuffer.NormalKind);
  69477. defines.push("#define NORMAL");
  69478. if (mesh.nonUniformScaling) {
  69479. defines.push("#define NONUNIFORMSCALING");
  69480. }
  69481. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  69482. defines.push("#define DIRECTIONINLIGHTDATA");
  69483. }
  69484. }
  69485. // Alpha test
  69486. if (material && material.needAlphaTesting()) {
  69487. var alphaTexture = material.getAlphaTestTexture();
  69488. if (alphaTexture) {
  69489. defines.push("#define ALPHATEST");
  69490. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  69491. attribs.push(BABYLON.VertexBuffer.UVKind);
  69492. defines.push("#define UV1");
  69493. }
  69494. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  69495. if (alphaTexture.coordinatesIndex === 1) {
  69496. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  69497. defines.push("#define UV2");
  69498. }
  69499. }
  69500. }
  69501. }
  69502. // Bones
  69503. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  69504. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  69505. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  69506. if (mesh.numBoneInfluencers > 4) {
  69507. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  69508. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  69509. }
  69510. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  69511. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  69512. }
  69513. else {
  69514. defines.push("#define NUM_BONE_INFLUENCERS 0");
  69515. }
  69516. // Morph targets
  69517. var manager = mesh.morphTargetManager;
  69518. var morphInfluencers = 0;
  69519. if (manager) {
  69520. if (manager.numInfluencers > 0) {
  69521. defines.push("#define MORPHTARGETS");
  69522. morphInfluencers = manager.numInfluencers;
  69523. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  69524. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  69525. }
  69526. }
  69527. // Instances
  69528. if (useInstances) {
  69529. defines.push("#define INSTANCES");
  69530. attribs.push("world0");
  69531. attribs.push("world1");
  69532. attribs.push("world2");
  69533. attribs.push("world3");
  69534. }
  69535. // Get correct effect
  69536. var join = defines.join("\n");
  69537. if (this._cachedDefines !== join) {
  69538. this._cachedDefines = join;
  69539. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  69540. }
  69541. if (!this._effect.isReady()) {
  69542. return false;
  69543. }
  69544. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  69545. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  69546. this._initializeBlurRTTAndPostProcesses();
  69547. }
  69548. }
  69549. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  69550. return false;
  69551. }
  69552. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  69553. return false;
  69554. }
  69555. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  69556. return false;
  69557. }
  69558. return true;
  69559. };
  69560. /**
  69561. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  69562. * @param defines Defines of the material we want to update
  69563. * @param lightIndex Index of the light in the enabled light list of the material
  69564. */
  69565. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  69566. var scene = this._scene;
  69567. var light = this._light;
  69568. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  69569. return;
  69570. }
  69571. defines["SHADOW" + lightIndex] = true;
  69572. if (this.useContactHardeningShadow) {
  69573. defines["SHADOWPCSS" + lightIndex] = true;
  69574. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  69575. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  69576. }
  69577. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  69578. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  69579. }
  69580. // else default to high.
  69581. }
  69582. if (this.usePercentageCloserFiltering) {
  69583. defines["SHADOWPCF" + lightIndex] = true;
  69584. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  69585. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  69586. }
  69587. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  69588. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  69589. }
  69590. // else default to high.
  69591. }
  69592. else if (this.usePoissonSampling) {
  69593. defines["SHADOWPOISSON" + lightIndex] = true;
  69594. }
  69595. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  69596. defines["SHADOWESM" + lightIndex] = true;
  69597. }
  69598. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  69599. defines["SHADOWCLOSEESM" + lightIndex] = true;
  69600. }
  69601. if (light.needCube()) {
  69602. defines["SHADOWCUBE" + lightIndex] = true;
  69603. }
  69604. };
  69605. /**
  69606. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  69607. * defined in the generator but impacting the effect).
  69608. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  69609. * @param effect The effect we are binfing the information for
  69610. */
  69611. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  69612. var light = this._light;
  69613. var scene = this._scene;
  69614. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  69615. return;
  69616. }
  69617. var camera = scene.activeCamera;
  69618. if (!camera) {
  69619. return;
  69620. }
  69621. var shadowMap = this.getShadowMap();
  69622. if (!shadowMap) {
  69623. return;
  69624. }
  69625. if (!light.needCube()) {
  69626. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  69627. }
  69628. // Only PCF uses depth stencil texture.
  69629. if (this._filter === ShadowGenerator.FILTER_PCF) {
  69630. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  69631. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  69632. }
  69633. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  69634. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  69635. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  69636. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  69637. }
  69638. else {
  69639. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  69640. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  69641. }
  69642. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  69643. };
  69644. /**
  69645. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  69646. * (eq to shadow prjection matrix * light transform matrix)
  69647. * @returns The transform matrix used to create the shadow map
  69648. */
  69649. ShadowGenerator.prototype.getTransformMatrix = function () {
  69650. var scene = this._scene;
  69651. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  69652. return this._transformMatrix;
  69653. }
  69654. this._currentRenderID = scene.getRenderId();
  69655. this._currentFaceIndexCache = this._currentFaceIndex;
  69656. var lightPosition = this._light.position;
  69657. if (this._light.computeTransformedInformation()) {
  69658. lightPosition = this._light.transformedPosition;
  69659. }
  69660. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  69661. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  69662. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  69663. }
  69664. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  69665. this._cachedPosition.copyFrom(lightPosition);
  69666. this._cachedDirection.copyFrom(this._lightDirection);
  69667. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  69668. var shadowMap = this.getShadowMap();
  69669. if (shadowMap) {
  69670. var renderList = shadowMap.renderList;
  69671. if (renderList) {
  69672. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  69673. }
  69674. }
  69675. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  69676. }
  69677. return this._transformMatrix;
  69678. };
  69679. /**
  69680. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  69681. * Cube and 2D textures for instance.
  69682. */
  69683. ShadowGenerator.prototype.recreateShadowMap = function () {
  69684. var shadowMap = this._shadowMap;
  69685. if (!shadowMap) {
  69686. return;
  69687. }
  69688. // Track render list.
  69689. var renderList = shadowMap.renderList;
  69690. // Clean up existing data.
  69691. this._disposeRTTandPostProcesses();
  69692. // Reinitializes.
  69693. this._initializeGenerator();
  69694. // Reaffect the filter to ensure a correct fallback if necessary.
  69695. this.filter = this.filter;
  69696. // Reaffect the filter.
  69697. this._applyFilterValues();
  69698. // Reaffect Render List.
  69699. this._shadowMap.renderList = renderList;
  69700. };
  69701. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  69702. if (this._shadowMap2) {
  69703. this._shadowMap2.dispose();
  69704. this._shadowMap2 = null;
  69705. }
  69706. if (this._boxBlurPostprocess) {
  69707. this._boxBlurPostprocess.dispose();
  69708. this._boxBlurPostprocess = null;
  69709. }
  69710. if (this._kernelBlurXPostprocess) {
  69711. this._kernelBlurXPostprocess.dispose();
  69712. this._kernelBlurXPostprocess = null;
  69713. }
  69714. if (this._kernelBlurYPostprocess) {
  69715. this._kernelBlurYPostprocess.dispose();
  69716. this._kernelBlurYPostprocess = null;
  69717. }
  69718. this._blurPostProcesses = [];
  69719. };
  69720. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  69721. if (this._shadowMap) {
  69722. this._shadowMap.dispose();
  69723. this._shadowMap = null;
  69724. }
  69725. this._disposeBlurPostProcesses();
  69726. };
  69727. /**
  69728. * Disposes the ShadowGenerator.
  69729. * Returns nothing.
  69730. */
  69731. ShadowGenerator.prototype.dispose = function () {
  69732. this._disposeRTTandPostProcesses();
  69733. if (this._light) {
  69734. this._light._shadowGenerator = null;
  69735. this._light._markMeshesAsLightDirty();
  69736. }
  69737. };
  69738. /**
  69739. * Serializes the shadow generator setup to a json object.
  69740. * @returns The serialized JSON object
  69741. */
  69742. ShadowGenerator.prototype.serialize = function () {
  69743. var serializationObject = {};
  69744. var shadowMap = this.getShadowMap();
  69745. if (!shadowMap) {
  69746. return serializationObject;
  69747. }
  69748. serializationObject.lightId = this._light.id;
  69749. serializationObject.mapSize = shadowMap.getRenderSize();
  69750. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  69751. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  69752. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  69753. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  69754. serializationObject.usePoissonSampling = this.usePoissonSampling;
  69755. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  69756. serializationObject.depthScale = this.depthScale;
  69757. serializationObject.darkness = this.getDarkness();
  69758. serializationObject.blurBoxOffset = this.blurBoxOffset;
  69759. serializationObject.blurKernel = this.blurKernel;
  69760. serializationObject.blurScale = this.blurScale;
  69761. serializationObject.useKernelBlur = this.useKernelBlur;
  69762. serializationObject.transparencyShadow = this._transparencyShadow;
  69763. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  69764. serializationObject.bias = this.bias;
  69765. serializationObject.normalBias = this.normalBias;
  69766. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  69767. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  69768. serializationObject.filteringQuality = this.filteringQuality;
  69769. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  69770. serializationObject.renderList = [];
  69771. if (shadowMap.renderList) {
  69772. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  69773. var mesh = shadowMap.renderList[meshIndex];
  69774. serializationObject.renderList.push(mesh.id);
  69775. }
  69776. }
  69777. return serializationObject;
  69778. };
  69779. /**
  69780. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  69781. * @param parsedShadowGenerator The JSON object to parse
  69782. * @param scene The scene to create the shadow map for
  69783. * @returns The parsed shadow generator
  69784. */
  69785. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  69786. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  69787. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  69788. var shadowMap = shadowGenerator.getShadowMap();
  69789. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  69790. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  69791. meshes.forEach(function (mesh) {
  69792. if (!shadowMap) {
  69793. return;
  69794. }
  69795. if (!shadowMap.renderList) {
  69796. shadowMap.renderList = [];
  69797. }
  69798. shadowMap.renderList.push(mesh);
  69799. });
  69800. }
  69801. if (parsedShadowGenerator.usePoissonSampling) {
  69802. shadowGenerator.usePoissonSampling = true;
  69803. }
  69804. else if (parsedShadowGenerator.useExponentialShadowMap) {
  69805. shadowGenerator.useExponentialShadowMap = true;
  69806. }
  69807. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  69808. shadowGenerator.useBlurExponentialShadowMap = true;
  69809. }
  69810. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  69811. shadowGenerator.useCloseExponentialShadowMap = true;
  69812. }
  69813. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  69814. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  69815. }
  69816. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  69817. shadowGenerator.usePercentageCloserFiltering = true;
  69818. }
  69819. else if (parsedShadowGenerator.useContactHardeningShadow) {
  69820. shadowGenerator.useContactHardeningShadow = true;
  69821. }
  69822. if (parsedShadowGenerator.filteringQuality) {
  69823. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  69824. }
  69825. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  69826. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  69827. }
  69828. // Backward compat
  69829. else if (parsedShadowGenerator.useVarianceShadowMap) {
  69830. shadowGenerator.useExponentialShadowMap = true;
  69831. }
  69832. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  69833. shadowGenerator.useBlurExponentialShadowMap = true;
  69834. }
  69835. if (parsedShadowGenerator.depthScale) {
  69836. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  69837. }
  69838. if (parsedShadowGenerator.blurScale) {
  69839. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  69840. }
  69841. if (parsedShadowGenerator.blurBoxOffset) {
  69842. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  69843. }
  69844. if (parsedShadowGenerator.useKernelBlur) {
  69845. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  69846. }
  69847. if (parsedShadowGenerator.blurKernel) {
  69848. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  69849. }
  69850. if (parsedShadowGenerator.bias !== undefined) {
  69851. shadowGenerator.bias = parsedShadowGenerator.bias;
  69852. }
  69853. if (parsedShadowGenerator.normalBias !== undefined) {
  69854. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  69855. }
  69856. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  69857. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  69858. }
  69859. if (parsedShadowGenerator.darkness) {
  69860. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  69861. }
  69862. if (parsedShadowGenerator.transparencyShadow) {
  69863. shadowGenerator.setTransparencyShadow(true);
  69864. }
  69865. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  69866. return shadowGenerator;
  69867. };
  69868. /**
  69869. * Shadow generator mode None: no filtering applied.
  69870. */
  69871. ShadowGenerator.FILTER_NONE = 0;
  69872. /**
  69873. * Shadow generator mode ESM: Exponential Shadow Mapping.
  69874. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  69875. */
  69876. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  69877. /**
  69878. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  69879. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  69880. */
  69881. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  69882. /**
  69883. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  69884. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  69885. */
  69886. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  69887. /**
  69888. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  69889. * edge artifacts on steep falloff.
  69890. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  69891. */
  69892. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  69893. /**
  69894. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  69895. * edge artifacts on steep falloff.
  69896. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  69897. */
  69898. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  69899. /**
  69900. * Shadow generator mode PCF: Percentage Closer Filtering
  69901. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  69902. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  69903. */
  69904. ShadowGenerator.FILTER_PCF = 6;
  69905. /**
  69906. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  69907. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  69908. * Contact Hardening
  69909. */
  69910. ShadowGenerator.FILTER_PCSS = 7;
  69911. /**
  69912. * Reserved for PCF and PCSS
  69913. * Highest Quality.
  69914. *
  69915. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  69916. *
  69917. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  69918. */
  69919. ShadowGenerator.QUALITY_HIGH = 0;
  69920. /**
  69921. * Reserved for PCF and PCSS
  69922. * Good tradeoff for quality/perf cross devices
  69923. *
  69924. * Execute PCF on a 3*3 kernel.
  69925. *
  69926. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  69927. */
  69928. ShadowGenerator.QUALITY_MEDIUM = 1;
  69929. /**
  69930. * Reserved for PCF and PCSS
  69931. * The lowest quality but the fastest.
  69932. *
  69933. * Execute PCF on a 1*1 kernel.
  69934. *
  69935. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  69936. */
  69937. ShadowGenerator.QUALITY_LOW = 2;
  69938. return ShadowGenerator;
  69939. }());
  69940. BABYLON.ShadowGenerator = ShadowGenerator;
  69941. })(BABYLON || (BABYLON = {}));
  69942. //# sourceMappingURL=babylon.shadowGenerator.js.map
  69943. var BABYLON;
  69944. (function (BABYLON) {
  69945. var DefaultLoadingScreen = /** @class */ (function () {
  69946. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  69947. if (_loadingText === void 0) { _loadingText = ""; }
  69948. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  69949. var _this = this;
  69950. this._renderingCanvas = _renderingCanvas;
  69951. this._loadingText = _loadingText;
  69952. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  69953. // Resize
  69954. this._resizeLoadingUI = function () {
  69955. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  69956. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  69957. if (!_this._loadingDiv) {
  69958. return;
  69959. }
  69960. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  69961. _this._loadingDiv.style.left = canvasRect.left + "px";
  69962. _this._loadingDiv.style.top = canvasRect.top + "px";
  69963. _this._loadingDiv.style.width = canvasRect.width + "px";
  69964. _this._loadingDiv.style.height = canvasRect.height + "px";
  69965. };
  69966. }
  69967. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  69968. if (this._loadingDiv) {
  69969. // Do not add a loading screen if there is already one
  69970. return;
  69971. }
  69972. this._loadingDiv = document.createElement("div");
  69973. this._loadingDiv.id = "babylonjsLoadingDiv";
  69974. this._loadingDiv.style.opacity = "0";
  69975. this._loadingDiv.style.transition = "opacity 1.5s ease";
  69976. this._loadingDiv.style.pointerEvents = "none";
  69977. // Loading text
  69978. this._loadingTextDiv = document.createElement("div");
  69979. this._loadingTextDiv.style.position = "absolute";
  69980. this._loadingTextDiv.style.left = "0";
  69981. this._loadingTextDiv.style.top = "50%";
  69982. this._loadingTextDiv.style.marginTop = "80px";
  69983. this._loadingTextDiv.style.width = "100%";
  69984. this._loadingTextDiv.style.height = "20px";
  69985. this._loadingTextDiv.style.fontFamily = "Arial";
  69986. this._loadingTextDiv.style.fontSize = "14px";
  69987. this._loadingTextDiv.style.color = "white";
  69988. this._loadingTextDiv.style.textAlign = "center";
  69989. this._loadingTextDiv.innerHTML = "Loading";
  69990. this._loadingDiv.appendChild(this._loadingTextDiv);
  69991. //set the predefined text
  69992. this._loadingTextDiv.innerHTML = this._loadingText;
  69993. // Generating keyframes
  69994. var style = document.createElement('style');
  69995. style.type = 'text/css';
  69996. 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 }";
  69997. style.innerHTML = keyFrames;
  69998. document.getElementsByTagName('head')[0].appendChild(style);
  69999. // Loading img
  70000. var imgBack = new Image();
  70001. 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";
  70002. imgBack.style.position = "absolute";
  70003. imgBack.style.left = "50%";
  70004. imgBack.style.top = "50%";
  70005. imgBack.style.marginLeft = "-60px";
  70006. imgBack.style.marginTop = "-60px";
  70007. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  70008. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  70009. imgBack.style.transformOrigin = "50% 50%";
  70010. imgBack.style.webkitTransformOrigin = "50% 50%";
  70011. this._loadingDiv.appendChild(imgBack);
  70012. this._resizeLoadingUI();
  70013. window.addEventListener("resize", this._resizeLoadingUI);
  70014. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  70015. document.body.appendChild(this._loadingDiv);
  70016. this._loadingDiv.style.opacity = "1";
  70017. };
  70018. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  70019. var _this = this;
  70020. if (!this._loadingDiv) {
  70021. return;
  70022. }
  70023. var onTransitionEnd = function () {
  70024. if (!_this._loadingDiv) {
  70025. return;
  70026. }
  70027. document.body.removeChild(_this._loadingDiv);
  70028. window.removeEventListener("resize", _this._resizeLoadingUI);
  70029. _this._loadingDiv = null;
  70030. };
  70031. this._loadingDiv.style.opacity = "0";
  70032. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  70033. };
  70034. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  70035. set: function (text) {
  70036. this._loadingText = text;
  70037. if (this._loadingTextDiv) {
  70038. this._loadingTextDiv.innerHTML = this._loadingText;
  70039. }
  70040. },
  70041. enumerable: true,
  70042. configurable: true
  70043. });
  70044. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  70045. get: function () {
  70046. return this._loadingDivBackgroundColor;
  70047. },
  70048. set: function (color) {
  70049. this._loadingDivBackgroundColor = color;
  70050. if (!this._loadingDiv) {
  70051. return;
  70052. }
  70053. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  70054. },
  70055. enumerable: true,
  70056. configurable: true
  70057. });
  70058. return DefaultLoadingScreen;
  70059. }());
  70060. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  70061. })(BABYLON || (BABYLON = {}));
  70062. //# sourceMappingURL=babylon.loadingScreen.js.map
  70063. var BABYLON;
  70064. (function (BABYLON) {
  70065. var SceneLoaderProgressEvent = /** @class */ (function () {
  70066. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  70067. this.lengthComputable = lengthComputable;
  70068. this.loaded = loaded;
  70069. this.total = total;
  70070. }
  70071. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  70072. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  70073. };
  70074. return SceneLoaderProgressEvent;
  70075. }());
  70076. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  70077. var SceneLoader = /** @class */ (function () {
  70078. function SceneLoader() {
  70079. }
  70080. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  70081. get: function () {
  70082. return 0;
  70083. },
  70084. enumerable: true,
  70085. configurable: true
  70086. });
  70087. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  70088. get: function () {
  70089. return 1;
  70090. },
  70091. enumerable: true,
  70092. configurable: true
  70093. });
  70094. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  70095. get: function () {
  70096. return 2;
  70097. },
  70098. enumerable: true,
  70099. configurable: true
  70100. });
  70101. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  70102. get: function () {
  70103. return 3;
  70104. },
  70105. enumerable: true,
  70106. configurable: true
  70107. });
  70108. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  70109. get: function () {
  70110. return SceneLoader._ForceFullSceneLoadingForIncremental;
  70111. },
  70112. set: function (value) {
  70113. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  70114. },
  70115. enumerable: true,
  70116. configurable: true
  70117. });
  70118. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  70119. get: function () {
  70120. return SceneLoader._ShowLoadingScreen;
  70121. },
  70122. set: function (value) {
  70123. SceneLoader._ShowLoadingScreen = value;
  70124. },
  70125. enumerable: true,
  70126. configurable: true
  70127. });
  70128. Object.defineProperty(SceneLoader, "loggingLevel", {
  70129. get: function () {
  70130. return SceneLoader._loggingLevel;
  70131. },
  70132. set: function (value) {
  70133. SceneLoader._loggingLevel = value;
  70134. },
  70135. enumerable: true,
  70136. configurable: true
  70137. });
  70138. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  70139. get: function () {
  70140. return SceneLoader._CleanBoneMatrixWeights;
  70141. },
  70142. set: function (value) {
  70143. SceneLoader._CleanBoneMatrixWeights = value;
  70144. },
  70145. enumerable: true,
  70146. configurable: true
  70147. });
  70148. SceneLoader._getDefaultPlugin = function () {
  70149. return SceneLoader._registeredPlugins[".babylon"];
  70150. };
  70151. SceneLoader._getPluginForExtension = function (extension) {
  70152. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  70153. if (registeredPlugin) {
  70154. return registeredPlugin;
  70155. }
  70156. 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");
  70157. return SceneLoader._getDefaultPlugin();
  70158. };
  70159. SceneLoader._getPluginForDirectLoad = function (data) {
  70160. for (var extension in SceneLoader._registeredPlugins) {
  70161. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  70162. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  70163. return SceneLoader._registeredPlugins[extension];
  70164. }
  70165. }
  70166. return SceneLoader._getDefaultPlugin();
  70167. };
  70168. SceneLoader._getPluginForFilename = function (sceneFilename) {
  70169. if (sceneFilename.name) {
  70170. sceneFilename = sceneFilename.name;
  70171. }
  70172. var queryStringPosition = sceneFilename.indexOf("?");
  70173. if (queryStringPosition !== -1) {
  70174. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  70175. }
  70176. var dotPosition = sceneFilename.lastIndexOf(".");
  70177. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  70178. return SceneLoader._getPluginForExtension(extension);
  70179. };
  70180. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  70181. SceneLoader._getDirectLoad = function (sceneFilename) {
  70182. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  70183. return sceneFilename.substr(5);
  70184. }
  70185. return null;
  70186. };
  70187. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  70188. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  70189. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  70190. var plugin;
  70191. if (registeredPlugin.plugin.createPlugin) {
  70192. plugin = registeredPlugin.plugin.createPlugin();
  70193. }
  70194. else {
  70195. plugin = registeredPlugin.plugin;
  70196. }
  70197. var useArrayBuffer = registeredPlugin.isBinary;
  70198. var database;
  70199. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  70200. var dataCallback = function (data, responseURL) {
  70201. if (scene.isDisposed) {
  70202. onError("Scene has been disposed");
  70203. return;
  70204. }
  70205. scene.database = database;
  70206. onSuccess(plugin, data, responseURL);
  70207. };
  70208. var request = null;
  70209. var pluginDisposed = false;
  70210. var onDisposeObservable = plugin.onDisposeObservable;
  70211. if (onDisposeObservable) {
  70212. onDisposeObservable.add(function () {
  70213. pluginDisposed = true;
  70214. if (request) {
  70215. request.abort();
  70216. request = null;
  70217. }
  70218. onDispose();
  70219. });
  70220. }
  70221. var manifestChecked = function () {
  70222. if (pluginDisposed) {
  70223. return;
  70224. }
  70225. var url = rootUrl + sceneFilename;
  70226. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  70227. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  70228. } : undefined, database, useArrayBuffer, function (request, exception) {
  70229. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  70230. });
  70231. };
  70232. if (directLoad) {
  70233. dataCallback(directLoad);
  70234. return plugin;
  70235. }
  70236. if (rootUrl.indexOf("file:") === -1) {
  70237. var engine = scene.getEngine();
  70238. var canUseOfflineSupport = engine.enableOfflineSupport;
  70239. if (canUseOfflineSupport) {
  70240. // Also check for exceptions
  70241. var exceptionFound = false;
  70242. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  70243. var regex = _a[_i];
  70244. if (regex.test(rootUrl + sceneFilename)) {
  70245. exceptionFound = true;
  70246. break;
  70247. }
  70248. }
  70249. canUseOfflineSupport = !exceptionFound;
  70250. }
  70251. if (canUseOfflineSupport) {
  70252. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  70253. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  70254. }
  70255. else {
  70256. manifestChecked();
  70257. }
  70258. }
  70259. // Loading file from disk via input file or drag'n'drop
  70260. else {
  70261. var fileOrString = sceneFilename;
  70262. if (fileOrString.name) { // File
  70263. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  70264. }
  70265. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  70266. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  70267. }
  70268. else {
  70269. onError("Unable to find file named " + sceneFilename);
  70270. }
  70271. }
  70272. return plugin;
  70273. };
  70274. // Public functions
  70275. SceneLoader.GetPluginForExtension = function (extension) {
  70276. return SceneLoader._getPluginForExtension(extension).plugin;
  70277. };
  70278. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  70279. return !!SceneLoader._registeredPlugins[extension];
  70280. };
  70281. SceneLoader.RegisterPlugin = function (plugin) {
  70282. if (typeof plugin.extensions === "string") {
  70283. var extension = plugin.extensions;
  70284. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  70285. plugin: plugin,
  70286. isBinary: false
  70287. };
  70288. }
  70289. else {
  70290. var extensions = plugin.extensions;
  70291. Object.keys(extensions).forEach(function (extension) {
  70292. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  70293. plugin: plugin,
  70294. isBinary: extensions[extension].isBinary
  70295. };
  70296. });
  70297. }
  70298. };
  70299. /**
  70300. * Import meshes into a scene
  70301. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  70302. * @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)
  70303. * @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)
  70304. * @param scene the instance of BABYLON.Scene to append to
  70305. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  70306. * @param onProgress a callback with a progress event for each file being loaded
  70307. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  70308. * @param pluginExtension the extension used to determine the plugin
  70309. * @returns The loaded plugin
  70310. */
  70311. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  70312. if (sceneFilename === void 0) { sceneFilename = ""; }
  70313. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70314. if (onSuccess === void 0) { onSuccess = null; }
  70315. if (onProgress === void 0) { onProgress = null; }
  70316. if (onError === void 0) { onError = null; }
  70317. if (pluginExtension === void 0) { pluginExtension = null; }
  70318. if (!scene) {
  70319. BABYLON.Tools.Error("No scene available to import mesh to");
  70320. return null;
  70321. }
  70322. if (!sceneFilename) {
  70323. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  70324. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  70325. }
  70326. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  70327. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  70328. return null;
  70329. }
  70330. var loadingToken = {};
  70331. scene._addPendingData(loadingToken);
  70332. var disposeHandler = function () {
  70333. scene._removePendingData(loadingToken);
  70334. };
  70335. var errorHandler = function (message, exception) {
  70336. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  70337. if (onError) {
  70338. onError(scene, errorMessage, exception);
  70339. }
  70340. else {
  70341. BABYLON.Tools.Error(errorMessage);
  70342. // should the exception be thrown?
  70343. }
  70344. disposeHandler();
  70345. };
  70346. var progressHandler = onProgress ? function (event) {
  70347. try {
  70348. onProgress(event);
  70349. }
  70350. catch (e) {
  70351. errorHandler("Error in onProgress callback", e);
  70352. }
  70353. } : undefined;
  70354. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  70355. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  70356. if (onSuccess) {
  70357. try {
  70358. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  70359. }
  70360. catch (e) {
  70361. errorHandler("Error in onSuccess callback", e);
  70362. }
  70363. }
  70364. scene._removePendingData(loadingToken);
  70365. };
  70366. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  70367. if (plugin.rewriteRootURL) {
  70368. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  70369. }
  70370. if (sceneFilename === "") {
  70371. if (sceneFilename === "") {
  70372. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  70373. }
  70374. }
  70375. if (plugin.importMesh) {
  70376. var syncedPlugin = plugin;
  70377. var meshes = new Array();
  70378. var particleSystems = new Array();
  70379. var skeletons = new Array();
  70380. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  70381. return;
  70382. }
  70383. scene.loadingPluginName = plugin.name;
  70384. successHandler(meshes, particleSystems, skeletons, []);
  70385. }
  70386. else {
  70387. var asyncedPlugin = plugin;
  70388. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  70389. scene.loadingPluginName = plugin.name;
  70390. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  70391. }).catch(function (error) {
  70392. errorHandler(error.message, error);
  70393. });
  70394. }
  70395. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  70396. };
  70397. /**
  70398. * Import meshes into a scene
  70399. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  70400. * @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)
  70401. * @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)
  70402. * @param scene the instance of BABYLON.Scene to append to
  70403. * @param onProgress a callback with a progress event for each file being loaded
  70404. * @param pluginExtension the extension used to determine the plugin
  70405. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  70406. */
  70407. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  70408. if (sceneFilename === void 0) { sceneFilename = ""; }
  70409. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70410. if (onProgress === void 0) { onProgress = null; }
  70411. if (pluginExtension === void 0) { pluginExtension = null; }
  70412. return new Promise(function (resolve, reject) {
  70413. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  70414. resolve({
  70415. meshes: meshes,
  70416. particleSystems: particleSystems,
  70417. skeletons: skeletons,
  70418. animationGroups: animationGroups
  70419. });
  70420. }, onProgress, function (scene, message, exception) {
  70421. reject(exception || new Error(message));
  70422. }, pluginExtension);
  70423. });
  70424. };
  70425. /**
  70426. * Load a scene
  70427. * @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)
  70428. * @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)
  70429. * @param engine is the instance of BABYLON.Engine to use to create the scene
  70430. * @param onSuccess a callback with the scene when import succeeds
  70431. * @param onProgress a callback with a progress event for each file being loaded
  70432. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  70433. * @param pluginExtension the extension used to determine the plugin
  70434. * @returns The loaded plugin
  70435. */
  70436. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  70437. if (onSuccess === void 0) { onSuccess = null; }
  70438. if (onProgress === void 0) { onProgress = null; }
  70439. if (onError === void 0) { onError = null; }
  70440. if (pluginExtension === void 0) { pluginExtension = null; }
  70441. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  70442. };
  70443. /**
  70444. * Load a scene
  70445. * @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)
  70446. * @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)
  70447. * @param engine is the instance of BABYLON.Engine to use to create the scene
  70448. * @param onProgress a callback with a progress event for each file being loaded
  70449. * @param pluginExtension the extension used to determine the plugin
  70450. * @returns The loaded scene
  70451. */
  70452. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  70453. if (onProgress === void 0) { onProgress = null; }
  70454. if (pluginExtension === void 0) { pluginExtension = null; }
  70455. return new Promise(function (resolve, reject) {
  70456. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  70457. resolve(scene);
  70458. }, onProgress, function (scene, message, exception) {
  70459. reject(exception || new Error(message));
  70460. }, pluginExtension);
  70461. });
  70462. };
  70463. /**
  70464. * Append a scene
  70465. * @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)
  70466. * @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)
  70467. * @param scene is the instance of BABYLON.Scene to append to
  70468. * @param onSuccess a callback with the scene when import succeeds
  70469. * @param onProgress a callback with a progress event for each file being loaded
  70470. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  70471. * @param pluginExtension the extension used to determine the plugin
  70472. * @returns The loaded plugin
  70473. */
  70474. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  70475. if (sceneFilename === void 0) { sceneFilename = ""; }
  70476. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70477. if (onSuccess === void 0) { onSuccess = null; }
  70478. if (onProgress === void 0) { onProgress = null; }
  70479. if (onError === void 0) { onError = null; }
  70480. if (pluginExtension === void 0) { pluginExtension = null; }
  70481. if (!scene) {
  70482. BABYLON.Tools.Error("No scene available to append to");
  70483. return null;
  70484. }
  70485. if (!sceneFilename) {
  70486. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  70487. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  70488. }
  70489. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  70490. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  70491. return null;
  70492. }
  70493. if (SceneLoader.ShowLoadingScreen) {
  70494. scene.getEngine().displayLoadingUI();
  70495. }
  70496. var loadingToken = {};
  70497. scene._addPendingData(loadingToken);
  70498. var disposeHandler = function () {
  70499. scene._removePendingData(loadingToken);
  70500. scene.getEngine().hideLoadingUI();
  70501. };
  70502. var errorHandler = function (message, exception) {
  70503. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  70504. if (onError) {
  70505. onError(scene, errorMessage, exception);
  70506. }
  70507. else {
  70508. BABYLON.Tools.Error(errorMessage);
  70509. // should the exception be thrown?
  70510. }
  70511. disposeHandler();
  70512. };
  70513. var progressHandler = onProgress ? function (event) {
  70514. try {
  70515. onProgress(event);
  70516. }
  70517. catch (e) {
  70518. errorHandler("Error in onProgress callback", e);
  70519. }
  70520. } : undefined;
  70521. var successHandler = function () {
  70522. if (onSuccess) {
  70523. try {
  70524. onSuccess(scene);
  70525. }
  70526. catch (e) {
  70527. errorHandler("Error in onSuccess callback", e);
  70528. }
  70529. }
  70530. scene._removePendingData(loadingToken);
  70531. };
  70532. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  70533. if (sceneFilename === "") {
  70534. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  70535. }
  70536. if (plugin.load) {
  70537. var syncedPlugin = plugin;
  70538. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  70539. return;
  70540. }
  70541. scene.loadingPluginName = plugin.name;
  70542. successHandler();
  70543. }
  70544. else {
  70545. var asyncedPlugin = plugin;
  70546. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  70547. scene.loadingPluginName = plugin.name;
  70548. successHandler();
  70549. }).catch(function (error) {
  70550. errorHandler(error.message, error);
  70551. });
  70552. }
  70553. if (SceneLoader.ShowLoadingScreen) {
  70554. scene.executeWhenReady(function () {
  70555. scene.getEngine().hideLoadingUI();
  70556. });
  70557. }
  70558. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  70559. };
  70560. /**
  70561. * Append a scene
  70562. * @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)
  70563. * @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)
  70564. * @param scene is the instance of BABYLON.Scene to append to
  70565. * @param onProgress a callback with a progress event for each file being loaded
  70566. * @param pluginExtension the extension used to determine the plugin
  70567. * @returns The given scene
  70568. */
  70569. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  70570. if (sceneFilename === void 0) { sceneFilename = ""; }
  70571. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70572. if (onProgress === void 0) { onProgress = null; }
  70573. if (pluginExtension === void 0) { pluginExtension = null; }
  70574. return new Promise(function (resolve, reject) {
  70575. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  70576. resolve(scene);
  70577. }, onProgress, function (scene, message, exception) {
  70578. reject(exception || new Error(message));
  70579. }, pluginExtension);
  70580. });
  70581. };
  70582. /**
  70583. * Load a scene into an asset container
  70584. * @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)
  70585. * @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)
  70586. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  70587. * @param onSuccess a callback with the scene when import succeeds
  70588. * @param onProgress a callback with a progress event for each file being loaded
  70589. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  70590. * @param pluginExtension the extension used to determine the plugin
  70591. * @returns The loaded plugin
  70592. */
  70593. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  70594. if (sceneFilename === void 0) { sceneFilename = ""; }
  70595. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70596. if (onSuccess === void 0) { onSuccess = null; }
  70597. if (onProgress === void 0) { onProgress = null; }
  70598. if (onError === void 0) { onError = null; }
  70599. if (pluginExtension === void 0) { pluginExtension = null; }
  70600. if (!scene) {
  70601. BABYLON.Tools.Error("No scene available to load asset container to");
  70602. return null;
  70603. }
  70604. if (!sceneFilename) {
  70605. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  70606. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  70607. }
  70608. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  70609. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  70610. return null;
  70611. }
  70612. var loadingToken = {};
  70613. scene._addPendingData(loadingToken);
  70614. var disposeHandler = function () {
  70615. scene._removePendingData(loadingToken);
  70616. };
  70617. var errorHandler = function (message, exception) {
  70618. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  70619. if (onError) {
  70620. onError(scene, errorMessage, exception);
  70621. }
  70622. else {
  70623. BABYLON.Tools.Error(errorMessage);
  70624. // should the exception be thrown?
  70625. }
  70626. disposeHandler();
  70627. };
  70628. var progressHandler = onProgress ? function (event) {
  70629. try {
  70630. onProgress(event);
  70631. }
  70632. catch (e) {
  70633. errorHandler("Error in onProgress callback", e);
  70634. }
  70635. } : undefined;
  70636. var successHandler = function (assets) {
  70637. if (onSuccess) {
  70638. try {
  70639. onSuccess(assets);
  70640. }
  70641. catch (e) {
  70642. errorHandler("Error in onSuccess callback", e);
  70643. }
  70644. }
  70645. scene._removePendingData(loadingToken);
  70646. };
  70647. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  70648. if (plugin.loadAssetContainer) {
  70649. var syncedPlugin = plugin;
  70650. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  70651. if (!assetContainer) {
  70652. return;
  70653. }
  70654. scene.loadingPluginName = plugin.name;
  70655. successHandler(assetContainer);
  70656. }
  70657. else if (plugin.loadAssetContainerAsync) {
  70658. var asyncedPlugin = plugin;
  70659. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  70660. scene.loadingPluginName = plugin.name;
  70661. successHandler(assetContainer);
  70662. }).catch(function (error) {
  70663. errorHandler(error.message, error);
  70664. });
  70665. }
  70666. else {
  70667. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  70668. }
  70669. if (SceneLoader.ShowLoadingScreen) {
  70670. scene.executeWhenReady(function () {
  70671. scene.getEngine().hideLoadingUI();
  70672. });
  70673. }
  70674. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  70675. };
  70676. /**
  70677. * Load a scene into an asset container
  70678. * @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)
  70679. * @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)
  70680. * @param scene is the instance of BABYLON.Scene to append to
  70681. * @param onProgress a callback with a progress event for each file being loaded
  70682. * @param pluginExtension the extension used to determine the plugin
  70683. * @returns The loaded asset container
  70684. */
  70685. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  70686. if (sceneFilename === void 0) { sceneFilename = ""; }
  70687. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  70688. if (onProgress === void 0) { onProgress = null; }
  70689. if (pluginExtension === void 0) { pluginExtension = null; }
  70690. return new Promise(function (resolve, reject) {
  70691. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  70692. resolve(assetContainer);
  70693. }, onProgress, function (scene, message, exception) {
  70694. reject(exception || new Error(message));
  70695. }, pluginExtension);
  70696. });
  70697. };
  70698. // Flags
  70699. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  70700. SceneLoader._ShowLoadingScreen = true;
  70701. SceneLoader._CleanBoneMatrixWeights = false;
  70702. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  70703. // Members
  70704. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  70705. SceneLoader._registeredPlugins = {};
  70706. return SceneLoader;
  70707. }());
  70708. BABYLON.SceneLoader = SceneLoader;
  70709. ;
  70710. })(BABYLON || (BABYLON = {}));
  70711. //# sourceMappingURL=babylon.sceneLoader.js.map
  70712. var BABYLON;
  70713. (function (BABYLON) {
  70714. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  70715. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  70716. var parsedMaterial = parsedData.materials[index];
  70717. if (parsedMaterial.id === id) {
  70718. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  70719. }
  70720. }
  70721. return null;
  70722. };
  70723. var isDescendantOf = function (mesh, names, hierarchyIds) {
  70724. for (var i in names) {
  70725. if (mesh.name === names[i]) {
  70726. hierarchyIds.push(mesh.id);
  70727. return true;
  70728. }
  70729. }
  70730. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  70731. hierarchyIds.push(mesh.id);
  70732. return true;
  70733. }
  70734. return false;
  70735. };
  70736. var logOperation = function (operation, producer) {
  70737. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  70738. };
  70739. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  70740. if (addToScene === void 0) { addToScene = false; }
  70741. var container = new BABYLON.AssetContainer(scene);
  70742. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  70743. // when SceneLoader.debugLogging = true (default), or exception encountered.
  70744. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  70745. // and avoid problems with multiple concurrent .babylon loads.
  70746. var log = "importScene has failed JSON parse";
  70747. try {
  70748. var parsedData = JSON.parse(data);
  70749. log = "";
  70750. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  70751. var index;
  70752. var cache;
  70753. // Lights
  70754. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  70755. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  70756. var parsedLight = parsedData.lights[index];
  70757. var light = BABYLON.Light.Parse(parsedLight, scene);
  70758. if (light) {
  70759. container.lights.push(light);
  70760. log += (index === 0 ? "\n\tLights:" : "");
  70761. log += "\n\t\t" + light.toString(fullDetails);
  70762. }
  70763. }
  70764. }
  70765. // Animations
  70766. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  70767. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  70768. var parsedAnimation = parsedData.animations[index];
  70769. var animation = BABYLON.Animation.Parse(parsedAnimation);
  70770. scene.animations.push(animation);
  70771. container.animations.push(animation);
  70772. log += (index === 0 ? "\n\tAnimations:" : "");
  70773. log += "\n\t\t" + animation.toString(fullDetails);
  70774. }
  70775. }
  70776. // Materials
  70777. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  70778. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  70779. var parsedMaterial = parsedData.materials[index];
  70780. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  70781. container.materials.push(mat);
  70782. log += (index === 0 ? "\n\tMaterials:" : "");
  70783. log += "\n\t\t" + mat.toString(fullDetails);
  70784. }
  70785. }
  70786. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  70787. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  70788. var parsedMultiMaterial = parsedData.multiMaterials[index];
  70789. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  70790. container.multiMaterials.push(mmat);
  70791. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  70792. log += "\n\t\t" + mmat.toString(fullDetails);
  70793. }
  70794. }
  70795. // Morph targets
  70796. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  70797. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  70798. var managerData = _a[_i];
  70799. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  70800. }
  70801. }
  70802. // Skeletons
  70803. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  70804. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  70805. var parsedSkeleton = parsedData.skeletons[index];
  70806. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  70807. container.skeletons.push(skeleton);
  70808. log += (index === 0 ? "\n\tSkeletons:" : "");
  70809. log += "\n\t\t" + skeleton.toString(fullDetails);
  70810. }
  70811. }
  70812. // Geometries
  70813. var geometries = parsedData.geometries;
  70814. if (geometries !== undefined && geometries !== null) {
  70815. var addedGeometry = new Array();
  70816. // Boxes
  70817. var boxes = geometries.boxes;
  70818. if (boxes !== undefined && boxes !== null) {
  70819. for (index = 0, cache = boxes.length; index < cache; index++) {
  70820. var parsedBox = boxes[index];
  70821. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  70822. }
  70823. }
  70824. // Spheres
  70825. var spheres = geometries.spheres;
  70826. if (spheres !== undefined && spheres !== null) {
  70827. for (index = 0, cache = spheres.length; index < cache; index++) {
  70828. var parsedSphere = spheres[index];
  70829. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  70830. }
  70831. }
  70832. // Cylinders
  70833. var cylinders = geometries.cylinders;
  70834. if (cylinders !== undefined && cylinders !== null) {
  70835. for (index = 0, cache = cylinders.length; index < cache; index++) {
  70836. var parsedCylinder = cylinders[index];
  70837. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  70838. }
  70839. }
  70840. // Toruses
  70841. var toruses = geometries.toruses;
  70842. if (toruses !== undefined && toruses !== null) {
  70843. for (index = 0, cache = toruses.length; index < cache; index++) {
  70844. var parsedTorus = toruses[index];
  70845. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  70846. }
  70847. }
  70848. // Grounds
  70849. var grounds = geometries.grounds;
  70850. if (grounds !== undefined && grounds !== null) {
  70851. for (index = 0, cache = grounds.length; index < cache; index++) {
  70852. var parsedGround = grounds[index];
  70853. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  70854. }
  70855. }
  70856. // Planes
  70857. var planes = geometries.planes;
  70858. if (planes !== undefined && planes !== null) {
  70859. for (index = 0, cache = planes.length; index < cache; index++) {
  70860. var parsedPlane = planes[index];
  70861. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  70862. }
  70863. }
  70864. // TorusKnots
  70865. var torusKnots = geometries.torusKnots;
  70866. if (torusKnots !== undefined && torusKnots !== null) {
  70867. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  70868. var parsedTorusKnot = torusKnots[index];
  70869. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  70870. }
  70871. }
  70872. // VertexData
  70873. var vertexData = geometries.vertexData;
  70874. if (vertexData !== undefined && vertexData !== null) {
  70875. for (index = 0, cache = vertexData.length; index < cache; index++) {
  70876. var parsedVertexData = vertexData[index];
  70877. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  70878. }
  70879. }
  70880. addedGeometry.forEach(function (g) {
  70881. if (g) {
  70882. container.geometries.push(g);
  70883. }
  70884. });
  70885. }
  70886. // Transform nodes
  70887. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  70888. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  70889. var parsedTransformNode = parsedData.transformNodes[index];
  70890. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  70891. container.transformNodes.push(node);
  70892. }
  70893. }
  70894. // Meshes
  70895. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  70896. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  70897. var parsedMesh = parsedData.meshes[index];
  70898. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  70899. container.meshes.push(mesh);
  70900. log += (index === 0 ? "\n\tMeshes:" : "");
  70901. log += "\n\t\t" + mesh.toString(fullDetails);
  70902. }
  70903. }
  70904. // Cameras
  70905. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  70906. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  70907. var parsedCamera = parsedData.cameras[index];
  70908. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  70909. container.cameras.push(camera);
  70910. log += (index === 0 ? "\n\tCameras:" : "");
  70911. log += "\n\t\t" + camera.toString(fullDetails);
  70912. }
  70913. }
  70914. // Browsing all the graph to connect the dots
  70915. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  70916. var camera = scene.cameras[index];
  70917. if (camera._waitingParentId) {
  70918. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  70919. camera._waitingParentId = null;
  70920. }
  70921. }
  70922. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  70923. var light_1 = scene.lights[index];
  70924. if (light_1 && light_1._waitingParentId) {
  70925. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  70926. light_1._waitingParentId = null;
  70927. }
  70928. }
  70929. // Sounds
  70930. // TODO: add sound
  70931. var loadedSounds = [];
  70932. var loadedSound;
  70933. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  70934. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  70935. var parsedSound = parsedData.sounds[index];
  70936. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  70937. if (!parsedSound.url)
  70938. parsedSound.url = parsedSound.name;
  70939. if (!loadedSounds[parsedSound.url]) {
  70940. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  70941. loadedSounds[parsedSound.url] = loadedSound;
  70942. container.sounds.push(loadedSound);
  70943. }
  70944. else {
  70945. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  70946. }
  70947. }
  70948. else {
  70949. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  70950. }
  70951. }
  70952. }
  70953. loadedSounds = [];
  70954. // Connect parents & children and parse actions
  70955. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  70956. var transformNode = scene.transformNodes[index];
  70957. if (transformNode._waitingParentId) {
  70958. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  70959. transformNode._waitingParentId = null;
  70960. }
  70961. }
  70962. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  70963. var mesh = scene.meshes[index];
  70964. if (mesh._waitingParentId) {
  70965. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  70966. mesh._waitingParentId = null;
  70967. }
  70968. if (mesh._waitingActions) {
  70969. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  70970. mesh._waitingActions = null;
  70971. }
  70972. }
  70973. // freeze world matrix application
  70974. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  70975. var currentMesh = scene.meshes[index];
  70976. if (currentMesh._waitingFreezeWorldMatrix) {
  70977. currentMesh.freezeWorldMatrix();
  70978. currentMesh._waitingFreezeWorldMatrix = null;
  70979. }
  70980. else {
  70981. currentMesh.computeWorldMatrix(true);
  70982. }
  70983. }
  70984. // Shadows
  70985. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  70986. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  70987. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  70988. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  70989. // SG would be available on their associated lights
  70990. }
  70991. }
  70992. // Lights exclusions / inclusions
  70993. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  70994. var light_2 = scene.lights[index];
  70995. // Excluded check
  70996. if (light_2._excludedMeshesIds.length > 0) {
  70997. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  70998. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  70999. if (excludedMesh) {
  71000. light_2.excludedMeshes.push(excludedMesh);
  71001. }
  71002. }
  71003. light_2._excludedMeshesIds = [];
  71004. }
  71005. // Included check
  71006. if (light_2._includedOnlyMeshesIds.length > 0) {
  71007. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  71008. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  71009. if (includedOnlyMesh) {
  71010. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  71011. }
  71012. }
  71013. light_2._includedOnlyMeshesIds = [];
  71014. }
  71015. }
  71016. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  71017. // Actions (scene)
  71018. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  71019. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  71020. }
  71021. if (!addToScene) {
  71022. container.removeAllFromScene();
  71023. }
  71024. }
  71025. catch (err) {
  71026. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  71027. if (onError) {
  71028. onError(msg, err);
  71029. }
  71030. else {
  71031. BABYLON.Tools.Log(msg);
  71032. throw err;
  71033. }
  71034. }
  71035. finally {
  71036. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  71037. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  71038. }
  71039. }
  71040. return container;
  71041. };
  71042. BABYLON.SceneLoader.RegisterPlugin({
  71043. name: "babylon.js",
  71044. extensions: ".babylon",
  71045. canDirectLoad: function (data) {
  71046. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  71047. return true;
  71048. }
  71049. return false;
  71050. },
  71051. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  71052. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  71053. // when SceneLoader.debugLogging = true (default), or exception encountered.
  71054. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  71055. // and avoid problems with multiple concurrent .babylon loads.
  71056. var log = "importMesh has failed JSON parse";
  71057. try {
  71058. var parsedData = JSON.parse(data);
  71059. log = "";
  71060. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  71061. if (!meshesNames) {
  71062. meshesNames = null;
  71063. }
  71064. else if (!Array.isArray(meshesNames)) {
  71065. meshesNames = [meshesNames];
  71066. }
  71067. var hierarchyIds = new Array();
  71068. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  71069. var loadedSkeletonsIds = [];
  71070. var loadedMaterialsIds = [];
  71071. var index;
  71072. var cache;
  71073. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  71074. var parsedMesh = parsedData.meshes[index];
  71075. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  71076. if (meshesNames !== null) {
  71077. // Remove found mesh name from list.
  71078. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  71079. }
  71080. //Geometry?
  71081. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  71082. //does the file contain geometries?
  71083. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  71084. //find the correct geometry and add it to the scene
  71085. var found = false;
  71086. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  71087. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  71088. return;
  71089. }
  71090. else {
  71091. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  71092. if (parsedGeometryData.id === parsedMesh.geometryId) {
  71093. switch (geometryType) {
  71094. case "boxes":
  71095. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  71096. break;
  71097. case "spheres":
  71098. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  71099. break;
  71100. case "cylinders":
  71101. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  71102. break;
  71103. case "toruses":
  71104. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  71105. break;
  71106. case "grounds":
  71107. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  71108. break;
  71109. case "planes":
  71110. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  71111. break;
  71112. case "torusKnots":
  71113. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  71114. break;
  71115. case "vertexData":
  71116. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  71117. break;
  71118. }
  71119. found = true;
  71120. }
  71121. });
  71122. }
  71123. });
  71124. if (found === false) {
  71125. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  71126. }
  71127. }
  71128. }
  71129. // Material ?
  71130. if (parsedMesh.materialId) {
  71131. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  71132. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  71133. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  71134. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  71135. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  71136. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  71137. var subMatId = parsedMultiMaterial.materials[matIndex];
  71138. loadedMaterialsIds.push(subMatId);
  71139. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  71140. if (mat) {
  71141. log += "\n\tMaterial " + mat.toString(fullDetails);
  71142. }
  71143. }
  71144. loadedMaterialsIds.push(parsedMultiMaterial.id);
  71145. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  71146. if (mmat) {
  71147. materialFound = true;
  71148. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  71149. }
  71150. break;
  71151. }
  71152. }
  71153. }
  71154. if (materialFound === false) {
  71155. loadedMaterialsIds.push(parsedMesh.materialId);
  71156. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  71157. if (!mat) {
  71158. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  71159. }
  71160. else {
  71161. log += "\n\tMaterial " + mat.toString(fullDetails);
  71162. }
  71163. }
  71164. }
  71165. // Skeleton ?
  71166. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  71167. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  71168. if (skeletonAlreadyLoaded === false) {
  71169. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  71170. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  71171. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  71172. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  71173. skeletons.push(skeleton);
  71174. loadedSkeletonsIds.push(parsedSkeleton.id);
  71175. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  71176. }
  71177. }
  71178. }
  71179. }
  71180. // Morph targets ?
  71181. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  71182. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  71183. var managerData = _a[_i];
  71184. BABYLON.MorphTargetManager.Parse(managerData, scene);
  71185. }
  71186. }
  71187. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  71188. meshes.push(mesh);
  71189. log += "\n\tMesh " + mesh.toString(fullDetails);
  71190. }
  71191. }
  71192. // Connecting parents
  71193. var currentMesh;
  71194. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  71195. currentMesh = scene.meshes[index];
  71196. if (currentMesh._waitingParentId) {
  71197. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  71198. currentMesh._waitingParentId = null;
  71199. }
  71200. }
  71201. // freeze and compute world matrix application
  71202. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  71203. currentMesh = scene.meshes[index];
  71204. if (currentMesh._waitingFreezeWorldMatrix) {
  71205. currentMesh.freezeWorldMatrix();
  71206. currentMesh._waitingFreezeWorldMatrix = null;
  71207. }
  71208. else {
  71209. currentMesh.computeWorldMatrix(true);
  71210. }
  71211. }
  71212. }
  71213. // Particles
  71214. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  71215. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  71216. if (parser) {
  71217. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  71218. var parsedParticleSystem = parsedData.particleSystems[index];
  71219. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  71220. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  71221. }
  71222. }
  71223. }
  71224. }
  71225. return true;
  71226. }
  71227. catch (err) {
  71228. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  71229. if (onError) {
  71230. onError(msg, err);
  71231. }
  71232. else {
  71233. BABYLON.Tools.Log(msg);
  71234. throw err;
  71235. }
  71236. }
  71237. finally {
  71238. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  71239. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  71240. }
  71241. }
  71242. return false;
  71243. },
  71244. load: function (scene, data, rootUrl, onError) {
  71245. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  71246. // when SceneLoader.debugLogging = true (default), or exception encountered.
  71247. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  71248. // and avoid problems with multiple concurrent .babylon loads.
  71249. var log = "importScene has failed JSON parse";
  71250. try {
  71251. var parsedData = JSON.parse(data);
  71252. log = "";
  71253. // Scene
  71254. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  71255. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  71256. }
  71257. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  71258. scene.autoClear = parsedData.autoClear;
  71259. }
  71260. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  71261. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  71262. }
  71263. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  71264. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  71265. }
  71266. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  71267. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  71268. }
  71269. // Fog
  71270. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  71271. scene.fogMode = parsedData.fogMode;
  71272. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  71273. scene.fogStart = parsedData.fogStart;
  71274. scene.fogEnd = parsedData.fogEnd;
  71275. scene.fogDensity = parsedData.fogDensity;
  71276. log += "\tFog mode for scene: ";
  71277. switch (scene.fogMode) {
  71278. // getters not compiling, so using hardcoded
  71279. case 1:
  71280. log += "exp\n";
  71281. break;
  71282. case 2:
  71283. log += "exp2\n";
  71284. break;
  71285. case 3:
  71286. log += "linear\n";
  71287. break;
  71288. }
  71289. }
  71290. //Physics
  71291. if (parsedData.physicsEnabled) {
  71292. var physicsPlugin;
  71293. if (parsedData.physicsEngine === "cannon") {
  71294. physicsPlugin = new BABYLON.CannonJSPlugin();
  71295. }
  71296. else if (parsedData.physicsEngine === "oimo") {
  71297. physicsPlugin = new BABYLON.OimoJSPlugin();
  71298. }
  71299. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  71300. //else - default engine, which is currently oimo
  71301. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  71302. scene.enablePhysics(physicsGravity, physicsPlugin);
  71303. }
  71304. // Metadata
  71305. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  71306. scene.metadata = parsedData.metadata;
  71307. }
  71308. //collisions, if defined. otherwise, default is true
  71309. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  71310. scene.collisionsEnabled = parsedData.collisionsEnabled;
  71311. }
  71312. scene.workerCollisions = !!parsedData.workerCollisions;
  71313. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  71314. if (!container) {
  71315. return false;
  71316. }
  71317. if (parsedData.autoAnimate) {
  71318. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  71319. }
  71320. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  71321. scene.setActiveCameraByID(parsedData.activeCameraID);
  71322. }
  71323. // Environment texture
  71324. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  71325. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  71326. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  71327. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  71328. if (parsedData.environmentTextureRotationY) {
  71329. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  71330. }
  71331. scene.environmentTexture = hdrTexture;
  71332. }
  71333. else {
  71334. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  71335. if (parsedData.environmentTextureRotationY) {
  71336. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  71337. }
  71338. scene.environmentTexture = cubeTexture;
  71339. }
  71340. if (parsedData.createDefaultSkybox === true) {
  71341. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  71342. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  71343. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  71344. }
  71345. }
  71346. // Finish
  71347. return true;
  71348. }
  71349. catch (err) {
  71350. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  71351. if (onError) {
  71352. onError(msg, err);
  71353. }
  71354. else {
  71355. BABYLON.Tools.Log(msg);
  71356. throw err;
  71357. }
  71358. }
  71359. finally {
  71360. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  71361. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  71362. }
  71363. }
  71364. return false;
  71365. },
  71366. loadAssetContainer: function (scene, data, rootUrl, onError) {
  71367. var container = loadAssetContainer(scene, data, rootUrl, onError);
  71368. return container;
  71369. }
  71370. });
  71371. })(BABYLON || (BABYLON = {}));
  71372. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  71373. var BABYLON;
  71374. (function (BABYLON) {
  71375. var FilesInput = /** @class */ (function () {
  71376. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  71377. this.onProcessFileCallback = function () { return true; };
  71378. this._engine = engine;
  71379. this._currentScene = scene;
  71380. this._sceneLoadedCallback = sceneLoadedCallback;
  71381. this._progressCallback = progressCallback;
  71382. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  71383. this._textureLoadingCallback = textureLoadingCallback;
  71384. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  71385. this._onReloadCallback = onReloadCallback;
  71386. this._errorCallback = errorCallback;
  71387. }
  71388. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  71389. var _this = this;
  71390. if (elementToMonitor) {
  71391. this._elementToMonitor = elementToMonitor;
  71392. this._dragEnterHandler = function (e) { _this.drag(e); };
  71393. this._dragOverHandler = function (e) { _this.drag(e); };
  71394. this._dropHandler = function (e) { _this.drop(e); };
  71395. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  71396. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  71397. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  71398. }
  71399. };
  71400. FilesInput.prototype.dispose = function () {
  71401. if (!this._elementToMonitor) {
  71402. return;
  71403. }
  71404. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  71405. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  71406. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  71407. };
  71408. FilesInput.prototype.renderFunction = function () {
  71409. if (this._additionalRenderLoopLogicCallback) {
  71410. this._additionalRenderLoopLogicCallback();
  71411. }
  71412. if (this._currentScene) {
  71413. if (this._textureLoadingCallback) {
  71414. var remaining = this._currentScene.getWaitingItemsCount();
  71415. if (remaining > 0) {
  71416. this._textureLoadingCallback(remaining);
  71417. }
  71418. }
  71419. this._currentScene.render();
  71420. }
  71421. };
  71422. FilesInput.prototype.drag = function (e) {
  71423. e.stopPropagation();
  71424. e.preventDefault();
  71425. };
  71426. FilesInput.prototype.drop = function (eventDrop) {
  71427. eventDrop.stopPropagation();
  71428. eventDrop.preventDefault();
  71429. this.loadFiles(eventDrop);
  71430. };
  71431. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  71432. var _this = this;
  71433. var reader = folder.createReader();
  71434. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  71435. reader.readEntries(function (entries) {
  71436. remaining.count += entries.length;
  71437. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  71438. var entry = entries_1[_i];
  71439. if (entry.isFile) {
  71440. entry.file(function (file) {
  71441. file.correctName = relativePath + file.name;
  71442. files.push(file);
  71443. if (--remaining.count === 0) {
  71444. callback();
  71445. }
  71446. });
  71447. }
  71448. else if (entry.isDirectory) {
  71449. _this._traverseFolder(entry, files, remaining, callback);
  71450. }
  71451. }
  71452. if (--remaining.count) {
  71453. callback();
  71454. }
  71455. });
  71456. };
  71457. FilesInput.prototype._processFiles = function (files) {
  71458. for (var i = 0; i < files.length; i++) {
  71459. var name = files[i].correctName.toLowerCase();
  71460. var extension = name.split('.').pop();
  71461. if (!this.onProcessFileCallback(files[i], name, extension)) {
  71462. continue;
  71463. }
  71464. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  71465. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  71466. this._sceneFileToLoad = files[i];
  71467. }
  71468. else {
  71469. FilesInput.FilesToLoad[name] = files[i];
  71470. }
  71471. }
  71472. };
  71473. FilesInput.prototype.loadFiles = function (event) {
  71474. var _this = this;
  71475. if (this._startingProcessingFilesCallback)
  71476. this._startingProcessingFilesCallback();
  71477. // Handling data transfer via drag'n'drop
  71478. if (event && event.dataTransfer && event.dataTransfer.files) {
  71479. this._filesToLoad = event.dataTransfer.files;
  71480. }
  71481. // Handling files from input files
  71482. if (event && event.target && event.target.files) {
  71483. this._filesToLoad = event.target.files;
  71484. }
  71485. if (this._filesToLoad && this._filesToLoad.length > 0) {
  71486. var files_1 = new Array();
  71487. var folders = [];
  71488. var items = event.dataTransfer ? event.dataTransfer.items : null;
  71489. for (var i = 0; i < this._filesToLoad.length; i++) {
  71490. var fileToLoad = this._filesToLoad[i];
  71491. var name_1 = fileToLoad.name.toLowerCase();
  71492. var entry = void 0;
  71493. fileToLoad.correctName = name_1;
  71494. if (items) {
  71495. var item = items[i];
  71496. if (item.getAsEntry) {
  71497. entry = item.getAsEntry();
  71498. }
  71499. else if (item.webkitGetAsEntry) {
  71500. entry = item.webkitGetAsEntry();
  71501. }
  71502. }
  71503. if (!entry) {
  71504. files_1.push(fileToLoad);
  71505. }
  71506. else {
  71507. if (entry.isDirectory) {
  71508. folders.push(entry);
  71509. }
  71510. else {
  71511. files_1.push(fileToLoad);
  71512. }
  71513. }
  71514. }
  71515. if (folders.length === 0) {
  71516. this._processFiles(files_1);
  71517. this._processReload();
  71518. }
  71519. else {
  71520. var remaining = { count: folders.length };
  71521. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  71522. var folder = folders_1[_i];
  71523. this._traverseFolder(folder, files_1, remaining, function () {
  71524. _this._processFiles(files_1);
  71525. if (remaining.count === 0) {
  71526. _this._processReload();
  71527. }
  71528. });
  71529. }
  71530. }
  71531. }
  71532. };
  71533. FilesInput.prototype._processReload = function () {
  71534. if (this._onReloadCallback) {
  71535. this._onReloadCallback(this._sceneFileToLoad);
  71536. }
  71537. else {
  71538. this.reload();
  71539. }
  71540. };
  71541. FilesInput.prototype.reload = function () {
  71542. var _this = this;
  71543. // If a scene file has been provided
  71544. if (this._sceneFileToLoad) {
  71545. if (this._currentScene) {
  71546. if (BABYLON.Tools.errorsCount > 0) {
  71547. BABYLON.Tools.ClearLogCache();
  71548. }
  71549. this._engine.stopRenderLoop();
  71550. }
  71551. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  71552. if (_this._progressCallback) {
  71553. _this._progressCallback(progress);
  71554. }
  71555. }).then(function (scene) {
  71556. if (_this._currentScene) {
  71557. _this._currentScene.dispose();
  71558. }
  71559. _this._currentScene = scene;
  71560. if (_this._sceneLoadedCallback) {
  71561. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  71562. }
  71563. // Wait for textures and shaders to be ready
  71564. _this._currentScene.executeWhenReady(function () {
  71565. _this._engine.runRenderLoop(function () {
  71566. _this.renderFunction();
  71567. });
  71568. });
  71569. }).catch(function (error) {
  71570. if (_this._errorCallback) {
  71571. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  71572. }
  71573. });
  71574. }
  71575. else {
  71576. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  71577. }
  71578. };
  71579. FilesInput.FilesToLoad = {};
  71580. return FilesInput;
  71581. }());
  71582. BABYLON.FilesInput = FilesInput;
  71583. })(BABYLON || (BABYLON = {}));
  71584. //# sourceMappingURL=babylon.filesInput.js.map
  71585. var BABYLON;
  71586. (function (BABYLON) {
  71587. var Tags = /** @class */ (function () {
  71588. function Tags() {
  71589. }
  71590. Tags.EnableFor = function (obj) {
  71591. obj._tags = obj._tags || {};
  71592. obj.hasTags = function () {
  71593. return Tags.HasTags(obj);
  71594. };
  71595. obj.addTags = function (tagsString) {
  71596. return Tags.AddTagsTo(obj, tagsString);
  71597. };
  71598. obj.removeTags = function (tagsString) {
  71599. return Tags.RemoveTagsFrom(obj, tagsString);
  71600. };
  71601. obj.matchesTagsQuery = function (tagsQuery) {
  71602. return Tags.MatchesQuery(obj, tagsQuery);
  71603. };
  71604. };
  71605. Tags.DisableFor = function (obj) {
  71606. delete obj._tags;
  71607. delete obj.hasTags;
  71608. delete obj.addTags;
  71609. delete obj.removeTags;
  71610. delete obj.matchesTagsQuery;
  71611. };
  71612. Tags.HasTags = function (obj) {
  71613. if (!obj._tags) {
  71614. return false;
  71615. }
  71616. return !BABYLON.Tools.IsEmpty(obj._tags);
  71617. };
  71618. Tags.GetTags = function (obj, asString) {
  71619. if (asString === void 0) { asString = true; }
  71620. if (!obj._tags) {
  71621. return null;
  71622. }
  71623. if (asString) {
  71624. var tagsArray = [];
  71625. for (var tag in obj._tags) {
  71626. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  71627. tagsArray.push(tag);
  71628. }
  71629. }
  71630. return tagsArray.join(" ");
  71631. }
  71632. else {
  71633. return obj._tags;
  71634. }
  71635. };
  71636. // the tags 'true' and 'false' are reserved and cannot be used as tags
  71637. // a tag cannot start with '||', '&&', and '!'
  71638. // it cannot contain whitespaces
  71639. Tags.AddTagsTo = function (obj, tagsString) {
  71640. if (!tagsString) {
  71641. return;
  71642. }
  71643. if (typeof tagsString !== "string") {
  71644. return;
  71645. }
  71646. var tags = tagsString.split(" ");
  71647. tags.forEach(function (tag, index, array) {
  71648. Tags._AddTagTo(obj, tag);
  71649. });
  71650. };
  71651. Tags._AddTagTo = function (obj, tag) {
  71652. tag = tag.trim();
  71653. if (tag === "" || tag === "true" || tag === "false") {
  71654. return;
  71655. }
  71656. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  71657. return;
  71658. }
  71659. Tags.EnableFor(obj);
  71660. obj._tags[tag] = true;
  71661. };
  71662. Tags.RemoveTagsFrom = function (obj, tagsString) {
  71663. if (!Tags.HasTags(obj)) {
  71664. return;
  71665. }
  71666. var tags = tagsString.split(" ");
  71667. for (var t in tags) {
  71668. Tags._RemoveTagFrom(obj, tags[t]);
  71669. }
  71670. };
  71671. Tags._RemoveTagFrom = function (obj, tag) {
  71672. delete obj._tags[tag];
  71673. };
  71674. Tags.MatchesQuery = function (obj, tagsQuery) {
  71675. if (tagsQuery === undefined) {
  71676. return true;
  71677. }
  71678. if (tagsQuery === "") {
  71679. return Tags.HasTags(obj);
  71680. }
  71681. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  71682. };
  71683. return Tags;
  71684. }());
  71685. BABYLON.Tags = Tags;
  71686. })(BABYLON || (BABYLON = {}));
  71687. //# sourceMappingURL=babylon.tags.js.map
  71688. var BABYLON;
  71689. (function (BABYLON) {
  71690. /**
  71691. * Class used to evalaute queries containing `and` and `or` operators
  71692. */
  71693. var AndOrNotEvaluator = /** @class */ (function () {
  71694. function AndOrNotEvaluator() {
  71695. }
  71696. /**
  71697. * Evaluate a query
  71698. * @param query defines the query to evaluate
  71699. * @param evaluateCallback defines the callback used to filter result
  71700. * @returns true if the query matches
  71701. */
  71702. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  71703. if (!query.match(/\([^\(\)]*\)/g)) {
  71704. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  71705. }
  71706. else {
  71707. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  71708. // remove parenthesis
  71709. r = r.slice(1, r.length - 1);
  71710. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  71711. });
  71712. }
  71713. if (query === "true") {
  71714. return true;
  71715. }
  71716. if (query === "false") {
  71717. return false;
  71718. }
  71719. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  71720. };
  71721. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  71722. evaluateCallback = evaluateCallback || (function (r) {
  71723. return r === "true" ? true : false;
  71724. });
  71725. var result;
  71726. var or = parenthesisContent.split("||");
  71727. for (var i in or) {
  71728. if (or.hasOwnProperty(i)) {
  71729. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  71730. var and = ori.split("&&");
  71731. if (and.length > 1) {
  71732. for (var j = 0; j < and.length; ++j) {
  71733. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  71734. if (andj !== "true" && andj !== "false") {
  71735. if (andj[0] === "!") {
  71736. result = !evaluateCallback(andj.substring(1));
  71737. }
  71738. else {
  71739. result = evaluateCallback(andj);
  71740. }
  71741. }
  71742. else {
  71743. result = andj === "true" ? true : false;
  71744. }
  71745. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  71746. ori = "false";
  71747. break;
  71748. }
  71749. }
  71750. }
  71751. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  71752. result = true;
  71753. break;
  71754. }
  71755. // result equals false (or undefined)
  71756. if (ori !== "true" && ori !== "false") {
  71757. if (ori[0] === "!") {
  71758. result = !evaluateCallback(ori.substring(1));
  71759. }
  71760. else {
  71761. result = evaluateCallback(ori);
  71762. }
  71763. }
  71764. else {
  71765. result = ori === "true" ? true : false;
  71766. }
  71767. }
  71768. }
  71769. // the whole parenthesis scope is replaced by 'true' or 'false'
  71770. return result ? "true" : "false";
  71771. };
  71772. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  71773. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  71774. // remove whitespaces
  71775. r = r.replace(/[\s]/g, function () { return ""; });
  71776. return r.length % 2 ? "!" : "";
  71777. });
  71778. booleanString = booleanString.trim();
  71779. if (booleanString === "!true") {
  71780. booleanString = "false";
  71781. }
  71782. else if (booleanString === "!false") {
  71783. booleanString = "true";
  71784. }
  71785. return booleanString;
  71786. };
  71787. return AndOrNotEvaluator;
  71788. }());
  71789. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  71790. })(BABYLON || (BABYLON = {}));
  71791. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  71792. var BABYLON;
  71793. (function (BABYLON) {
  71794. /**
  71795. * Class used to enable access to IndexedDB
  71796. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  71797. */
  71798. var Database = /** @class */ (function () {
  71799. /**
  71800. * Creates a new Database
  71801. * @param urlToScene defines the url to load the scene
  71802. * @param callbackManifestChecked defines the callback to use when manifest is checked
  71803. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  71804. */
  71805. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  71806. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  71807. var _this = this;
  71808. // Handling various flavors of prefixed version of IndexedDB
  71809. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  71810. this.callbackManifestChecked = callbackManifestChecked;
  71811. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  71812. this.db = null;
  71813. this._enableSceneOffline = false;
  71814. this._enableTexturesOffline = false;
  71815. this.manifestVersionFound = 0;
  71816. this.mustUpdateRessources = false;
  71817. this.hasReachedQuota = false;
  71818. if (!Database.IDBStorageEnabled) {
  71819. this.callbackManifestChecked(true);
  71820. }
  71821. else {
  71822. if (disableManifestCheck) {
  71823. this._enableSceneOffline = true;
  71824. this._enableTexturesOffline = true;
  71825. this.manifestVersionFound = 1;
  71826. BABYLON.Tools.SetImmediate(function () {
  71827. _this.callbackManifestChecked(true);
  71828. });
  71829. }
  71830. else {
  71831. this._checkManifestFile();
  71832. }
  71833. }
  71834. }
  71835. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  71836. /**
  71837. * Gets a boolean indicating if scene must be saved in the database
  71838. */
  71839. get: function () {
  71840. return this._enableSceneOffline;
  71841. },
  71842. enumerable: true,
  71843. configurable: true
  71844. });
  71845. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  71846. /**
  71847. * Gets a boolean indicating if textures must be saved in the database
  71848. */
  71849. get: function () {
  71850. return this._enableTexturesOffline;
  71851. },
  71852. enumerable: true,
  71853. configurable: true
  71854. });
  71855. Database.prototype._checkManifestFile = function () {
  71856. var _this = this;
  71857. var noManifestFile = function () {
  71858. _this._enableSceneOffline = false;
  71859. _this._enableTexturesOffline = false;
  71860. _this.callbackManifestChecked(false);
  71861. };
  71862. var timeStampUsed = false;
  71863. var manifestURL = this.currentSceneUrl + ".manifest";
  71864. var xhr = new XMLHttpRequest();
  71865. if (navigator.onLine) {
  71866. // Adding a timestamp to by-pass browsers' cache
  71867. timeStampUsed = true;
  71868. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  71869. }
  71870. xhr.open("GET", manifestURL, true);
  71871. xhr.addEventListener("load", function () {
  71872. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  71873. try {
  71874. var manifestFile = JSON.parse(xhr.response);
  71875. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  71876. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  71877. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  71878. _this.manifestVersionFound = manifestFile.version;
  71879. }
  71880. if (_this.callbackManifestChecked) {
  71881. _this.callbackManifestChecked(true);
  71882. }
  71883. }
  71884. catch (ex) {
  71885. noManifestFile();
  71886. }
  71887. }
  71888. else {
  71889. noManifestFile();
  71890. }
  71891. }, false);
  71892. xhr.addEventListener("error", function (event) {
  71893. if (timeStampUsed) {
  71894. timeStampUsed = false;
  71895. // Let's retry without the timeStamp
  71896. // It could fail when coupled with HTML5 Offline API
  71897. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  71898. xhr.open("GET", retryManifestURL, true);
  71899. xhr.send();
  71900. }
  71901. else {
  71902. noManifestFile();
  71903. }
  71904. }, false);
  71905. try {
  71906. xhr.send();
  71907. }
  71908. catch (ex) {
  71909. BABYLON.Tools.Error("Error on XHR send request.");
  71910. this.callbackManifestChecked(false);
  71911. }
  71912. };
  71913. /**
  71914. * Open the database and make it available
  71915. * @param successCallback defines the callback to call on success
  71916. * @param errorCallback defines the callback to call on error
  71917. */
  71918. Database.prototype.openAsync = function (successCallback, errorCallback) {
  71919. var _this = this;
  71920. var handleError = function () {
  71921. _this.isSupported = false;
  71922. if (errorCallback)
  71923. errorCallback();
  71924. };
  71925. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  71926. // Your browser doesn't support IndexedDB
  71927. this.isSupported = false;
  71928. if (errorCallback)
  71929. errorCallback();
  71930. }
  71931. else {
  71932. // If the DB hasn't been opened or created yet
  71933. if (!this.db) {
  71934. this.hasReachedQuota = false;
  71935. this.isSupported = true;
  71936. var request = this.idbFactory.open("babylonjs", 1);
  71937. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  71938. request.onerror = function (event) {
  71939. handleError();
  71940. };
  71941. // executes when a version change transaction cannot complete due to other active transactions
  71942. request.onblocked = function (event) {
  71943. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  71944. handleError();
  71945. };
  71946. // DB has been opened successfully
  71947. request.onsuccess = function (event) {
  71948. _this.db = request.result;
  71949. successCallback();
  71950. };
  71951. // Initialization of the DB. Creating Scenes & Textures stores
  71952. request.onupgradeneeded = function (event) {
  71953. _this.db = (event.target).result;
  71954. if (_this.db) {
  71955. try {
  71956. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  71957. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  71958. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  71959. }
  71960. catch (ex) {
  71961. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  71962. handleError();
  71963. }
  71964. }
  71965. };
  71966. }
  71967. // DB has already been created and opened
  71968. else {
  71969. if (successCallback)
  71970. successCallback();
  71971. }
  71972. }
  71973. };
  71974. /**
  71975. * Loads an image from the database
  71976. * @param url defines the url to load from
  71977. * @param image defines the target DOM image
  71978. */
  71979. Database.prototype.loadImageFromDB = function (url, image) {
  71980. var _this = this;
  71981. var completeURL = Database._ReturnFullUrlLocation(url);
  71982. var saveAndLoadImage = function () {
  71983. if (!_this.hasReachedQuota && _this.db !== null) {
  71984. // the texture is not yet in the DB, let's try to save it
  71985. _this._saveImageIntoDBAsync(completeURL, image);
  71986. }
  71987. // If the texture is not in the DB and we've reached the DB quota limit
  71988. // let's load it directly from the web
  71989. else {
  71990. image.src = url;
  71991. }
  71992. };
  71993. if (!this.mustUpdateRessources) {
  71994. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  71995. }
  71996. // First time we're download the images or update requested in the manifest file by a version change
  71997. else {
  71998. saveAndLoadImage();
  71999. }
  72000. };
  72001. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  72002. if (this.isSupported && this.db !== null) {
  72003. var texture;
  72004. var transaction = this.db.transaction(["textures"]);
  72005. transaction.onabort = function (event) {
  72006. image.src = url;
  72007. };
  72008. transaction.oncomplete = function (event) {
  72009. var blobTextureURL;
  72010. if (texture) {
  72011. var URL = window.URL || window.webkitURL;
  72012. blobTextureURL = URL.createObjectURL(texture.data);
  72013. image.onerror = function () {
  72014. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  72015. image.src = url;
  72016. };
  72017. image.src = blobTextureURL;
  72018. }
  72019. else {
  72020. notInDBCallback();
  72021. }
  72022. };
  72023. var getRequest = transaction.objectStore("textures").get(url);
  72024. getRequest.onsuccess = function (event) {
  72025. texture = (event.target).result;
  72026. };
  72027. getRequest.onerror = function (event) {
  72028. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  72029. image.src = url;
  72030. };
  72031. }
  72032. else {
  72033. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  72034. image.src = url;
  72035. }
  72036. };
  72037. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  72038. var _this = this;
  72039. if (this.isSupported) {
  72040. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  72041. var generateBlobUrl = function () {
  72042. var blobTextureURL;
  72043. if (blob) {
  72044. var URL = window.URL || window.webkitURL;
  72045. try {
  72046. blobTextureURL = URL.createObjectURL(blob);
  72047. }
  72048. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  72049. catch (ex) {
  72050. blobTextureURL = URL.createObjectURL(blob);
  72051. }
  72052. }
  72053. if (blobTextureURL) {
  72054. image.src = blobTextureURL;
  72055. }
  72056. };
  72057. if (Database.IsUASupportingBlobStorage) { // Create XHR
  72058. var xhr = new XMLHttpRequest(), blob;
  72059. xhr.open("GET", url, true);
  72060. xhr.responseType = "blob";
  72061. xhr.addEventListener("load", function () {
  72062. if (xhr.status === 200 && _this.db) {
  72063. // Blob as response (XHR2)
  72064. blob = xhr.response;
  72065. var transaction = _this.db.transaction(["textures"], "readwrite");
  72066. // the transaction could abort because of a QuotaExceededError error
  72067. transaction.onabort = function (event) {
  72068. try {
  72069. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  72070. var srcElement = (event.srcElement || event.target);
  72071. var error = srcElement.error;
  72072. if (error && error.name === "QuotaExceededError") {
  72073. _this.hasReachedQuota = true;
  72074. }
  72075. }
  72076. catch (ex) { }
  72077. generateBlobUrl();
  72078. };
  72079. transaction.oncomplete = function (event) {
  72080. generateBlobUrl();
  72081. };
  72082. var newTexture = { textureUrl: url, data: blob };
  72083. try {
  72084. // Put the blob into the dabase
  72085. var addRequest = transaction.objectStore("textures").put(newTexture);
  72086. addRequest.onsuccess = function (event) {
  72087. };
  72088. addRequest.onerror = function (event) {
  72089. generateBlobUrl();
  72090. };
  72091. }
  72092. catch (ex) {
  72093. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  72094. if (ex.code === 25) {
  72095. Database.IsUASupportingBlobStorage = false;
  72096. }
  72097. image.src = url;
  72098. }
  72099. }
  72100. else {
  72101. image.src = url;
  72102. }
  72103. }, false);
  72104. xhr.addEventListener("error", function (event) {
  72105. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  72106. image.src = url;
  72107. }, false);
  72108. xhr.send();
  72109. }
  72110. else {
  72111. image.src = url;
  72112. }
  72113. }
  72114. else {
  72115. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  72116. image.src = url;
  72117. }
  72118. };
  72119. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  72120. var _this = this;
  72121. var updateVersion = function () {
  72122. // the version is not yet in the DB or we need to update it
  72123. _this._saveVersionIntoDBAsync(url, versionLoaded);
  72124. };
  72125. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  72126. };
  72127. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  72128. var _this = this;
  72129. if (this.isSupported && this.db) {
  72130. var version;
  72131. try {
  72132. var transaction = this.db.transaction(["versions"]);
  72133. transaction.oncomplete = function (event) {
  72134. if (version) {
  72135. // If the version in the JSON file is different from the version in DB
  72136. if (_this.manifestVersionFound !== version.data) {
  72137. _this.mustUpdateRessources = true;
  72138. updateInDBCallback();
  72139. }
  72140. else {
  72141. callback(version.data);
  72142. }
  72143. }
  72144. // version was not found in DB
  72145. else {
  72146. _this.mustUpdateRessources = true;
  72147. updateInDBCallback();
  72148. }
  72149. };
  72150. transaction.onabort = function (event) {
  72151. callback(-1);
  72152. };
  72153. var getRequest = transaction.objectStore("versions").get(url);
  72154. getRequest.onsuccess = function (event) {
  72155. version = (event.target).result;
  72156. };
  72157. getRequest.onerror = function (event) {
  72158. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  72159. callback(-1);
  72160. };
  72161. }
  72162. catch (ex) {
  72163. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  72164. callback(-1);
  72165. }
  72166. }
  72167. else {
  72168. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  72169. callback(-1);
  72170. }
  72171. };
  72172. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  72173. var _this = this;
  72174. if (this.isSupported && !this.hasReachedQuota && this.db) {
  72175. try {
  72176. // Open a transaction to the database
  72177. var transaction = this.db.transaction(["versions"], "readwrite");
  72178. // the transaction could abort because of a QuotaExceededError error
  72179. transaction.onabort = function (event) {
  72180. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  72181. var error = event.srcElement['error'];
  72182. if (error && error.name === "QuotaExceededError") {
  72183. _this.hasReachedQuota = true;
  72184. }
  72185. }
  72186. catch (ex) { }
  72187. callback(-1);
  72188. };
  72189. transaction.oncomplete = function (event) {
  72190. callback(_this.manifestVersionFound);
  72191. };
  72192. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  72193. // Put the scene into the database
  72194. var addRequest = transaction.objectStore("versions").put(newVersion);
  72195. addRequest.onsuccess = function (event) {
  72196. };
  72197. addRequest.onerror = function (event) {
  72198. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  72199. };
  72200. }
  72201. catch (ex) {
  72202. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  72203. callback(-1);
  72204. }
  72205. }
  72206. else {
  72207. callback(-1);
  72208. }
  72209. };
  72210. /**
  72211. * Loads a file from database
  72212. * @param url defines the URL to load from
  72213. * @param sceneLoaded defines a callback to call on success
  72214. * @param progressCallBack defines a callback to call when progress changed
  72215. * @param errorCallback defines a callback to call on error
  72216. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  72217. */
  72218. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  72219. var _this = this;
  72220. var completeUrl = Database._ReturnFullUrlLocation(url);
  72221. var saveAndLoadFile = function () {
  72222. // the scene is not yet in the DB, let's try to save it
  72223. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  72224. };
  72225. this._checkVersionFromDB(completeUrl, function (version) {
  72226. if (version !== -1) {
  72227. if (!_this.mustUpdateRessources) {
  72228. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  72229. }
  72230. else {
  72231. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  72232. }
  72233. }
  72234. else {
  72235. if (errorCallback) {
  72236. errorCallback();
  72237. }
  72238. }
  72239. });
  72240. };
  72241. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  72242. if (this.isSupported && this.db) {
  72243. var targetStore;
  72244. if (url.indexOf(".babylon") !== -1) {
  72245. targetStore = "scenes";
  72246. }
  72247. else {
  72248. targetStore = "textures";
  72249. }
  72250. var file;
  72251. var transaction = this.db.transaction([targetStore]);
  72252. transaction.oncomplete = function (event) {
  72253. if (file) {
  72254. callback(file.data);
  72255. }
  72256. // file was not found in DB
  72257. else {
  72258. notInDBCallback();
  72259. }
  72260. };
  72261. transaction.onabort = function (event) {
  72262. notInDBCallback();
  72263. };
  72264. var getRequest = transaction.objectStore(targetStore).get(url);
  72265. getRequest.onsuccess = function (event) {
  72266. file = (event.target).result;
  72267. };
  72268. getRequest.onerror = function (event) {
  72269. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  72270. notInDBCallback();
  72271. };
  72272. }
  72273. else {
  72274. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  72275. callback();
  72276. }
  72277. };
  72278. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  72279. var _this = this;
  72280. if (this.isSupported) {
  72281. var targetStore;
  72282. if (url.indexOf(".babylon") !== -1) {
  72283. targetStore = "scenes";
  72284. }
  72285. else {
  72286. targetStore = "textures";
  72287. }
  72288. // Create XHR
  72289. var xhr = new XMLHttpRequest();
  72290. var fileData;
  72291. xhr.open("GET", url + "?" + Date.now(), true);
  72292. if (useArrayBuffer) {
  72293. xhr.responseType = "arraybuffer";
  72294. }
  72295. if (progressCallback) {
  72296. xhr.onprogress = progressCallback;
  72297. }
  72298. xhr.addEventListener("load", function () {
  72299. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  72300. // Blob as response (XHR2)
  72301. //fileData = xhr.responseText;
  72302. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  72303. if (!_this.hasReachedQuota && _this.db) {
  72304. // Open a transaction to the database
  72305. var transaction = _this.db.transaction([targetStore], "readwrite");
  72306. // the transaction could abort because of a QuotaExceededError error
  72307. transaction.onabort = function (event) {
  72308. try {
  72309. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  72310. var error = event.srcElement['error'];
  72311. if (error && error.name === "QuotaExceededError") {
  72312. _this.hasReachedQuota = true;
  72313. }
  72314. }
  72315. catch (ex) { }
  72316. callback(fileData);
  72317. };
  72318. transaction.oncomplete = function (event) {
  72319. callback(fileData);
  72320. };
  72321. var newFile;
  72322. if (targetStore === "scenes") {
  72323. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  72324. }
  72325. else {
  72326. newFile = { textureUrl: url, data: fileData };
  72327. }
  72328. try {
  72329. // Put the scene into the database
  72330. var addRequest = transaction.objectStore(targetStore).put(newFile);
  72331. addRequest.onsuccess = function (event) {
  72332. };
  72333. addRequest.onerror = function (event) {
  72334. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  72335. };
  72336. }
  72337. catch (ex) {
  72338. callback(fileData);
  72339. }
  72340. }
  72341. else {
  72342. callback(fileData);
  72343. }
  72344. }
  72345. else {
  72346. if (xhr.status >= 400 && errorCallback) {
  72347. errorCallback(xhr);
  72348. }
  72349. else {
  72350. callback();
  72351. }
  72352. }
  72353. }, false);
  72354. xhr.addEventListener("error", function (event) {
  72355. BABYLON.Tools.Error("error on XHR request.");
  72356. callback();
  72357. }, false);
  72358. xhr.send();
  72359. }
  72360. else {
  72361. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  72362. callback();
  72363. }
  72364. };
  72365. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  72366. Database.IsUASupportingBlobStorage = true;
  72367. /** Gets a boolean indicating if Database storate is enabled */
  72368. Database.IDBStorageEnabled = true;
  72369. Database._ParseURL = function (url) {
  72370. var a = document.createElement('a');
  72371. a.href = url;
  72372. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  72373. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  72374. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  72375. return absLocation;
  72376. };
  72377. Database._ReturnFullUrlLocation = function (url) {
  72378. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  72379. return (Database._ParseURL(window.location.href) + url);
  72380. }
  72381. else {
  72382. return url;
  72383. }
  72384. };
  72385. return Database;
  72386. }());
  72387. BABYLON.Database = Database;
  72388. })(BABYLON || (BABYLON = {}));
  72389. //# sourceMappingURL=babylon.database.js.map
  72390. var BABYLON;
  72391. (function (BABYLON) {
  72392. var FresnelParameters = /** @class */ (function () {
  72393. function FresnelParameters() {
  72394. this._isEnabled = true;
  72395. this.leftColor = BABYLON.Color3.White();
  72396. this.rightColor = BABYLON.Color3.Black();
  72397. this.bias = 0;
  72398. this.power = 1;
  72399. }
  72400. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  72401. get: function () {
  72402. return this._isEnabled;
  72403. },
  72404. set: function (value) {
  72405. if (this._isEnabled === value) {
  72406. return;
  72407. }
  72408. this._isEnabled = value;
  72409. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  72410. },
  72411. enumerable: true,
  72412. configurable: true
  72413. });
  72414. FresnelParameters.prototype.clone = function () {
  72415. var newFresnelParameters = new FresnelParameters();
  72416. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  72417. return newFresnelParameters;
  72418. };
  72419. FresnelParameters.prototype.serialize = function () {
  72420. var serializationObject = {};
  72421. serializationObject.isEnabled = this.isEnabled;
  72422. serializationObject.leftColor = this.leftColor.asArray();
  72423. serializationObject.rightColor = this.rightColor.asArray();
  72424. serializationObject.bias = this.bias;
  72425. serializationObject.power = this.power;
  72426. return serializationObject;
  72427. };
  72428. FresnelParameters.Parse = function (parsedFresnelParameters) {
  72429. var fresnelParameters = new FresnelParameters();
  72430. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  72431. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  72432. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  72433. fresnelParameters.bias = parsedFresnelParameters.bias;
  72434. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  72435. return fresnelParameters;
  72436. };
  72437. return FresnelParameters;
  72438. }());
  72439. BABYLON.FresnelParameters = FresnelParameters;
  72440. })(BABYLON || (BABYLON = {}));
  72441. //# sourceMappingURL=babylon.fresnelParameters.js.map
  72442. var BABYLON;
  72443. (function (BABYLON) {
  72444. var MultiMaterial = /** @class */ (function (_super) {
  72445. __extends(MultiMaterial, _super);
  72446. function MultiMaterial(name, scene) {
  72447. var _this = _super.call(this, name, scene, true) || this;
  72448. scene.multiMaterials.push(_this);
  72449. _this.subMaterials = new Array();
  72450. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  72451. return _this;
  72452. }
  72453. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  72454. get: function () {
  72455. return this._subMaterials;
  72456. },
  72457. set: function (value) {
  72458. this._subMaterials = value;
  72459. this._hookArray(value);
  72460. },
  72461. enumerable: true,
  72462. configurable: true
  72463. });
  72464. MultiMaterial.prototype._hookArray = function (array) {
  72465. var _this = this;
  72466. var oldPush = array.push;
  72467. array.push = function () {
  72468. var items = [];
  72469. for (var _i = 0; _i < arguments.length; _i++) {
  72470. items[_i] = arguments[_i];
  72471. }
  72472. var result = oldPush.apply(array, items);
  72473. _this._markAllSubMeshesAsTexturesDirty();
  72474. return result;
  72475. };
  72476. var oldSplice = array.splice;
  72477. array.splice = function (index, deleteCount) {
  72478. var deleted = oldSplice.apply(array, [index, deleteCount]);
  72479. _this._markAllSubMeshesAsTexturesDirty();
  72480. return deleted;
  72481. };
  72482. };
  72483. // Properties
  72484. MultiMaterial.prototype.getSubMaterial = function (index) {
  72485. if (index < 0 || index >= this.subMaterials.length) {
  72486. return this.getScene().defaultMaterial;
  72487. }
  72488. return this.subMaterials[index];
  72489. };
  72490. MultiMaterial.prototype.getActiveTextures = function () {
  72491. var _a;
  72492. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  72493. if (subMaterial) {
  72494. return subMaterial.getActiveTextures();
  72495. }
  72496. else {
  72497. return [];
  72498. }
  72499. }));
  72500. };
  72501. // Methods
  72502. MultiMaterial.prototype.getClassName = function () {
  72503. return "MultiMaterial";
  72504. };
  72505. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  72506. for (var index = 0; index < this.subMaterials.length; index++) {
  72507. var subMaterial = this.subMaterials[index];
  72508. if (subMaterial) {
  72509. if (subMaterial.storeEffectOnSubMeshes) {
  72510. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  72511. return false;
  72512. }
  72513. continue;
  72514. }
  72515. if (!subMaterial.isReady(mesh)) {
  72516. return false;
  72517. }
  72518. }
  72519. }
  72520. return true;
  72521. };
  72522. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  72523. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  72524. for (var index = 0; index < this.subMaterials.length; index++) {
  72525. var subMaterial = null;
  72526. var current = this.subMaterials[index];
  72527. if (cloneChildren && current) {
  72528. subMaterial = current.clone(name + "-" + current.name);
  72529. }
  72530. else {
  72531. subMaterial = this.subMaterials[index];
  72532. }
  72533. newMultiMaterial.subMaterials.push(subMaterial);
  72534. }
  72535. return newMultiMaterial;
  72536. };
  72537. MultiMaterial.prototype.serialize = function () {
  72538. var serializationObject = {};
  72539. serializationObject.name = this.name;
  72540. serializationObject.id = this.id;
  72541. if (BABYLON.Tags) {
  72542. serializationObject.tags = BABYLON.Tags.GetTags(this);
  72543. }
  72544. serializationObject.materials = [];
  72545. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  72546. var subMat = this.subMaterials[matIndex];
  72547. if (subMat) {
  72548. serializationObject.materials.push(subMat.id);
  72549. }
  72550. else {
  72551. serializationObject.materials.push(null);
  72552. }
  72553. }
  72554. return serializationObject;
  72555. };
  72556. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  72557. var scene = this.getScene();
  72558. if (!scene) {
  72559. return;
  72560. }
  72561. var index = scene.multiMaterials.indexOf(this);
  72562. if (index >= 0) {
  72563. scene.multiMaterials.splice(index, 1);
  72564. }
  72565. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  72566. };
  72567. return MultiMaterial;
  72568. }(BABYLON.Material));
  72569. BABYLON.MultiMaterial = MultiMaterial;
  72570. })(BABYLON || (BABYLON = {}));
  72571. //# sourceMappingURL=babylon.multiMaterial.js.map
  72572. var BABYLON;
  72573. (function (BABYLON) {
  72574. var FreeCameraTouchInput = /** @class */ (function () {
  72575. function FreeCameraTouchInput() {
  72576. this._offsetX = null;
  72577. this._offsetY = null;
  72578. this._pointerPressed = new Array();
  72579. this.touchAngularSensibility = 200000.0;
  72580. this.touchMoveSensibility = 250.0;
  72581. }
  72582. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  72583. var _this = this;
  72584. var previousPosition = null;
  72585. if (this._pointerInput === undefined) {
  72586. this._onLostFocus = function (evt) {
  72587. _this._offsetX = null;
  72588. _this._offsetY = null;
  72589. };
  72590. this._pointerInput = function (p, s) {
  72591. var evt = p.event;
  72592. if (evt.pointerType === "mouse") {
  72593. return;
  72594. }
  72595. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  72596. if (!noPreventDefault) {
  72597. evt.preventDefault();
  72598. }
  72599. _this._pointerPressed.push(evt.pointerId);
  72600. if (_this._pointerPressed.length !== 1) {
  72601. return;
  72602. }
  72603. previousPosition = {
  72604. x: evt.clientX,
  72605. y: evt.clientY
  72606. };
  72607. }
  72608. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  72609. if (!noPreventDefault) {
  72610. evt.preventDefault();
  72611. }
  72612. var index = _this._pointerPressed.indexOf(evt.pointerId);
  72613. if (index === -1) {
  72614. return;
  72615. }
  72616. _this._pointerPressed.splice(index, 1);
  72617. if (index != 0) {
  72618. return;
  72619. }
  72620. previousPosition = null;
  72621. _this._offsetX = null;
  72622. _this._offsetY = null;
  72623. }
  72624. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  72625. if (!noPreventDefault) {
  72626. evt.preventDefault();
  72627. }
  72628. if (!previousPosition) {
  72629. return;
  72630. }
  72631. var index = _this._pointerPressed.indexOf(evt.pointerId);
  72632. if (index != 0) {
  72633. return;
  72634. }
  72635. _this._offsetX = evt.clientX - previousPosition.x;
  72636. _this._offsetY = -(evt.clientY - previousPosition.y);
  72637. }
  72638. };
  72639. }
  72640. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  72641. if (this._onLostFocus) {
  72642. element.addEventListener("blur", this._onLostFocus);
  72643. }
  72644. };
  72645. FreeCameraTouchInput.prototype.detachControl = function (element) {
  72646. if (this._pointerInput && element) {
  72647. if (this._observer) {
  72648. this.camera.getScene().onPointerObservable.remove(this._observer);
  72649. this._observer = null;
  72650. }
  72651. if (this._onLostFocus) {
  72652. element.removeEventListener("blur", this._onLostFocus);
  72653. this._onLostFocus = null;
  72654. }
  72655. this._pointerPressed = [];
  72656. this._offsetX = null;
  72657. this._offsetY = null;
  72658. }
  72659. };
  72660. FreeCameraTouchInput.prototype.checkInputs = function () {
  72661. if (this._offsetX && this._offsetY) {
  72662. var camera = this.camera;
  72663. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  72664. if (this._pointerPressed.length > 1) {
  72665. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  72666. }
  72667. else {
  72668. var speed = camera._computeLocalCameraSpeed();
  72669. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  72670. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  72671. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  72672. }
  72673. }
  72674. };
  72675. FreeCameraTouchInput.prototype.getClassName = function () {
  72676. return "FreeCameraTouchInput";
  72677. };
  72678. FreeCameraTouchInput.prototype.getSimpleName = function () {
  72679. return "touch";
  72680. };
  72681. __decorate([
  72682. BABYLON.serialize()
  72683. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  72684. __decorate([
  72685. BABYLON.serialize()
  72686. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  72687. return FreeCameraTouchInput;
  72688. }());
  72689. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  72690. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  72691. })(BABYLON || (BABYLON = {}));
  72692. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  72693. var BABYLON;
  72694. (function (BABYLON) {
  72695. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  72696. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  72697. });
  72698. // We're mainly based on the logic defined into the FreeCamera code
  72699. var TouchCamera = /** @class */ (function (_super) {
  72700. __extends(TouchCamera, _super);
  72701. //-- end properties for backward compatibility for inputs
  72702. function TouchCamera(name, position, scene) {
  72703. var _this = _super.call(this, name, position, scene) || this;
  72704. _this.inputs.addTouch();
  72705. _this._setupInputs();
  72706. return _this;
  72707. }
  72708. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  72709. //-- Begin properties for backward compatibility for inputs
  72710. get: function () {
  72711. var touch = this.inputs.attached["touch"];
  72712. if (touch)
  72713. return touch.touchAngularSensibility;
  72714. return 0;
  72715. },
  72716. set: function (value) {
  72717. var touch = this.inputs.attached["touch"];
  72718. if (touch)
  72719. touch.touchAngularSensibility = value;
  72720. },
  72721. enumerable: true,
  72722. configurable: true
  72723. });
  72724. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  72725. get: function () {
  72726. var touch = this.inputs.attached["touch"];
  72727. if (touch)
  72728. return touch.touchMoveSensibility;
  72729. return 0;
  72730. },
  72731. set: function (value) {
  72732. var touch = this.inputs.attached["touch"];
  72733. if (touch)
  72734. touch.touchMoveSensibility = value;
  72735. },
  72736. enumerable: true,
  72737. configurable: true
  72738. });
  72739. TouchCamera.prototype.getClassName = function () {
  72740. return "TouchCamera";
  72741. };
  72742. /** @hidden */
  72743. TouchCamera.prototype._setupInputs = function () {
  72744. var mouse = this.inputs.attached["mouse"];
  72745. if (mouse) {
  72746. mouse.touchEnabled = false;
  72747. }
  72748. };
  72749. return TouchCamera;
  72750. }(BABYLON.FreeCamera));
  72751. BABYLON.TouchCamera = TouchCamera;
  72752. })(BABYLON || (BABYLON = {}));
  72753. //# sourceMappingURL=babylon.touchCamera.js.map
  72754. var BABYLON;
  72755. (function (BABYLON) {
  72756. var ProceduralTexture = /** @class */ (function (_super) {
  72757. __extends(ProceduralTexture, _super);
  72758. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  72759. if (fallbackTexture === void 0) { fallbackTexture = null; }
  72760. if (generateMipMaps === void 0) { generateMipMaps = true; }
  72761. if (isCube === void 0) { isCube = false; }
  72762. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  72763. _this.isCube = isCube;
  72764. _this.isEnabled = true;
  72765. _this._currentRefreshId = -1;
  72766. _this._refreshRate = 1;
  72767. _this._vertexBuffers = {};
  72768. _this._uniforms = new Array();
  72769. _this._samplers = new Array();
  72770. /** @hidden */
  72771. _this._textures = {};
  72772. _this._floats = {};
  72773. _this._ints = {};
  72774. _this._floatsArrays = {};
  72775. _this._colors3 = {};
  72776. _this._colors4 = {};
  72777. _this._vectors2 = {};
  72778. _this._vectors3 = {};
  72779. _this._matrices = {};
  72780. _this._fallbackTextureUsed = false;
  72781. scene = _this.getScene();
  72782. scene.proceduralTextures.push(_this);
  72783. _this._engine = scene.getEngine();
  72784. _this.name = name;
  72785. _this.isRenderTarget = true;
  72786. _this._size = size;
  72787. _this._generateMipMaps = generateMipMaps;
  72788. _this.setFragment(fragment);
  72789. _this._fallbackTexture = fallbackTexture;
  72790. if (isCube) {
  72791. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  72792. _this.setFloat("face", 0);
  72793. }
  72794. else {
  72795. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  72796. }
  72797. // VBO
  72798. var vertices = [];
  72799. vertices.push(1, 1);
  72800. vertices.push(-1, 1);
  72801. vertices.push(-1, -1);
  72802. vertices.push(1, -1);
  72803. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  72804. _this._createIndexBuffer();
  72805. return _this;
  72806. }
  72807. ProceduralTexture.prototype._createIndexBuffer = function () {
  72808. var engine = this._engine;
  72809. // Indices
  72810. var indices = [];
  72811. indices.push(0);
  72812. indices.push(1);
  72813. indices.push(2);
  72814. indices.push(0);
  72815. indices.push(2);
  72816. indices.push(3);
  72817. this._indexBuffer = engine.createIndexBuffer(indices);
  72818. };
  72819. /** @hidden */
  72820. ProceduralTexture.prototype._rebuild = function () {
  72821. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72822. if (vb) {
  72823. vb._rebuild();
  72824. }
  72825. this._createIndexBuffer();
  72826. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  72827. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  72828. }
  72829. };
  72830. ProceduralTexture.prototype.reset = function () {
  72831. if (this._effect === undefined) {
  72832. return;
  72833. }
  72834. var engine = this._engine;
  72835. engine._releaseEffect(this._effect);
  72836. };
  72837. ProceduralTexture.prototype.isReady = function () {
  72838. var _this = this;
  72839. var engine = this._engine;
  72840. var shaders;
  72841. if (!this._fragment) {
  72842. return false;
  72843. }
  72844. if (this._fallbackTextureUsed) {
  72845. return true;
  72846. }
  72847. if (this._fragment.fragmentElement !== undefined) {
  72848. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  72849. }
  72850. else {
  72851. shaders = { vertex: "procedural", fragment: this._fragment };
  72852. }
  72853. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  72854. _this.releaseInternalTexture();
  72855. if (_this._fallbackTexture) {
  72856. _this._texture = _this._fallbackTexture._texture;
  72857. if (_this._texture) {
  72858. _this._texture.incrementReferences();
  72859. }
  72860. }
  72861. _this._fallbackTextureUsed = true;
  72862. });
  72863. return this._effect.isReady();
  72864. };
  72865. ProceduralTexture.prototype.resetRefreshCounter = function () {
  72866. this._currentRefreshId = -1;
  72867. };
  72868. ProceduralTexture.prototype.setFragment = function (fragment) {
  72869. this._fragment = fragment;
  72870. };
  72871. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  72872. get: function () {
  72873. return this._refreshRate;
  72874. },
  72875. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  72876. set: function (value) {
  72877. this._refreshRate = value;
  72878. this.resetRefreshCounter();
  72879. },
  72880. enumerable: true,
  72881. configurable: true
  72882. });
  72883. /** @hidden */
  72884. ProceduralTexture.prototype._shouldRender = function () {
  72885. if (!this.isEnabled || !this.isReady() || !this._texture) {
  72886. return false;
  72887. }
  72888. if (this._fallbackTextureUsed) {
  72889. return false;
  72890. }
  72891. if (this._currentRefreshId === -1) { // At least render once
  72892. this._currentRefreshId = 1;
  72893. return true;
  72894. }
  72895. if (this.refreshRate === this._currentRefreshId) {
  72896. this._currentRefreshId = 1;
  72897. return true;
  72898. }
  72899. this._currentRefreshId++;
  72900. return false;
  72901. };
  72902. ProceduralTexture.prototype.getRenderSize = function () {
  72903. return this._size;
  72904. };
  72905. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  72906. if (this._fallbackTextureUsed) {
  72907. return;
  72908. }
  72909. this.releaseInternalTexture();
  72910. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  72911. // Update properties
  72912. this._size = size;
  72913. this._generateMipMaps = generateMipMaps;
  72914. };
  72915. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  72916. if (this._uniforms.indexOf(uniformName) === -1) {
  72917. this._uniforms.push(uniformName);
  72918. }
  72919. };
  72920. ProceduralTexture.prototype.setTexture = function (name, texture) {
  72921. if (this._samplers.indexOf(name) === -1) {
  72922. this._samplers.push(name);
  72923. }
  72924. this._textures[name] = texture;
  72925. return this;
  72926. };
  72927. ProceduralTexture.prototype.setFloat = function (name, value) {
  72928. this._checkUniform(name);
  72929. this._floats[name] = value;
  72930. return this;
  72931. };
  72932. /**
  72933. * Set the value of an uniform to an integer value
  72934. * @param name defines the name of the uniform
  72935. * @param value defines the value to set
  72936. * @returns the current procedural texture
  72937. */
  72938. ProceduralTexture.prototype.setInt = function (name, value) {
  72939. this._checkUniform(name);
  72940. this._ints[name] = value;
  72941. return this;
  72942. };
  72943. ProceduralTexture.prototype.setFloats = function (name, value) {
  72944. this._checkUniform(name);
  72945. this._floatsArrays[name] = value;
  72946. return this;
  72947. };
  72948. ProceduralTexture.prototype.setColor3 = function (name, value) {
  72949. this._checkUniform(name);
  72950. this._colors3[name] = value;
  72951. return this;
  72952. };
  72953. ProceduralTexture.prototype.setColor4 = function (name, value) {
  72954. this._checkUniform(name);
  72955. this._colors4[name] = value;
  72956. return this;
  72957. };
  72958. ProceduralTexture.prototype.setVector2 = function (name, value) {
  72959. this._checkUniform(name);
  72960. this._vectors2[name] = value;
  72961. return this;
  72962. };
  72963. ProceduralTexture.prototype.setVector3 = function (name, value) {
  72964. this._checkUniform(name);
  72965. this._vectors3[name] = value;
  72966. return this;
  72967. };
  72968. ProceduralTexture.prototype.setMatrix = function (name, value) {
  72969. this._checkUniform(name);
  72970. this._matrices[name] = value;
  72971. return this;
  72972. };
  72973. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  72974. var scene = this.getScene();
  72975. if (!scene) {
  72976. return;
  72977. }
  72978. var engine = this._engine;
  72979. // Render
  72980. engine.enableEffect(this._effect);
  72981. engine.setState(false);
  72982. // Texture
  72983. for (var name in this._textures) {
  72984. this._effect.setTexture(name, this._textures[name]);
  72985. }
  72986. // Float
  72987. for (name in this._ints) {
  72988. this._effect.setInt(name, this._ints[name]);
  72989. }
  72990. // Float
  72991. for (name in this._floats) {
  72992. this._effect.setFloat(name, this._floats[name]);
  72993. }
  72994. // Floats
  72995. for (name in this._floatsArrays) {
  72996. this._effect.setArray(name, this._floatsArrays[name]);
  72997. }
  72998. // Color3
  72999. for (name in this._colors3) {
  73000. this._effect.setColor3(name, this._colors3[name]);
  73001. }
  73002. // Color4
  73003. for (name in this._colors4) {
  73004. var color = this._colors4[name];
  73005. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  73006. }
  73007. // Vector2
  73008. for (name in this._vectors2) {
  73009. this._effect.setVector2(name, this._vectors2[name]);
  73010. }
  73011. // Vector3
  73012. for (name in this._vectors3) {
  73013. this._effect.setVector3(name, this._vectors3[name]);
  73014. }
  73015. // Matrix
  73016. for (name in this._matrices) {
  73017. this._effect.setMatrix(name, this._matrices[name]);
  73018. }
  73019. if (!this._texture) {
  73020. return;
  73021. }
  73022. if (this.isCube) {
  73023. for (var face = 0; face < 6; face++) {
  73024. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  73025. // VBOs
  73026. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  73027. this._effect.setFloat("face", face);
  73028. // Clear
  73029. engine.clear(scene.clearColor, true, true, true);
  73030. // Draw order
  73031. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  73032. // Mipmaps
  73033. if (face === 5) {
  73034. engine.generateMipMapsForCubemap(this._texture);
  73035. }
  73036. }
  73037. }
  73038. else {
  73039. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  73040. // VBOs
  73041. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  73042. // Clear
  73043. engine.clear(scene.clearColor, true, true, true);
  73044. // Draw order
  73045. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  73046. }
  73047. // Unbind
  73048. engine.unBindFramebuffer(this._texture, this.isCube);
  73049. if (this.onGenerated) {
  73050. this.onGenerated();
  73051. }
  73052. };
  73053. ProceduralTexture.prototype.clone = function () {
  73054. var textureSize = this.getSize();
  73055. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  73056. // Base texture
  73057. newTexture.hasAlpha = this.hasAlpha;
  73058. newTexture.level = this.level;
  73059. // RenderTarget Texture
  73060. newTexture.coordinatesMode = this.coordinatesMode;
  73061. return newTexture;
  73062. };
  73063. ProceduralTexture.prototype.dispose = function () {
  73064. var scene = this.getScene();
  73065. if (!scene) {
  73066. return;
  73067. }
  73068. var index = scene.proceduralTextures.indexOf(this);
  73069. if (index >= 0) {
  73070. scene.proceduralTextures.splice(index, 1);
  73071. }
  73072. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73073. if (vertexBuffer) {
  73074. vertexBuffer.dispose();
  73075. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  73076. }
  73077. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  73078. this._indexBuffer = null;
  73079. }
  73080. _super.prototype.dispose.call(this);
  73081. };
  73082. __decorate([
  73083. BABYLON.serialize()
  73084. ], ProceduralTexture.prototype, "_size", void 0);
  73085. __decorate([
  73086. BABYLON.serialize()
  73087. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  73088. __decorate([
  73089. BABYLON.serialize()
  73090. ], ProceduralTexture.prototype, "isEnabled", void 0);
  73091. __decorate([
  73092. BABYLON.serialize()
  73093. ], ProceduralTexture.prototype, "refreshRate", null);
  73094. return ProceduralTexture;
  73095. }(BABYLON.Texture));
  73096. BABYLON.ProceduralTexture = ProceduralTexture;
  73097. })(BABYLON || (BABYLON = {}));
  73098. //# sourceMappingURL=babylon.proceduralTexture.js.map
  73099. var BABYLON;
  73100. (function (BABYLON) {
  73101. var CustomProceduralTexture = /** @class */ (function (_super) {
  73102. __extends(CustomProceduralTexture, _super);
  73103. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  73104. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  73105. _this._animate = true;
  73106. _this._time = 0;
  73107. _this._texturePath = texturePath;
  73108. //Try to load json
  73109. _this.loadJson(texturePath);
  73110. _this.refreshRate = 1;
  73111. return _this;
  73112. }
  73113. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  73114. var _this = this;
  73115. var noConfigFile = function () {
  73116. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  73117. try {
  73118. _this.setFragment(_this._texturePath);
  73119. }
  73120. catch (ex) {
  73121. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  73122. }
  73123. };
  73124. var configFileUrl = jsonUrl + "/config.json";
  73125. var xhr = new XMLHttpRequest();
  73126. xhr.open("GET", configFileUrl, true);
  73127. xhr.addEventListener("load", function () {
  73128. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  73129. try {
  73130. _this._config = JSON.parse(xhr.response);
  73131. _this.updateShaderUniforms();
  73132. _this.updateTextures();
  73133. _this.setFragment(_this._texturePath + "/custom");
  73134. _this._animate = _this._config.animate;
  73135. _this.refreshRate = _this._config.refreshrate;
  73136. }
  73137. catch (ex) {
  73138. noConfigFile();
  73139. }
  73140. }
  73141. else {
  73142. noConfigFile();
  73143. }
  73144. }, false);
  73145. xhr.addEventListener("error", function () {
  73146. noConfigFile();
  73147. }, false);
  73148. try {
  73149. xhr.send();
  73150. }
  73151. catch (ex) {
  73152. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  73153. }
  73154. };
  73155. CustomProceduralTexture.prototype.isReady = function () {
  73156. if (!_super.prototype.isReady.call(this)) {
  73157. return false;
  73158. }
  73159. for (var name in this._textures) {
  73160. var texture = this._textures[name];
  73161. if (!texture.isReady()) {
  73162. return false;
  73163. }
  73164. }
  73165. return true;
  73166. };
  73167. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  73168. var scene = this.getScene();
  73169. if (this._animate && scene) {
  73170. this._time += scene.getAnimationRatio() * 0.03;
  73171. this.updateShaderUniforms();
  73172. }
  73173. _super.prototype.render.call(this, useCameraPostProcess);
  73174. };
  73175. CustomProceduralTexture.prototype.updateTextures = function () {
  73176. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  73177. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  73178. }
  73179. };
  73180. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  73181. if (this._config) {
  73182. for (var j = 0; j < this._config.uniforms.length; j++) {
  73183. var uniform = this._config.uniforms[j];
  73184. switch (uniform.type) {
  73185. case "float":
  73186. this.setFloat(uniform.name, uniform.value);
  73187. break;
  73188. case "color3":
  73189. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  73190. break;
  73191. case "color4":
  73192. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  73193. break;
  73194. case "vector2":
  73195. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  73196. break;
  73197. case "vector3":
  73198. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  73199. break;
  73200. }
  73201. }
  73202. }
  73203. this.setFloat("time", this._time);
  73204. };
  73205. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  73206. get: function () {
  73207. return this._animate;
  73208. },
  73209. set: function (value) {
  73210. this._animate = value;
  73211. },
  73212. enumerable: true,
  73213. configurable: true
  73214. });
  73215. return CustomProceduralTexture;
  73216. }(BABYLON.ProceduralTexture));
  73217. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  73218. })(BABYLON || (BABYLON = {}));
  73219. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  73220. var BABYLON;
  73221. (function (BABYLON) {
  73222. var FreeCameraGamepadInput = /** @class */ (function () {
  73223. function FreeCameraGamepadInput() {
  73224. this.gamepadAngularSensibility = 200;
  73225. this.gamepadMoveSensibility = 40;
  73226. // private members
  73227. this._cameraTransform = BABYLON.Matrix.Identity();
  73228. this._deltaTransform = BABYLON.Vector3.Zero();
  73229. this._vector3 = BABYLON.Vector3.Zero();
  73230. this._vector2 = BABYLON.Vector2.Zero();
  73231. }
  73232. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  73233. var _this = this;
  73234. var manager = this.camera.getScene().gamepadManager;
  73235. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  73236. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  73237. // prioritize XBOX gamepads.
  73238. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  73239. _this.gamepad = gamepad;
  73240. }
  73241. }
  73242. });
  73243. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  73244. if (_this.gamepad === gamepad) {
  73245. _this.gamepad = null;
  73246. }
  73247. });
  73248. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  73249. };
  73250. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  73251. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  73252. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  73253. this.gamepad = null;
  73254. };
  73255. FreeCameraGamepadInput.prototype.checkInputs = function () {
  73256. if (this.gamepad && this.gamepad.leftStick) {
  73257. var camera = this.camera;
  73258. var LSValues = this.gamepad.leftStick;
  73259. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  73260. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  73261. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  73262. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  73263. var RSValues = this.gamepad.rightStick;
  73264. if (RSValues) {
  73265. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  73266. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  73267. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  73268. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  73269. }
  73270. else {
  73271. RSValues = { x: 0, y: 0 };
  73272. }
  73273. if (!camera.rotationQuaternion) {
  73274. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  73275. }
  73276. else {
  73277. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  73278. }
  73279. var speed = camera._computeLocalCameraSpeed() * 50.0;
  73280. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  73281. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  73282. camera.cameraDirection.addInPlace(this._deltaTransform);
  73283. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  73284. camera.cameraRotation.addInPlace(this._vector2);
  73285. }
  73286. };
  73287. FreeCameraGamepadInput.prototype.getClassName = function () {
  73288. return "FreeCameraGamepadInput";
  73289. };
  73290. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  73291. return "gamepad";
  73292. };
  73293. __decorate([
  73294. BABYLON.serialize()
  73295. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  73296. __decorate([
  73297. BABYLON.serialize()
  73298. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  73299. return FreeCameraGamepadInput;
  73300. }());
  73301. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  73302. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  73303. })(BABYLON || (BABYLON = {}));
  73304. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  73305. var BABYLON;
  73306. (function (BABYLON) {
  73307. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  73308. function ArcRotateCameraGamepadInput() {
  73309. this.gamepadRotationSensibility = 80;
  73310. this.gamepadMoveSensibility = 40;
  73311. }
  73312. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  73313. var _this = this;
  73314. var manager = this.camera.getScene().gamepadManager;
  73315. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  73316. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  73317. // prioritize XBOX gamepads.
  73318. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  73319. _this.gamepad = gamepad;
  73320. }
  73321. }
  73322. });
  73323. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  73324. if (_this.gamepad === gamepad) {
  73325. _this.gamepad = null;
  73326. }
  73327. });
  73328. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  73329. };
  73330. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  73331. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  73332. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  73333. this.gamepad = null;
  73334. };
  73335. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  73336. if (this.gamepad) {
  73337. var camera = this.camera;
  73338. var RSValues = this.gamepad.rightStick;
  73339. if (RSValues) {
  73340. if (RSValues.x != 0) {
  73341. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  73342. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  73343. camera.inertialAlphaOffset += normalizedRX;
  73344. }
  73345. }
  73346. if (RSValues.y != 0) {
  73347. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  73348. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  73349. camera.inertialBetaOffset += normalizedRY;
  73350. }
  73351. }
  73352. }
  73353. var LSValues = this.gamepad.leftStick;
  73354. if (LSValues && LSValues.y != 0) {
  73355. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  73356. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  73357. this.camera.inertialRadiusOffset -= normalizedLY;
  73358. }
  73359. }
  73360. }
  73361. };
  73362. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  73363. return "ArcRotateCameraGamepadInput";
  73364. };
  73365. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  73366. return "gamepad";
  73367. };
  73368. __decorate([
  73369. BABYLON.serialize()
  73370. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  73371. __decorate([
  73372. BABYLON.serialize()
  73373. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  73374. return ArcRotateCameraGamepadInput;
  73375. }());
  73376. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  73377. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  73378. })(BABYLON || (BABYLON = {}));
  73379. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  73380. var BABYLON;
  73381. (function (BABYLON) {
  73382. var GamepadManager = /** @class */ (function () {
  73383. function GamepadManager(_scene) {
  73384. var _this = this;
  73385. this._scene = _scene;
  73386. this._babylonGamepads = [];
  73387. this._oneGamepadConnected = false;
  73388. /** @hidden */
  73389. this._isMonitoring = false;
  73390. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  73391. if (!BABYLON.Tools.IsWindowObjectExist()) {
  73392. this._gamepadEventSupported = false;
  73393. }
  73394. else {
  73395. this._gamepadEventSupported = 'GamepadEvent' in window;
  73396. this._gamepadSupport = (navigator.getGamepads ||
  73397. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  73398. }
  73399. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  73400. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  73401. for (var i in _this._babylonGamepads) {
  73402. var gamepad = _this._babylonGamepads[i];
  73403. if (gamepad && gamepad._isConnected) {
  73404. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  73405. }
  73406. }
  73407. });
  73408. this._onGamepadConnectedEvent = function (evt) {
  73409. var gamepad = evt.gamepad;
  73410. if (gamepad.index in _this._babylonGamepads) {
  73411. if (_this._babylonGamepads[gamepad.index].isConnected) {
  73412. return;
  73413. }
  73414. }
  73415. var newGamepad;
  73416. if (_this._babylonGamepads[gamepad.index]) {
  73417. newGamepad = _this._babylonGamepads[gamepad.index];
  73418. newGamepad.browserGamepad = gamepad;
  73419. newGamepad._isConnected = true;
  73420. }
  73421. else {
  73422. newGamepad = _this._addNewGamepad(gamepad);
  73423. }
  73424. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  73425. _this._startMonitoringGamepads();
  73426. };
  73427. this._onGamepadDisconnectedEvent = function (evt) {
  73428. var gamepad = evt.gamepad;
  73429. // Remove the gamepad from the list of gamepads to monitor.
  73430. for (var i in _this._babylonGamepads) {
  73431. if (_this._babylonGamepads[i].index === gamepad.index) {
  73432. var disconnectedGamepad = _this._babylonGamepads[i];
  73433. disconnectedGamepad._isConnected = false;
  73434. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  73435. break;
  73436. }
  73437. }
  73438. };
  73439. if (this._gamepadSupport) {
  73440. //first add already-connected gamepads
  73441. this._updateGamepadObjects();
  73442. if (this._babylonGamepads.length) {
  73443. this._startMonitoringGamepads();
  73444. }
  73445. // Checking if the gamepad connected event is supported (like in Firefox)
  73446. if (this._gamepadEventSupported) {
  73447. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  73448. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  73449. }
  73450. else {
  73451. this._startMonitoringGamepads();
  73452. }
  73453. }
  73454. }
  73455. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  73456. get: function () {
  73457. return this._babylonGamepads;
  73458. },
  73459. enumerable: true,
  73460. configurable: true
  73461. });
  73462. GamepadManager.prototype.getGamepadByType = function (type) {
  73463. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  73464. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  73465. var gamepad = _a[_i];
  73466. if (gamepad && gamepad.type === type) {
  73467. return gamepad;
  73468. }
  73469. }
  73470. return null;
  73471. };
  73472. GamepadManager.prototype.dispose = function () {
  73473. if (this._gamepadEventSupported) {
  73474. if (this._onGamepadConnectedEvent) {
  73475. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  73476. }
  73477. if (this._onGamepadDisconnectedEvent) {
  73478. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  73479. }
  73480. this._onGamepadConnectedEvent = null;
  73481. this._onGamepadDisconnectedEvent = null;
  73482. }
  73483. this._babylonGamepads.forEach(function (gamepad) {
  73484. gamepad.dispose();
  73485. });
  73486. this.onGamepadConnectedObservable.clear();
  73487. this.onGamepadDisconnectedObservable.clear();
  73488. this._oneGamepadConnected = false;
  73489. this._stopMonitoringGamepads();
  73490. this._babylonGamepads = [];
  73491. };
  73492. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  73493. if (!this._oneGamepadConnected) {
  73494. this._oneGamepadConnected = true;
  73495. }
  73496. var newGamepad;
  73497. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  73498. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  73499. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  73500. }
  73501. // if pose is supported, use the (WebVR) pose enabled controller
  73502. else if (gamepad.pose) {
  73503. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  73504. }
  73505. else {
  73506. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  73507. }
  73508. this._babylonGamepads[newGamepad.index] = newGamepad;
  73509. return newGamepad;
  73510. };
  73511. GamepadManager.prototype._startMonitoringGamepads = function () {
  73512. if (!this._isMonitoring) {
  73513. this._isMonitoring = true;
  73514. //back-comp
  73515. if (!this._scene) {
  73516. this._checkGamepadsStatus();
  73517. }
  73518. }
  73519. };
  73520. GamepadManager.prototype._stopMonitoringGamepads = function () {
  73521. this._isMonitoring = false;
  73522. };
  73523. /** @hidden */
  73524. GamepadManager.prototype._checkGamepadsStatus = function () {
  73525. var _this = this;
  73526. // Hack to be compatible Chrome
  73527. this._updateGamepadObjects();
  73528. for (var i in this._babylonGamepads) {
  73529. var gamepad = this._babylonGamepads[i];
  73530. if (!gamepad || !gamepad.isConnected) {
  73531. continue;
  73532. }
  73533. gamepad.update();
  73534. }
  73535. if (this._isMonitoring && !this._scene) {
  73536. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  73537. }
  73538. };
  73539. // This function is called only on Chrome, which does not properly support
  73540. // connection/disconnection events and forces you to recopy again the gamepad object
  73541. GamepadManager.prototype._updateGamepadObjects = function () {
  73542. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  73543. for (var i = 0; i < gamepads.length; i++) {
  73544. var gamepad = gamepads[i];
  73545. if (gamepad) {
  73546. if (!this._babylonGamepads[gamepad.index]) {
  73547. var newGamepad = this._addNewGamepad(gamepad);
  73548. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  73549. }
  73550. else {
  73551. // Forced to copy again this object for Chrome for unknown reason
  73552. this._babylonGamepads[i].browserGamepad = gamepad;
  73553. if (!this._babylonGamepads[i].isConnected) {
  73554. this._babylonGamepads[i]._isConnected = true;
  73555. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  73556. }
  73557. }
  73558. }
  73559. }
  73560. };
  73561. return GamepadManager;
  73562. }());
  73563. BABYLON.GamepadManager = GamepadManager;
  73564. })(BABYLON || (BABYLON = {}));
  73565. //# sourceMappingURL=babylon.gamepadManager.js.map
  73566. var BABYLON;
  73567. (function (BABYLON) {
  73568. var StickValues = /** @class */ (function () {
  73569. function StickValues(x, y) {
  73570. this.x = x;
  73571. this.y = y;
  73572. }
  73573. return StickValues;
  73574. }());
  73575. BABYLON.StickValues = StickValues;
  73576. var Gamepad = /** @class */ (function () {
  73577. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  73578. if (leftStickX === void 0) { leftStickX = 0; }
  73579. if (leftStickY === void 0) { leftStickY = 1; }
  73580. if (rightStickX === void 0) { rightStickX = 2; }
  73581. if (rightStickY === void 0) { rightStickY = 3; }
  73582. this.id = id;
  73583. this.index = index;
  73584. this.browserGamepad = browserGamepad;
  73585. /** @hidden */
  73586. this._isConnected = true;
  73587. this._invertLeftStickY = false;
  73588. this.type = Gamepad.GAMEPAD;
  73589. this._leftStickAxisX = leftStickX;
  73590. this._leftStickAxisY = leftStickY;
  73591. this._rightStickAxisX = rightStickX;
  73592. this._rightStickAxisY = rightStickY;
  73593. if (this.browserGamepad.axes.length >= 2) {
  73594. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  73595. }
  73596. if (this.browserGamepad.axes.length >= 4) {
  73597. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  73598. }
  73599. }
  73600. Object.defineProperty(Gamepad.prototype, "isConnected", {
  73601. get: function () {
  73602. return this._isConnected;
  73603. },
  73604. enumerable: true,
  73605. configurable: true
  73606. });
  73607. Gamepad.prototype.onleftstickchanged = function (callback) {
  73608. this._onleftstickchanged = callback;
  73609. };
  73610. Gamepad.prototype.onrightstickchanged = function (callback) {
  73611. this._onrightstickchanged = callback;
  73612. };
  73613. Object.defineProperty(Gamepad.prototype, "leftStick", {
  73614. get: function () {
  73615. return this._leftStick;
  73616. },
  73617. set: function (newValues) {
  73618. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  73619. this._onleftstickchanged(newValues);
  73620. }
  73621. this._leftStick = newValues;
  73622. },
  73623. enumerable: true,
  73624. configurable: true
  73625. });
  73626. Object.defineProperty(Gamepad.prototype, "rightStick", {
  73627. get: function () {
  73628. return this._rightStick;
  73629. },
  73630. set: function (newValues) {
  73631. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  73632. this._onrightstickchanged(newValues);
  73633. }
  73634. this._rightStick = newValues;
  73635. },
  73636. enumerable: true,
  73637. configurable: true
  73638. });
  73639. Gamepad.prototype.update = function () {
  73640. if (this._leftStick) {
  73641. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  73642. if (this._invertLeftStickY) {
  73643. this.leftStick.y *= -1;
  73644. }
  73645. }
  73646. if (this._rightStick) {
  73647. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  73648. }
  73649. };
  73650. Gamepad.prototype.dispose = function () {
  73651. };
  73652. Gamepad.GAMEPAD = 0;
  73653. Gamepad.GENERIC = 1;
  73654. Gamepad.XBOX = 2;
  73655. Gamepad.POSE_ENABLED = 3;
  73656. return Gamepad;
  73657. }());
  73658. BABYLON.Gamepad = Gamepad;
  73659. var GenericPad = /** @class */ (function (_super) {
  73660. __extends(GenericPad, _super);
  73661. function GenericPad(id, index, browserGamepad) {
  73662. var _this = _super.call(this, id, index, browserGamepad) || this;
  73663. _this.onButtonDownObservable = new BABYLON.Observable();
  73664. _this.onButtonUpObservable = new BABYLON.Observable();
  73665. _this.type = Gamepad.GENERIC;
  73666. _this._buttons = new Array(browserGamepad.buttons.length);
  73667. return _this;
  73668. }
  73669. GenericPad.prototype.onbuttondown = function (callback) {
  73670. this._onbuttondown = callback;
  73671. };
  73672. GenericPad.prototype.onbuttonup = function (callback) {
  73673. this._onbuttonup = callback;
  73674. };
  73675. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  73676. if (newValue !== currentValue) {
  73677. if (newValue === 1) {
  73678. if (this._onbuttondown) {
  73679. this._onbuttondown(buttonIndex);
  73680. }
  73681. this.onButtonDownObservable.notifyObservers(buttonIndex);
  73682. }
  73683. if (newValue === 0) {
  73684. if (this._onbuttonup) {
  73685. this._onbuttonup(buttonIndex);
  73686. }
  73687. this.onButtonUpObservable.notifyObservers(buttonIndex);
  73688. }
  73689. }
  73690. return newValue;
  73691. };
  73692. GenericPad.prototype.update = function () {
  73693. _super.prototype.update.call(this);
  73694. for (var index = 0; index < this._buttons.length; index++) {
  73695. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  73696. }
  73697. };
  73698. GenericPad.prototype.dispose = function () {
  73699. _super.prototype.dispose.call(this);
  73700. this.onButtonDownObservable.clear();
  73701. this.onButtonUpObservable.clear();
  73702. };
  73703. return GenericPad;
  73704. }(Gamepad));
  73705. BABYLON.GenericPad = GenericPad;
  73706. })(BABYLON || (BABYLON = {}));
  73707. //# sourceMappingURL=babylon.gamepad.js.map
  73708. var BABYLON;
  73709. (function (BABYLON) {
  73710. /**
  73711. * Defines supported buttons for XBox360 compatible gamepads
  73712. */
  73713. var Xbox360Button;
  73714. (function (Xbox360Button) {
  73715. /** A */
  73716. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  73717. /** B */
  73718. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  73719. /** X */
  73720. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  73721. /** Y */
  73722. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  73723. /** Start */
  73724. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  73725. /** Back */
  73726. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  73727. /** Left button */
  73728. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  73729. /** Right button */
  73730. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  73731. /** Left stick */
  73732. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  73733. /** Right stick */
  73734. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  73735. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  73736. /** Defines values for XBox360 DPad */
  73737. var Xbox360Dpad;
  73738. (function (Xbox360Dpad) {
  73739. /** Up */
  73740. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  73741. /** Down */
  73742. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  73743. /** Left */
  73744. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  73745. /** Right */
  73746. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  73747. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  73748. /**
  73749. * Defines a XBox360 gamepad
  73750. */
  73751. var Xbox360Pad = /** @class */ (function (_super) {
  73752. __extends(Xbox360Pad, _super);
  73753. /**
  73754. * Creates a new XBox360 gamepad object
  73755. * @param id defines the id of this gamepad
  73756. * @param index defines its index
  73757. * @param gamepad defines the internal HTML gamepad object
  73758. * @param xboxOne defines if it is a XBox One gamepad
  73759. */
  73760. function Xbox360Pad(id, index, gamepad, xboxOne) {
  73761. if (xboxOne === void 0) { xboxOne = false; }
  73762. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  73763. _this._leftTrigger = 0;
  73764. _this._rightTrigger = 0;
  73765. /** Observable raised when a button is pressed */
  73766. _this.onButtonDownObservable = new BABYLON.Observable();
  73767. /** Observable raised when a button is released */
  73768. _this.onButtonUpObservable = new BABYLON.Observable();
  73769. /** Observable raised when a pad is pressed */
  73770. _this.onPadDownObservable = new BABYLON.Observable();
  73771. /** Observable raised when a pad is released */
  73772. _this.onPadUpObservable = new BABYLON.Observable();
  73773. _this._buttonA = 0;
  73774. _this._buttonB = 0;
  73775. _this._buttonX = 0;
  73776. _this._buttonY = 0;
  73777. _this._buttonBack = 0;
  73778. _this._buttonStart = 0;
  73779. _this._buttonLB = 0;
  73780. _this._buttonRB = 0;
  73781. _this._buttonLeftStick = 0;
  73782. _this._buttonRightStick = 0;
  73783. _this._dPadUp = 0;
  73784. _this._dPadDown = 0;
  73785. _this._dPadLeft = 0;
  73786. _this._dPadRight = 0;
  73787. _this._isXboxOnePad = false;
  73788. _this.type = BABYLON.Gamepad.XBOX;
  73789. _this._isXboxOnePad = xboxOne;
  73790. return _this;
  73791. }
  73792. /**
  73793. * Defines the callback to call when left trigger is pressed
  73794. * @param callback defines the callback to use
  73795. */
  73796. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  73797. this._onlefttriggerchanged = callback;
  73798. };
  73799. /**
  73800. * Defines the callback to call when right trigger is pressed
  73801. * @param callback defines the callback to use
  73802. */
  73803. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  73804. this._onrighttriggerchanged = callback;
  73805. };
  73806. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  73807. /**
  73808. * Gets or sets left trigger value
  73809. */
  73810. get: function () {
  73811. return this._leftTrigger;
  73812. },
  73813. set: function (newValue) {
  73814. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  73815. this._onlefttriggerchanged(newValue);
  73816. }
  73817. this._leftTrigger = newValue;
  73818. },
  73819. enumerable: true,
  73820. configurable: true
  73821. });
  73822. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  73823. /**
  73824. * Gets or sets right trigger value
  73825. */
  73826. get: function () {
  73827. return this._rightTrigger;
  73828. },
  73829. set: function (newValue) {
  73830. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  73831. this._onrighttriggerchanged(newValue);
  73832. }
  73833. this._rightTrigger = newValue;
  73834. },
  73835. enumerable: true,
  73836. configurable: true
  73837. });
  73838. /**
  73839. * Defines the callback to call when a button is pressed
  73840. * @param callback defines the callback to use
  73841. */
  73842. Xbox360Pad.prototype.onbuttondown = function (callback) {
  73843. this._onbuttondown = callback;
  73844. };
  73845. /**
  73846. * Defines the callback to call when a button is released
  73847. * @param callback defines the callback to use
  73848. */
  73849. Xbox360Pad.prototype.onbuttonup = function (callback) {
  73850. this._onbuttonup = callback;
  73851. };
  73852. /**
  73853. * Defines the callback to call when a pad is pressed
  73854. * @param callback defines the callback to use
  73855. */
  73856. Xbox360Pad.prototype.ondpaddown = function (callback) {
  73857. this._ondpaddown = callback;
  73858. };
  73859. /**
  73860. * Defines the callback to call when a pad is released
  73861. * @param callback defines the callback to use
  73862. */
  73863. Xbox360Pad.prototype.ondpadup = function (callback) {
  73864. this._ondpadup = callback;
  73865. };
  73866. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  73867. if (newValue !== currentValue) {
  73868. if (newValue === 1) {
  73869. if (this._onbuttondown) {
  73870. this._onbuttondown(buttonType);
  73871. }
  73872. this.onButtonDownObservable.notifyObservers(buttonType);
  73873. }
  73874. if (newValue === 0) {
  73875. if (this._onbuttonup) {
  73876. this._onbuttonup(buttonType);
  73877. }
  73878. this.onButtonUpObservable.notifyObservers(buttonType);
  73879. }
  73880. }
  73881. return newValue;
  73882. };
  73883. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  73884. if (newValue !== currentValue) {
  73885. if (newValue === 1) {
  73886. if (this._ondpaddown) {
  73887. this._ondpaddown(buttonType);
  73888. }
  73889. this.onPadDownObservable.notifyObservers(buttonType);
  73890. }
  73891. if (newValue === 0) {
  73892. if (this._ondpadup) {
  73893. this._ondpadup(buttonType);
  73894. }
  73895. this.onPadUpObservable.notifyObservers(buttonType);
  73896. }
  73897. }
  73898. return newValue;
  73899. };
  73900. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  73901. /** Gets or sets value of A button */
  73902. get: function () {
  73903. return this._buttonA;
  73904. },
  73905. set: function (value) {
  73906. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  73907. },
  73908. enumerable: true,
  73909. configurable: true
  73910. });
  73911. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  73912. /** Gets or sets value of B button */
  73913. get: function () {
  73914. return this._buttonB;
  73915. },
  73916. set: function (value) {
  73917. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  73918. },
  73919. enumerable: true,
  73920. configurable: true
  73921. });
  73922. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  73923. /** Gets or sets value of X button */
  73924. get: function () {
  73925. return this._buttonX;
  73926. },
  73927. set: function (value) {
  73928. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  73929. },
  73930. enumerable: true,
  73931. configurable: true
  73932. });
  73933. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  73934. /** Gets or sets value of Y button */
  73935. get: function () {
  73936. return this._buttonY;
  73937. },
  73938. set: function (value) {
  73939. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  73940. },
  73941. enumerable: true,
  73942. configurable: true
  73943. });
  73944. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  73945. /** Gets or sets value of Start button */
  73946. get: function () {
  73947. return this._buttonStart;
  73948. },
  73949. set: function (value) {
  73950. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  73951. },
  73952. enumerable: true,
  73953. configurable: true
  73954. });
  73955. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  73956. /** Gets or sets value of Back button */
  73957. get: function () {
  73958. return this._buttonBack;
  73959. },
  73960. set: function (value) {
  73961. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  73962. },
  73963. enumerable: true,
  73964. configurable: true
  73965. });
  73966. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  73967. /** Gets or sets value of Left button */
  73968. get: function () {
  73969. return this._buttonLB;
  73970. },
  73971. set: function (value) {
  73972. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  73973. },
  73974. enumerable: true,
  73975. configurable: true
  73976. });
  73977. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  73978. /** Gets or sets value of Right button */
  73979. get: function () {
  73980. return this._buttonRB;
  73981. },
  73982. set: function (value) {
  73983. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  73984. },
  73985. enumerable: true,
  73986. configurable: true
  73987. });
  73988. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  73989. /** Gets or sets value of left stick */
  73990. get: function () {
  73991. return this._buttonLeftStick;
  73992. },
  73993. set: function (value) {
  73994. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  73995. },
  73996. enumerable: true,
  73997. configurable: true
  73998. });
  73999. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  74000. /** Gets or sets value of right stick */
  74001. get: function () {
  74002. return this._buttonRightStick;
  74003. },
  74004. set: function (value) {
  74005. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  74006. },
  74007. enumerable: true,
  74008. configurable: true
  74009. });
  74010. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  74011. /** Gets or sets value of DPad up */
  74012. get: function () {
  74013. return this._dPadUp;
  74014. },
  74015. set: function (value) {
  74016. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  74017. },
  74018. enumerable: true,
  74019. configurable: true
  74020. });
  74021. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  74022. /** Gets or sets value of DPad down */
  74023. get: function () {
  74024. return this._dPadDown;
  74025. },
  74026. set: function (value) {
  74027. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  74028. },
  74029. enumerable: true,
  74030. configurable: true
  74031. });
  74032. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  74033. /** Gets or sets value of DPad left */
  74034. get: function () {
  74035. return this._dPadLeft;
  74036. },
  74037. set: function (value) {
  74038. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  74039. },
  74040. enumerable: true,
  74041. configurable: true
  74042. });
  74043. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  74044. /** Gets or sets value of DPad right */
  74045. get: function () {
  74046. return this._dPadRight;
  74047. },
  74048. set: function (value) {
  74049. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  74050. },
  74051. enumerable: true,
  74052. configurable: true
  74053. });
  74054. /**
  74055. * Force the gamepad to synchronize with device values
  74056. */
  74057. Xbox360Pad.prototype.update = function () {
  74058. _super.prototype.update.call(this);
  74059. if (this._isXboxOnePad) {
  74060. this.buttonA = this.browserGamepad.buttons[0].value;
  74061. this.buttonB = this.browserGamepad.buttons[1].value;
  74062. this.buttonX = this.browserGamepad.buttons[2].value;
  74063. this.buttonY = this.browserGamepad.buttons[3].value;
  74064. this.buttonLB = this.browserGamepad.buttons[4].value;
  74065. this.buttonRB = this.browserGamepad.buttons[5].value;
  74066. this.leftTrigger = this.browserGamepad.axes[2];
  74067. this.rightTrigger = this.browserGamepad.axes[5];
  74068. this.buttonBack = this.browserGamepad.buttons[9].value;
  74069. this.buttonStart = this.browserGamepad.buttons[8].value;
  74070. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  74071. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  74072. this.dPadUp = this.browserGamepad.buttons[11].value;
  74073. this.dPadDown = this.browserGamepad.buttons[12].value;
  74074. this.dPadLeft = this.browserGamepad.buttons[13].value;
  74075. this.dPadRight = this.browserGamepad.buttons[14].value;
  74076. }
  74077. else {
  74078. this.buttonA = this.browserGamepad.buttons[0].value;
  74079. this.buttonB = this.browserGamepad.buttons[1].value;
  74080. this.buttonX = this.browserGamepad.buttons[2].value;
  74081. this.buttonY = this.browserGamepad.buttons[3].value;
  74082. this.buttonLB = this.browserGamepad.buttons[4].value;
  74083. this.buttonRB = this.browserGamepad.buttons[5].value;
  74084. this.leftTrigger = this.browserGamepad.buttons[6].value;
  74085. this.rightTrigger = this.browserGamepad.buttons[7].value;
  74086. this.buttonBack = this.browserGamepad.buttons[8].value;
  74087. this.buttonStart = this.browserGamepad.buttons[9].value;
  74088. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  74089. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  74090. this.dPadUp = this.browserGamepad.buttons[12].value;
  74091. this.dPadDown = this.browserGamepad.buttons[13].value;
  74092. this.dPadLeft = this.browserGamepad.buttons[14].value;
  74093. this.dPadRight = this.browserGamepad.buttons[15].value;
  74094. }
  74095. };
  74096. Xbox360Pad.prototype.dispose = function () {
  74097. _super.prototype.dispose.call(this);
  74098. this.onButtonDownObservable.clear();
  74099. this.onButtonUpObservable.clear();
  74100. this.onPadDownObservable.clear();
  74101. this.onPadUpObservable.clear();
  74102. };
  74103. return Xbox360Pad;
  74104. }(BABYLON.Gamepad));
  74105. BABYLON.Xbox360Pad = Xbox360Pad;
  74106. })(BABYLON || (BABYLON = {}));
  74107. //# sourceMappingURL=babylon.xboxGamepad.js.map
  74108. var BABYLON;
  74109. (function (BABYLON) {
  74110. /**
  74111. * Defines the types of pose enabled controllers that are supported
  74112. */
  74113. var PoseEnabledControllerType;
  74114. (function (PoseEnabledControllerType) {
  74115. /**
  74116. * HTC Vive
  74117. */
  74118. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  74119. /**
  74120. * Oculus Rift
  74121. */
  74122. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  74123. /**
  74124. * Windows mixed reality
  74125. */
  74126. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  74127. /**
  74128. * Samsung gear VR
  74129. */
  74130. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  74131. /**
  74132. * Google Daydream
  74133. */
  74134. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  74135. /**
  74136. * Generic
  74137. */
  74138. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  74139. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  74140. /**
  74141. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  74142. */
  74143. var PoseEnabledControllerHelper = /** @class */ (function () {
  74144. function PoseEnabledControllerHelper() {
  74145. }
  74146. /**
  74147. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  74148. * @param vrGamepad the gamepad to initialized
  74149. * @returns a vr controller of the type the gamepad identified as
  74150. */
  74151. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  74152. // Oculus Touch
  74153. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  74154. return new BABYLON.OculusTouchController(vrGamepad);
  74155. }
  74156. // Windows Mixed Reality controllers
  74157. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  74158. return new BABYLON.WindowsMotionController(vrGamepad);
  74159. }
  74160. // HTC Vive
  74161. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  74162. return new BABYLON.ViveController(vrGamepad);
  74163. }
  74164. // Samsung/Oculus Gear VR or Oculus Go
  74165. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  74166. return new BABYLON.GearVRController(vrGamepad);
  74167. }
  74168. // Google Daydream
  74169. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  74170. return new BABYLON.DaydreamController(vrGamepad);
  74171. }
  74172. // Generic
  74173. else {
  74174. return new BABYLON.GenericController(vrGamepad);
  74175. }
  74176. };
  74177. return PoseEnabledControllerHelper;
  74178. }());
  74179. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  74180. /**
  74181. * Defines the PoseEnabledController object that contains state of a vr capable controller
  74182. */
  74183. var PoseEnabledController = /** @class */ (function (_super) {
  74184. __extends(PoseEnabledController, _super);
  74185. /**
  74186. * Creates a new PoseEnabledController from a gamepad
  74187. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  74188. */
  74189. function PoseEnabledController(browserGamepad) {
  74190. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  74191. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  74192. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  74193. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  74194. /**
  74195. * The device position in babylon space
  74196. */
  74197. _this.devicePosition = BABYLON.Vector3.Zero();
  74198. /**
  74199. * The device rotation in babylon space
  74200. */
  74201. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  74202. /**
  74203. * The scale factor of the device in babylon space
  74204. */
  74205. _this.deviceScaleFactor = 1;
  74206. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  74207. /**
  74208. * Internal, matrix used to convert room space to babylon space
  74209. * @hidden
  74210. */
  74211. _this._deviceToWorld = BABYLON.Matrix.Identity();
  74212. /**
  74213. * Node to be used when casting a ray from the controller
  74214. * @hidden
  74215. */
  74216. _this._pointingPoseNode = null;
  74217. _this._workingMatrix = BABYLON.Matrix.Identity();
  74218. /**
  74219. * @hidden
  74220. */
  74221. _this._meshAttachedObservable = new BABYLON.Observable();
  74222. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  74223. _this.controllerType = PoseEnabledControllerType.GENERIC;
  74224. _this.position = BABYLON.Vector3.Zero();
  74225. _this.rotationQuaternion = new BABYLON.Quaternion();
  74226. _this._calculatedPosition = BABYLON.Vector3.Zero();
  74227. _this._calculatedRotation = new BABYLON.Quaternion();
  74228. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  74229. return _this;
  74230. }
  74231. /**
  74232. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  74233. */
  74234. PoseEnabledController.prototype.update = function () {
  74235. _super.prototype.update.call(this);
  74236. this._updatePoseAndMesh();
  74237. };
  74238. /**
  74239. * Updates only the pose device and mesh without doing any button event checking
  74240. */
  74241. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  74242. var pose = this.browserGamepad.pose;
  74243. this.updateFromDevice(pose);
  74244. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  74245. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  74246. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  74247. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  74248. if (this._mesh) {
  74249. this._mesh.position.copyFrom(this.devicePosition);
  74250. if (this._mesh.rotationQuaternion) {
  74251. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  74252. }
  74253. }
  74254. };
  74255. /**
  74256. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  74257. * @param poseData raw pose fromthe device
  74258. */
  74259. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  74260. if (poseData) {
  74261. this.rawPose = poseData;
  74262. if (poseData.position) {
  74263. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  74264. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  74265. this._deviceRoomPosition.z *= -1;
  74266. }
  74267. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  74268. this._calculatedPosition.addInPlace(this.position);
  74269. }
  74270. var pose = this.rawPose;
  74271. if (poseData.orientation && pose.orientation) {
  74272. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  74273. if (this._mesh) {
  74274. if (this._mesh.getScene().useRightHandedSystem) {
  74275. this._deviceRoomRotationQuaternion.z *= -1;
  74276. this._deviceRoomRotationQuaternion.w *= -1;
  74277. }
  74278. else {
  74279. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  74280. }
  74281. }
  74282. // if the camera is set, rotate to the camera's rotation
  74283. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  74284. }
  74285. }
  74286. };
  74287. /**
  74288. * Attaches a mesh to the controller
  74289. * @param mesh the mesh to be attached
  74290. */
  74291. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  74292. if (this._mesh) {
  74293. this._mesh.parent = null;
  74294. }
  74295. this._mesh = mesh;
  74296. if (this._poseControlledCamera) {
  74297. this._mesh.parent = this._poseControlledCamera;
  74298. }
  74299. if (!this._mesh.rotationQuaternion) {
  74300. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  74301. }
  74302. // 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
  74303. this._updatePoseAndMesh();
  74304. if (this._pointingPoseNode) {
  74305. var parents = [];
  74306. var obj = this._pointingPoseNode;
  74307. while (obj.parent) {
  74308. parents.push(obj.parent);
  74309. obj = obj.parent;
  74310. }
  74311. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  74312. }
  74313. this._meshAttachedObservable.notifyObservers(mesh);
  74314. };
  74315. /**
  74316. * Attaches the controllers mesh to a camera
  74317. * @param camera the camera the mesh should be attached to
  74318. */
  74319. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  74320. this._poseControlledCamera = camera;
  74321. if (this._mesh) {
  74322. this._mesh.parent = this._poseControlledCamera;
  74323. }
  74324. };
  74325. /**
  74326. * Disposes of the controller
  74327. */
  74328. PoseEnabledController.prototype.dispose = function () {
  74329. if (this._mesh) {
  74330. this._mesh.dispose();
  74331. }
  74332. this._mesh = null;
  74333. _super.prototype.dispose.call(this);
  74334. };
  74335. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  74336. /**
  74337. * The mesh that is attached to the controller
  74338. */
  74339. get: function () {
  74340. return this._mesh;
  74341. },
  74342. enumerable: true,
  74343. configurable: true
  74344. });
  74345. /**
  74346. * Gets the ray of the controller in the direction the controller is pointing
  74347. * @param length the length the resulting ray should be
  74348. * @returns a ray in the direction the controller is pointing
  74349. */
  74350. PoseEnabledController.prototype.getForwardRay = function (length) {
  74351. if (length === void 0) { length = 100; }
  74352. if (!this.mesh) {
  74353. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  74354. }
  74355. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  74356. var origin = m.getTranslation();
  74357. var forward = new BABYLON.Vector3(0, 0, -1);
  74358. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  74359. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  74360. return new BABYLON.Ray(origin, direction, length);
  74361. };
  74362. /**
  74363. * Name of the child mesh that can be used to cast a ray from the controller
  74364. */
  74365. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  74366. return PoseEnabledController;
  74367. }(BABYLON.Gamepad));
  74368. BABYLON.PoseEnabledController = PoseEnabledController;
  74369. })(BABYLON || (BABYLON = {}));
  74370. //# sourceMappingURL=babylon.poseEnabledController.js.map
  74371. var BABYLON;
  74372. (function (BABYLON) {
  74373. /**
  74374. * Defines the WebVRController object that represents controllers tracked in 3D space
  74375. */
  74376. var WebVRController = /** @class */ (function (_super) {
  74377. __extends(WebVRController, _super);
  74378. /**
  74379. * Creates a new WebVRController from a gamepad
  74380. * @param vrGamepad the gamepad that the WebVRController should be created from
  74381. */
  74382. function WebVRController(vrGamepad) {
  74383. var _this = _super.call(this, vrGamepad) || this;
  74384. // Observables
  74385. /**
  74386. * Fired when the trigger state has changed
  74387. */
  74388. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  74389. /**
  74390. * Fired when the main button state has changed
  74391. */
  74392. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  74393. /**
  74394. * Fired when the secondary button state has changed
  74395. */
  74396. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  74397. /**
  74398. * Fired when the pad state has changed
  74399. */
  74400. _this.onPadStateChangedObservable = new BABYLON.Observable();
  74401. /**
  74402. * Fired when controllers stick values have changed
  74403. */
  74404. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  74405. /**
  74406. * X and Y axis corrisponding to the controllers joystick
  74407. */
  74408. _this.pad = { x: 0, y: 0 };
  74409. // avoid GC, store state in a tmp object
  74410. _this._changes = {
  74411. pressChanged: false,
  74412. touchChanged: false,
  74413. valueChanged: false,
  74414. changed: false
  74415. };
  74416. _this._buttons = new Array(vrGamepad.buttons.length);
  74417. _this.hand = vrGamepad.hand;
  74418. return _this;
  74419. }
  74420. /**
  74421. * Fired when a controller button's state has changed
  74422. * @param callback the callback containing the button that was modified
  74423. */
  74424. WebVRController.prototype.onButtonStateChange = function (callback) {
  74425. this._onButtonStateChange = callback;
  74426. };
  74427. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  74428. /**
  74429. * The default controller model for the controller
  74430. */
  74431. get: function () {
  74432. return this._defaultModel;
  74433. },
  74434. enumerable: true,
  74435. configurable: true
  74436. });
  74437. /**
  74438. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  74439. */
  74440. WebVRController.prototype.update = function () {
  74441. _super.prototype.update.call(this);
  74442. for (var index = 0; index < this._buttons.length; index++) {
  74443. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  74444. }
  74445. ;
  74446. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  74447. this.pad.x = this.leftStick.x;
  74448. this.pad.y = this.leftStick.y;
  74449. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  74450. }
  74451. };
  74452. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  74453. if (!newState) {
  74454. newState = {
  74455. pressed: false,
  74456. touched: false,
  74457. value: 0
  74458. };
  74459. }
  74460. if (!currentState) {
  74461. this._buttons[buttonIndex] = {
  74462. pressed: newState.pressed,
  74463. touched: newState.touched,
  74464. value: newState.value
  74465. };
  74466. return;
  74467. }
  74468. this._checkChanges(newState, currentState);
  74469. if (this._changes.changed) {
  74470. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  74471. this._handleButtonChange(buttonIndex, newState, this._changes);
  74472. }
  74473. this._buttons[buttonIndex].pressed = newState.pressed;
  74474. this._buttons[buttonIndex].touched = newState.touched;
  74475. // oculus triggers are never 0, thou not touched.
  74476. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  74477. };
  74478. WebVRController.prototype._checkChanges = function (newState, currentState) {
  74479. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  74480. this._changes.touchChanged = newState.touched !== currentState.touched;
  74481. this._changes.valueChanged = newState.value !== currentState.value;
  74482. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  74483. return this._changes;
  74484. };
  74485. /**
  74486. * Disposes of th webVRCOntroller
  74487. */
  74488. WebVRController.prototype.dispose = function () {
  74489. _super.prototype.dispose.call(this);
  74490. this.onTriggerStateChangedObservable.clear();
  74491. this.onMainButtonStateChangedObservable.clear();
  74492. this.onSecondaryButtonStateChangedObservable.clear();
  74493. this.onPadStateChangedObservable.clear();
  74494. this.onPadValuesChangedObservable.clear();
  74495. };
  74496. return WebVRController;
  74497. }(BABYLON.PoseEnabledController));
  74498. BABYLON.WebVRController = WebVRController;
  74499. })(BABYLON || (BABYLON = {}));
  74500. //# sourceMappingURL=babylon.webVRController.js.map
  74501. var BABYLON;
  74502. (function (BABYLON) {
  74503. /**
  74504. * Oculus Touch Controller
  74505. */
  74506. var OculusTouchController = /** @class */ (function (_super) {
  74507. __extends(OculusTouchController, _super);
  74508. /**
  74509. * Creates a new OculusTouchController from a gamepad
  74510. * @param vrGamepad the gamepad that the controller should be created from
  74511. */
  74512. function OculusTouchController(vrGamepad) {
  74513. var _this = _super.call(this, vrGamepad) || this;
  74514. /**
  74515. * Fired when the secondary trigger on this controller is modified
  74516. */
  74517. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  74518. /**
  74519. * Fired when the thumb rest on this controller is modified
  74520. */
  74521. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  74522. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  74523. return _this;
  74524. }
  74525. /**
  74526. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  74527. * @param scene scene in which to add meshes
  74528. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  74529. */
  74530. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  74531. var _this = this;
  74532. var meshName;
  74533. // Hand
  74534. if (this.hand === 'left') {
  74535. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  74536. }
  74537. else { // Right is the default if no hand is specified
  74538. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  74539. }
  74540. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  74541. /*
  74542. Parent Mesh name: oculus_touch_left
  74543. - body
  74544. - trigger
  74545. - thumbstick
  74546. - grip
  74547. - button_y
  74548. - button_x
  74549. - button_enter
  74550. */
  74551. _this._defaultModel = newMeshes[1];
  74552. _this.attachToMesh(_this._defaultModel);
  74553. if (meshLoaded) {
  74554. meshLoaded(_this._defaultModel);
  74555. }
  74556. });
  74557. };
  74558. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  74559. /**
  74560. * Fired when the A button on this controller is modified
  74561. */
  74562. get: function () {
  74563. if (this.hand === 'right') {
  74564. return this.onMainButtonStateChangedObservable;
  74565. }
  74566. else {
  74567. throw new Error('No A button on left hand');
  74568. }
  74569. },
  74570. enumerable: true,
  74571. configurable: true
  74572. });
  74573. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  74574. /**
  74575. * Fired when the B button on this controller is modified
  74576. */
  74577. get: function () {
  74578. if (this.hand === 'right') {
  74579. return this.onSecondaryButtonStateChangedObservable;
  74580. }
  74581. else {
  74582. throw new Error('No B button on left hand');
  74583. }
  74584. },
  74585. enumerable: true,
  74586. configurable: true
  74587. });
  74588. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  74589. /**
  74590. * Fired when the X button on this controller is modified
  74591. */
  74592. get: function () {
  74593. if (this.hand === 'left') {
  74594. return this.onMainButtonStateChangedObservable;
  74595. }
  74596. else {
  74597. throw new Error('No X button on right hand');
  74598. }
  74599. },
  74600. enumerable: true,
  74601. configurable: true
  74602. });
  74603. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  74604. /**
  74605. * Fired when the Y button on this controller is modified
  74606. */
  74607. get: function () {
  74608. if (this.hand === 'left') {
  74609. return this.onSecondaryButtonStateChangedObservable;
  74610. }
  74611. else {
  74612. throw new Error('No Y button on right hand');
  74613. }
  74614. },
  74615. enumerable: true,
  74616. configurable: true
  74617. });
  74618. /**
  74619. * Called once for each button that changed state since the last frame
  74620. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  74621. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  74622. * 2) secondary trigger (same)
  74623. * 3) A (right) X (left), touch, pressed = value
  74624. * 4) B / Y
  74625. * 5) thumb rest
  74626. * @param buttonIdx Which button index changed
  74627. * @param state New state of the button
  74628. * @param changes Which properties on the state changed since last frame
  74629. */
  74630. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  74631. var notifyObject = state; //{ state: state, changes: changes };
  74632. var triggerDirection = this.hand === 'right' ? -1 : 1;
  74633. switch (buttonIdx) {
  74634. case 0:
  74635. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  74636. return;
  74637. case 1: // index trigger
  74638. if (this._defaultModel) {
  74639. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  74640. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  74641. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  74642. }
  74643. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  74644. return;
  74645. case 2: // secondary trigger
  74646. if (this._defaultModel) {
  74647. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  74648. }
  74649. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  74650. return;
  74651. case 3:
  74652. if (this._defaultModel) {
  74653. if (notifyObject.pressed) {
  74654. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  74655. }
  74656. else {
  74657. (this._defaultModel.getChildren()[1]).position.y = 0;
  74658. }
  74659. }
  74660. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  74661. return;
  74662. case 4:
  74663. if (this._defaultModel) {
  74664. if (notifyObject.pressed) {
  74665. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  74666. }
  74667. else {
  74668. (this._defaultModel.getChildren()[2]).position.y = 0;
  74669. }
  74670. }
  74671. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  74672. return;
  74673. case 5:
  74674. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  74675. return;
  74676. }
  74677. };
  74678. /**
  74679. * Base Url for the controller model.
  74680. */
  74681. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  74682. /**
  74683. * File name for the left controller model.
  74684. */
  74685. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  74686. /**
  74687. * File name for the right controller model.
  74688. */
  74689. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  74690. return OculusTouchController;
  74691. }(BABYLON.WebVRController));
  74692. BABYLON.OculusTouchController = OculusTouchController;
  74693. })(BABYLON || (BABYLON = {}));
  74694. //# sourceMappingURL=babylon.oculusTouchController.js.map
  74695. var BABYLON;
  74696. (function (BABYLON) {
  74697. /**
  74698. * Vive Controller
  74699. */
  74700. var ViveController = /** @class */ (function (_super) {
  74701. __extends(ViveController, _super);
  74702. /**
  74703. * Creates a new ViveController from a gamepad
  74704. * @param vrGamepad the gamepad that the controller should be created from
  74705. */
  74706. function ViveController(vrGamepad) {
  74707. var _this = _super.call(this, vrGamepad) || this;
  74708. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  74709. _this._invertLeftStickY = true;
  74710. return _this;
  74711. }
  74712. /**
  74713. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  74714. * @param scene scene in which to add meshes
  74715. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  74716. */
  74717. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  74718. var _this = this;
  74719. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  74720. /*
  74721. Parent Mesh name: ViveWand
  74722. - body
  74723. - r_gripper
  74724. - l_gripper
  74725. - menu_button
  74726. - system_button
  74727. - trackpad
  74728. - trigger
  74729. - LED
  74730. */
  74731. _this._defaultModel = newMeshes[1];
  74732. _this.attachToMesh(_this._defaultModel);
  74733. if (meshLoaded) {
  74734. meshLoaded(_this._defaultModel);
  74735. }
  74736. });
  74737. };
  74738. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  74739. /**
  74740. * Fired when the left button on this controller is modified
  74741. */
  74742. get: function () {
  74743. return this.onMainButtonStateChangedObservable;
  74744. },
  74745. enumerable: true,
  74746. configurable: true
  74747. });
  74748. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  74749. /**
  74750. * Fired when the right button on this controller is modified
  74751. */
  74752. get: function () {
  74753. return this.onMainButtonStateChangedObservable;
  74754. },
  74755. enumerable: true,
  74756. configurable: true
  74757. });
  74758. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  74759. /**
  74760. * Fired when the menu button on this controller is modified
  74761. */
  74762. get: function () {
  74763. return this.onSecondaryButtonStateChangedObservable;
  74764. },
  74765. enumerable: true,
  74766. configurable: true
  74767. });
  74768. /**
  74769. * Called once for each button that changed state since the last frame
  74770. * Vive mapping:
  74771. * 0: touchpad
  74772. * 1: trigger
  74773. * 2: left AND right buttons
  74774. * 3: menu button
  74775. * @param buttonIdx Which button index changed
  74776. * @param state New state of the button
  74777. * @param changes Which properties on the state changed since last frame
  74778. */
  74779. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  74780. var notifyObject = state; //{ state: state, changes: changes };
  74781. switch (buttonIdx) {
  74782. case 0:
  74783. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  74784. return;
  74785. case 1: // index trigger
  74786. if (this._defaultModel) {
  74787. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  74788. }
  74789. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  74790. return;
  74791. case 2: // left AND right button
  74792. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  74793. return;
  74794. case 3:
  74795. if (this._defaultModel) {
  74796. if (notifyObject.pressed) {
  74797. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  74798. }
  74799. else {
  74800. (this._defaultModel.getChildren()[2]).position.y = 0;
  74801. }
  74802. }
  74803. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  74804. return;
  74805. }
  74806. };
  74807. /**
  74808. * Base Url for the controller model.
  74809. */
  74810. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  74811. /**
  74812. * File name for the controller model.
  74813. */
  74814. ViveController.MODEL_FILENAME = 'wand.babylon';
  74815. return ViveController;
  74816. }(BABYLON.WebVRController));
  74817. BABYLON.ViveController = ViveController;
  74818. })(BABYLON || (BABYLON = {}));
  74819. //# sourceMappingURL=babylon.viveController.js.map
  74820. var BABYLON;
  74821. (function (BABYLON) {
  74822. /**
  74823. * Generic Controller
  74824. */
  74825. var GenericController = /** @class */ (function (_super) {
  74826. __extends(GenericController, _super);
  74827. /**
  74828. * Creates a new GenericController from a gamepad
  74829. * @param vrGamepad the gamepad that the controller should be created from
  74830. */
  74831. function GenericController(vrGamepad) {
  74832. return _super.call(this, vrGamepad) || this;
  74833. }
  74834. /**
  74835. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  74836. * @param scene scene in which to add meshes
  74837. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  74838. */
  74839. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  74840. var _this = this;
  74841. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  74842. _this._defaultModel = newMeshes[1];
  74843. _this.attachToMesh(_this._defaultModel);
  74844. if (meshLoaded) {
  74845. meshLoaded(_this._defaultModel);
  74846. }
  74847. });
  74848. };
  74849. /**
  74850. * Called once for each button that changed state since the last frame
  74851. * @param buttonIdx Which button index changed
  74852. * @param state New state of the button
  74853. * @param changes Which properties on the state changed since last frame
  74854. */
  74855. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  74856. console.log("Button id: " + buttonIdx + "state: ");
  74857. console.dir(state);
  74858. };
  74859. /**
  74860. * Base Url for the controller model.
  74861. */
  74862. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  74863. /**
  74864. * File name for the controller model.
  74865. */
  74866. GenericController.MODEL_FILENAME = 'generic.babylon';
  74867. return GenericController;
  74868. }(BABYLON.WebVRController));
  74869. BABYLON.GenericController = GenericController;
  74870. })(BABYLON || (BABYLON = {}));
  74871. //# sourceMappingURL=babylon.genericController.js.map
  74872. var BABYLON;
  74873. (function (BABYLON) {
  74874. /**
  74875. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  74876. */
  74877. var LoadedMeshInfo = /** @class */ (function () {
  74878. function LoadedMeshInfo() {
  74879. /**
  74880. * Map of the button meshes contained in the controller
  74881. */
  74882. this.buttonMeshes = {};
  74883. /**
  74884. * Map of the axis meshes contained in the controller
  74885. */
  74886. this.axisMeshes = {};
  74887. }
  74888. return LoadedMeshInfo;
  74889. }());
  74890. /**
  74891. * Defines the WindowsMotionController object that the state of the windows motion controller
  74892. */
  74893. var WindowsMotionController = /** @class */ (function (_super) {
  74894. __extends(WindowsMotionController, _super);
  74895. /**
  74896. * Creates a new WindowsMotionController from a gamepad
  74897. * @param vrGamepad the gamepad that the controller should be created from
  74898. */
  74899. function WindowsMotionController(vrGamepad) {
  74900. var _this = _super.call(this, vrGamepad) || this;
  74901. _this._mapping = {
  74902. // Semantic button names
  74903. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  74904. // A mapping of the button name to glTF model node name
  74905. // that should be transformed by button value.
  74906. buttonMeshNames: {
  74907. 'trigger': 'SELECT',
  74908. 'menu': 'MENU',
  74909. 'grip': 'GRASP',
  74910. 'thumbstick': 'THUMBSTICK_PRESS',
  74911. 'trackpad': 'TOUCHPAD_PRESS'
  74912. },
  74913. // This mapping is used to translate from the Motion Controller to Babylon semantics
  74914. buttonObservableNames: {
  74915. 'trigger': 'onTriggerStateChangedObservable',
  74916. 'menu': 'onSecondaryButtonStateChangedObservable',
  74917. 'grip': 'onMainButtonStateChangedObservable',
  74918. 'thumbstick': 'onPadStateChangedObservable',
  74919. 'trackpad': 'onTrackpadChangedObservable'
  74920. },
  74921. // A mapping of the axis name to glTF model node name
  74922. // that should be transformed by axis value.
  74923. // This array mirrors the browserGamepad.axes array, such that
  74924. // the mesh corresponding to axis 0 is in this array index 0.
  74925. axisMeshNames: [
  74926. 'THUMBSTICK_X',
  74927. 'THUMBSTICK_Y',
  74928. 'TOUCHPAD_TOUCH_X',
  74929. 'TOUCHPAD_TOUCH_Y'
  74930. ],
  74931. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  74932. };
  74933. /**
  74934. * Fired when the trackpad on this controller is clicked
  74935. */
  74936. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  74937. /**
  74938. * Fired when the trackpad on this controller is modified
  74939. */
  74940. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  74941. /**
  74942. * The current x and y values of this controller's trackpad
  74943. */
  74944. _this.trackpad = { x: 0, y: 0 };
  74945. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  74946. _this._loadedMeshInfo = null;
  74947. return _this;
  74948. }
  74949. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  74950. /**
  74951. * Fired when the trigger on this controller is modified
  74952. */
  74953. get: function () {
  74954. return this.onTriggerStateChangedObservable;
  74955. },
  74956. enumerable: true,
  74957. configurable: true
  74958. });
  74959. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  74960. /**
  74961. * Fired when the menu button on this controller is modified
  74962. */
  74963. get: function () {
  74964. return this.onSecondaryButtonStateChangedObservable;
  74965. },
  74966. enumerable: true,
  74967. configurable: true
  74968. });
  74969. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  74970. /**
  74971. * Fired when the grip button on this controller is modified
  74972. */
  74973. get: function () {
  74974. return this.onMainButtonStateChangedObservable;
  74975. },
  74976. enumerable: true,
  74977. configurable: true
  74978. });
  74979. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  74980. /**
  74981. * Fired when the thumbstick button on this controller is modified
  74982. */
  74983. get: function () {
  74984. return this.onPadStateChangedObservable;
  74985. },
  74986. enumerable: true,
  74987. configurable: true
  74988. });
  74989. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  74990. /**
  74991. * Fired when the touchpad button on this controller is modified
  74992. */
  74993. get: function () {
  74994. return this.onTrackpadChangedObservable;
  74995. },
  74996. enumerable: true,
  74997. configurable: true
  74998. });
  74999. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  75000. /**
  75001. * Fired when the touchpad values on this controller are modified
  75002. */
  75003. get: function () {
  75004. return this.onTrackpadValuesChangedObservable;
  75005. },
  75006. enumerable: true,
  75007. configurable: true
  75008. });
  75009. WindowsMotionController.prototype._updateTrackpad = function () {
  75010. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  75011. this.trackpad.x = this.browserGamepad["axes"][2];
  75012. this.trackpad.y = this.browserGamepad["axes"][3];
  75013. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  75014. }
  75015. };
  75016. /**
  75017. * Called once per frame by the engine.
  75018. */
  75019. WindowsMotionController.prototype.update = function () {
  75020. _super.prototype.update.call(this);
  75021. if (this.browserGamepad.axes) {
  75022. this._updateTrackpad();
  75023. // Only need to animate axes if there is a loaded mesh
  75024. if (this._loadedMeshInfo) {
  75025. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  75026. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  75027. }
  75028. }
  75029. }
  75030. };
  75031. /**
  75032. * Called once for each button that changed state since the last frame
  75033. * @param buttonIdx Which button index changed
  75034. * @param state New state of the button
  75035. * @param changes Which properties on the state changed since last frame
  75036. */
  75037. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  75038. var buttonName = this._mapping.buttons[buttonIdx];
  75039. if (!buttonName) {
  75040. return;
  75041. }
  75042. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  75043. this._updateTrackpad();
  75044. // Only emit events for buttons that we know how to map from index to name
  75045. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  75046. if (observable) {
  75047. observable.notifyObservers(state);
  75048. }
  75049. this._lerpButtonTransform(buttonName, state.value);
  75050. };
  75051. /**
  75052. * Moves the buttons on the controller mesh based on their current state
  75053. * @param buttonName the name of the button to move
  75054. * @param buttonValue the value of the button which determines the buttons new position
  75055. */
  75056. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  75057. // If there is no loaded mesh, there is nothing to transform.
  75058. if (!this._loadedMeshInfo) {
  75059. return;
  75060. }
  75061. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  75062. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  75063. return;
  75064. }
  75065. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  75066. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  75067. };
  75068. /**
  75069. * Moves the axis on the controller mesh based on its current state
  75070. * @param axis the index of the axis
  75071. * @param axisValue the value of the axis which determines the meshes new position
  75072. * @hidden
  75073. */
  75074. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  75075. if (!this._loadedMeshInfo) {
  75076. return;
  75077. }
  75078. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  75079. if (!meshInfo) {
  75080. return;
  75081. }
  75082. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  75083. return;
  75084. }
  75085. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  75086. var lerpValue = axisValue * 0.5 + 0.5;
  75087. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  75088. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  75089. };
  75090. /**
  75091. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  75092. * @param scene scene in which to add meshes
  75093. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  75094. */
  75095. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  75096. var _this = this;
  75097. if (forceDefault === void 0) { forceDefault = false; }
  75098. var path;
  75099. var filename;
  75100. // Checking if GLB loader is present
  75101. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  75102. // Determine the device specific folder based on the ID suffix
  75103. var device = 'default';
  75104. if (this.id && !forceDefault) {
  75105. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  75106. device = ((match && match[0]) || device);
  75107. }
  75108. // Hand
  75109. if (this.hand === 'left') {
  75110. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  75111. }
  75112. else { // Right is the default if no hand is specified
  75113. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  75114. }
  75115. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  75116. }
  75117. else {
  75118. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  75119. path = BABYLON.GenericController.MODEL_BASE_URL;
  75120. filename = BABYLON.GenericController.MODEL_FILENAME;
  75121. }
  75122. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  75123. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  75124. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  75125. if (!_this._loadedMeshInfo) {
  75126. return;
  75127. }
  75128. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  75129. _this.attachToMesh(_this._defaultModel);
  75130. if (meshLoaded) {
  75131. meshLoaded(_this._defaultModel);
  75132. }
  75133. }, null, function (scene, message) {
  75134. BABYLON.Tools.Log(message);
  75135. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  75136. if (!forceDefault) {
  75137. _this.initControllerMesh(scene, meshLoaded, true);
  75138. }
  75139. });
  75140. };
  75141. /**
  75142. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  75143. * can be transformed by button presses and axes values, based on this._mapping.
  75144. *
  75145. * @param scene scene in which the meshes exist
  75146. * @param meshes list of meshes that make up the controller model to process
  75147. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  75148. */
  75149. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  75150. var loadedMeshInfo = null;
  75151. // Create a new mesh to contain the glTF hierarchy
  75152. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  75153. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  75154. var childMesh = null;
  75155. for (var i = 0; i < meshes.length; i++) {
  75156. var mesh = meshes[i];
  75157. if (!mesh.parent) {
  75158. // Exclude controller meshes from picking results
  75159. mesh.isPickable = false;
  75160. // Handle root node, attach to the new parentMesh
  75161. childMesh = mesh;
  75162. break;
  75163. }
  75164. }
  75165. if (childMesh) {
  75166. childMesh.setParent(parentMesh);
  75167. // Create our mesh info. Note that this method will always return non-null.
  75168. loadedMeshInfo = this.createMeshInfo(parentMesh);
  75169. }
  75170. else {
  75171. BABYLON.Tools.Warn('Could not find root node in model file.');
  75172. }
  75173. return loadedMeshInfo;
  75174. };
  75175. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  75176. var loadedMeshInfo = new LoadedMeshInfo();
  75177. var i;
  75178. loadedMeshInfo.rootNode = rootNode;
  75179. // Reset the caches
  75180. loadedMeshInfo.buttonMeshes = {};
  75181. loadedMeshInfo.axisMeshes = {};
  75182. // Button Meshes
  75183. for (i = 0; i < this._mapping.buttons.length; i++) {
  75184. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  75185. if (!buttonMeshName) {
  75186. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  75187. continue;
  75188. }
  75189. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  75190. if (!buttonMesh) {
  75191. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  75192. continue;
  75193. }
  75194. var buttonMeshInfo = {
  75195. index: i,
  75196. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  75197. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  75198. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  75199. };
  75200. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  75201. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  75202. }
  75203. else {
  75204. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  75205. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  75206. '(VALUE: ' + !!buttonMeshInfo.value +
  75207. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  75208. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  75209. ')');
  75210. }
  75211. }
  75212. // Axis Meshes
  75213. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  75214. var axisMeshName = this._mapping.axisMeshNames[i];
  75215. if (!axisMeshName) {
  75216. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  75217. continue;
  75218. }
  75219. var axisMesh = getChildByName(rootNode, axisMeshName);
  75220. if (!axisMesh) {
  75221. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  75222. continue;
  75223. }
  75224. var axisMeshInfo = {
  75225. index: i,
  75226. value: getImmediateChildByName(axisMesh, 'VALUE'),
  75227. min: getImmediateChildByName(axisMesh, 'MIN'),
  75228. max: getImmediateChildByName(axisMesh, 'MAX')
  75229. };
  75230. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  75231. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  75232. }
  75233. else {
  75234. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  75235. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  75236. '(VALUE: ' + !!axisMeshInfo.value +
  75237. ', MIN: ' + !!axisMeshInfo.min +
  75238. ', MAX:' + !!axisMeshInfo.max +
  75239. ')');
  75240. }
  75241. }
  75242. // Pointing Ray
  75243. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  75244. if (!loadedMeshInfo.pointingPoseNode) {
  75245. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  75246. }
  75247. else {
  75248. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  75249. }
  75250. return loadedMeshInfo;
  75251. // Look through all children recursively. This will return null if no mesh exists with the given name.
  75252. function getChildByName(node, name) {
  75253. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  75254. }
  75255. // Look through only immediate children. This will return null if no mesh exists with the given name.
  75256. function getImmediateChildByName(node, name) {
  75257. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  75258. }
  75259. };
  75260. /**
  75261. * Gets the ray of the controller in the direction the controller is pointing
  75262. * @param length the length the resulting ray should be
  75263. * @returns a ray in the direction the controller is pointing
  75264. */
  75265. WindowsMotionController.prototype.getForwardRay = function (length) {
  75266. if (length === void 0) { length = 100; }
  75267. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  75268. return _super.prototype.getForwardRay.call(this, length);
  75269. }
  75270. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  75271. var origin = m.getTranslation();
  75272. var forward = new BABYLON.Vector3(0, 0, -1);
  75273. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  75274. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  75275. return new BABYLON.Ray(origin, direction, length);
  75276. };
  75277. /**
  75278. * Disposes of the controller
  75279. */
  75280. WindowsMotionController.prototype.dispose = function () {
  75281. _super.prototype.dispose.call(this);
  75282. this.onTrackpadChangedObservable.clear();
  75283. };
  75284. /**
  75285. * The base url used to load the left and right controller models
  75286. */
  75287. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  75288. /**
  75289. * The name of the left controller model file
  75290. */
  75291. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  75292. /**
  75293. * The name of the right controller model file
  75294. */
  75295. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  75296. /**
  75297. * The controller name prefix for this controller type
  75298. */
  75299. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  75300. /**
  75301. * The controller id pattern for this controller type
  75302. */
  75303. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  75304. return WindowsMotionController;
  75305. }(BABYLON.WebVRController));
  75306. BABYLON.WindowsMotionController = WindowsMotionController;
  75307. })(BABYLON || (BABYLON = {}));
  75308. //# sourceMappingURL=babylon.windowsMotionController.js.map
  75309. var BABYLON;
  75310. (function (BABYLON) {
  75311. /**
  75312. * Gear VR Controller
  75313. */
  75314. var GearVRController = /** @class */ (function (_super) {
  75315. __extends(GearVRController, _super);
  75316. /**
  75317. * Creates a new GearVRController from a gamepad
  75318. * @param vrGamepad the gamepad that the controller should be created from
  75319. */
  75320. function GearVRController(vrGamepad) {
  75321. var _this = _super.call(this, vrGamepad) || this;
  75322. _this._maxRotationDistFromHeadset = Math.PI / 5;
  75323. _this._draggedRoomRotation = 0;
  75324. _this._tmpVector = new BABYLON.Vector3();
  75325. _this._buttonIndexToObservableNameMap = [
  75326. 'onTrackpadChangedObservable',
  75327. 'onTriggerStateChangedObservable' // Trigger
  75328. ];
  75329. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  75330. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  75331. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  75332. return _this;
  75333. }
  75334. /**
  75335. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  75336. * @param poseData raw pose fromthe device
  75337. */
  75338. GearVRController.prototype.updateFromDevice = function (poseData) {
  75339. _super.prototype.updateFromDevice.call(this, poseData);
  75340. if (BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera) {
  75341. if (BABYLON.Engine.LastCreatedScene.activeCamera.deviceRotationQuaternion) {
  75342. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  75343. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(this._tmpVector);
  75344. // Find the radian distance away that the headset is from the controllers rotation
  75345. var distanceAway = Math.atan2(Math.sin(this._tmpVector.y - this._draggedRoomRotation), Math.cos(this._tmpVector.y - this._draggedRoomRotation));
  75346. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  75347. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  75348. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  75349. this._draggedRoomRotation += rotationAmount;
  75350. // Rotate controller around headset
  75351. var sin = Math.sin(-rotationAmount);
  75352. var cos = Math.cos(-rotationAmount);
  75353. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  75354. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  75355. }
  75356. }
  75357. }
  75358. };
  75359. /**
  75360. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  75361. * @param scene scene in which to add meshes
  75362. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  75363. */
  75364. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  75365. var _this = this;
  75366. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  75367. // Offset the controller so it will rotate around the users wrist
  75368. var mesh = new BABYLON.Mesh("", scene);
  75369. newMeshes[1].parent = mesh;
  75370. newMeshes[1].position.z = -0.15;
  75371. _this._defaultModel = mesh;
  75372. _this.attachToMesh(_this._defaultModel);
  75373. if (meshLoaded) {
  75374. meshLoaded(_this._defaultModel);
  75375. }
  75376. });
  75377. };
  75378. /**
  75379. * Called once for each button that changed state since the last frame
  75380. * @param buttonIdx Which button index changed
  75381. * @param state New state of the button
  75382. * @param changes Which properties on the state changed since last frame
  75383. */
  75384. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  75385. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  75386. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  75387. // Only emit events for buttons that we know how to map from index to observable
  75388. var observable = this[observableName];
  75389. if (observable) {
  75390. observable.notifyObservers(state);
  75391. }
  75392. }
  75393. };
  75394. /**
  75395. * Base Url for the controller model.
  75396. */
  75397. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  75398. /**
  75399. * File name for the controller model.
  75400. */
  75401. GearVRController.MODEL_FILENAME = 'generic.babylon';
  75402. /**
  75403. * Gamepad Id prefix used to identify this controller.
  75404. */
  75405. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  75406. return GearVRController;
  75407. }(BABYLON.WebVRController));
  75408. BABYLON.GearVRController = GearVRController;
  75409. })(BABYLON || (BABYLON = {}));
  75410. //# sourceMappingURL=babylon.gearVRController.js.map
  75411. var BABYLON;
  75412. (function (BABYLON) {
  75413. /**
  75414. * Google Daydream controller
  75415. */
  75416. var DaydreamController = /** @class */ (function (_super) {
  75417. __extends(DaydreamController, _super);
  75418. /**
  75419. * Creates a new DaydreamController from a gamepad
  75420. * @param vrGamepad the gamepad that the controller should be created from
  75421. */
  75422. function DaydreamController(vrGamepad) {
  75423. var _this = _super.call(this, vrGamepad) || this;
  75424. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  75425. return _this;
  75426. }
  75427. /**
  75428. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  75429. * @param scene scene in which to add meshes
  75430. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  75431. */
  75432. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  75433. var _this = this;
  75434. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  75435. _this._defaultModel = newMeshes[1];
  75436. _this.attachToMesh(_this._defaultModel);
  75437. if (meshLoaded) {
  75438. meshLoaded(_this._defaultModel);
  75439. }
  75440. });
  75441. };
  75442. /**
  75443. * Called once for each button that changed state since the last frame
  75444. * @param buttonIdx Which button index changed
  75445. * @param state New state of the button
  75446. * @param changes Which properties on the state changed since last frame
  75447. */
  75448. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  75449. // Daydream controller only has 1 GamepadButton (on the trackpad).
  75450. if (buttonIdx === 0) {
  75451. var observable = this.onTriggerStateChangedObservable;
  75452. if (observable) {
  75453. observable.notifyObservers(state);
  75454. }
  75455. }
  75456. else {
  75457. // If the app or home buttons are ever made available
  75458. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  75459. }
  75460. };
  75461. /**
  75462. * Base Url for the controller model.
  75463. */
  75464. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  75465. /**
  75466. * File name for the controller model.
  75467. */
  75468. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  75469. /**
  75470. * Gamepad Id prefix used to identify Daydream Controller.
  75471. */
  75472. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  75473. return DaydreamController;
  75474. }(BABYLON.WebVRController));
  75475. BABYLON.DaydreamController = DaydreamController;
  75476. })(BABYLON || (BABYLON = {}));
  75477. //# sourceMappingURL=babylon.daydreamController.js.map
  75478. var BABYLON;
  75479. (function (BABYLON) {
  75480. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  75481. get: function () {
  75482. if (!this._gamepadManager) {
  75483. this._gamepadManager = new BABYLON.GamepadManager(this);
  75484. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  75485. if (!component) {
  75486. component = new GamepadSystemSceneComponent(this);
  75487. this._addComponent(component);
  75488. }
  75489. }
  75490. return this._gamepadManager;
  75491. },
  75492. enumerable: true,
  75493. configurable: true
  75494. });
  75495. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  75496. this.add(new BABYLON.FreeCameraGamepadInput());
  75497. return this;
  75498. };
  75499. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  75500. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  75501. return this;
  75502. };
  75503. /**
  75504. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  75505. */
  75506. var GamepadSystemSceneComponent = /** @class */ (function () {
  75507. /**
  75508. * Creates a new instance of the component for the given scene
  75509. * @param scene Defines the scene to register the component in
  75510. */
  75511. function GamepadSystemSceneComponent(scene) {
  75512. /**
  75513. * The component name helpfull to identify the component in the list of scene components.
  75514. */
  75515. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  75516. this.scene = scene;
  75517. }
  75518. /**
  75519. * Registers the component in a given scene
  75520. */
  75521. GamepadSystemSceneComponent.prototype.register = function () {
  75522. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  75523. };
  75524. /**
  75525. * Rebuilds the elements related to this component in case of
  75526. * context lost for instance.
  75527. */
  75528. GamepadSystemSceneComponent.prototype.rebuild = function () {
  75529. // Nothing to do for gamepads
  75530. };
  75531. /**
  75532. * Disposes the component and the associated ressources
  75533. */
  75534. GamepadSystemSceneComponent.prototype.dispose = function () {
  75535. var gamepadManager = this.scene._gamepadManager;
  75536. if (gamepadManager) {
  75537. gamepadManager.dispose();
  75538. this.scene._gamepadManager = null;
  75539. }
  75540. };
  75541. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  75542. var gamepadManager = this.scene._gamepadManager;
  75543. if (gamepadManager && gamepadManager._isMonitoring) {
  75544. gamepadManager._checkGamepadsStatus();
  75545. }
  75546. };
  75547. return GamepadSystemSceneComponent;
  75548. }());
  75549. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  75550. })(BABYLON || (BABYLON = {}));
  75551. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  75552. var BABYLON;
  75553. (function (BABYLON) {
  75554. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  75555. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  75556. });
  75557. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  75558. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  75559. });
  75560. var FollowCamera = /** @class */ (function (_super) {
  75561. __extends(FollowCamera, _super);
  75562. function FollowCamera(name, position, scene, lockedTarget) {
  75563. if (lockedTarget === void 0) { lockedTarget = null; }
  75564. var _this = _super.call(this, name, position, scene) || this;
  75565. _this.radius = 12;
  75566. _this.rotationOffset = 0;
  75567. _this.heightOffset = 4;
  75568. _this.cameraAcceleration = 0.05;
  75569. _this.maxCameraSpeed = 20;
  75570. _this.lockedTarget = lockedTarget;
  75571. return _this;
  75572. }
  75573. FollowCamera.prototype.getRadians = function (degrees) {
  75574. return degrees * Math.PI / 180;
  75575. };
  75576. FollowCamera.prototype.follow = function (cameraTarget) {
  75577. if (!cameraTarget)
  75578. return;
  75579. var yRotation;
  75580. if (cameraTarget.rotationQuaternion) {
  75581. var rotMatrix = new BABYLON.Matrix();
  75582. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  75583. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  75584. }
  75585. else {
  75586. yRotation = cameraTarget.rotation.y;
  75587. }
  75588. var radians = this.getRadians(this.rotationOffset) + yRotation;
  75589. var targetPosition = cameraTarget.getAbsolutePosition();
  75590. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  75591. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  75592. var dx = targetX - this.position.x;
  75593. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  75594. var dz = (targetZ) - this.position.z;
  75595. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  75596. var vy = dy * this.cameraAcceleration;
  75597. var vz = dz * this.cameraAcceleration * 2;
  75598. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  75599. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  75600. }
  75601. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  75602. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  75603. }
  75604. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  75605. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  75606. }
  75607. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  75608. this.setTarget(targetPosition);
  75609. };
  75610. /** @hidden */
  75611. FollowCamera.prototype._checkInputs = function () {
  75612. _super.prototype._checkInputs.call(this);
  75613. if (this.lockedTarget) {
  75614. this.follow(this.lockedTarget);
  75615. }
  75616. };
  75617. FollowCamera.prototype.getClassName = function () {
  75618. return "FollowCamera";
  75619. };
  75620. __decorate([
  75621. BABYLON.serialize()
  75622. ], FollowCamera.prototype, "radius", void 0);
  75623. __decorate([
  75624. BABYLON.serialize()
  75625. ], FollowCamera.prototype, "rotationOffset", void 0);
  75626. __decorate([
  75627. BABYLON.serialize()
  75628. ], FollowCamera.prototype, "heightOffset", void 0);
  75629. __decorate([
  75630. BABYLON.serialize()
  75631. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  75632. __decorate([
  75633. BABYLON.serialize()
  75634. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  75635. __decorate([
  75636. BABYLON.serializeAsMeshReference("lockedTargetId")
  75637. ], FollowCamera.prototype, "lockedTarget", void 0);
  75638. return FollowCamera;
  75639. }(BABYLON.TargetCamera));
  75640. BABYLON.FollowCamera = FollowCamera;
  75641. var ArcFollowCamera = /** @class */ (function (_super) {
  75642. __extends(ArcFollowCamera, _super);
  75643. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  75644. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  75645. _this.alpha = alpha;
  75646. _this.beta = beta;
  75647. _this.radius = radius;
  75648. _this.target = target;
  75649. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  75650. _this.follow();
  75651. return _this;
  75652. }
  75653. ArcFollowCamera.prototype.follow = function () {
  75654. if (!this.target) {
  75655. return;
  75656. }
  75657. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  75658. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  75659. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  75660. var targetPosition = this.target.getAbsolutePosition();
  75661. this.position = targetPosition.add(this._cartesianCoordinates);
  75662. this.setTarget(targetPosition);
  75663. };
  75664. /** @hidden */
  75665. ArcFollowCamera.prototype._checkInputs = function () {
  75666. _super.prototype._checkInputs.call(this);
  75667. this.follow();
  75668. };
  75669. ArcFollowCamera.prototype.getClassName = function () {
  75670. return "ArcFollowCamera";
  75671. };
  75672. return ArcFollowCamera;
  75673. }(BABYLON.TargetCamera));
  75674. BABYLON.ArcFollowCamera = ArcFollowCamera;
  75675. })(BABYLON || (BABYLON = {}));
  75676. //# sourceMappingURL=babylon.followCamera.js.map
  75677. var BABYLON;
  75678. (function (BABYLON) {
  75679. // We're mainly based on the logic defined into the FreeCamera code
  75680. var UniversalCamera = /** @class */ (function (_super) {
  75681. __extends(UniversalCamera, _super);
  75682. //-- end properties for backward compatibility for inputs
  75683. function UniversalCamera(name, position, scene) {
  75684. var _this = _super.call(this, name, position, scene) || this;
  75685. _this.inputs.addGamepad();
  75686. return _this;
  75687. }
  75688. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  75689. //-- Begin properties for backward compatibility for inputs
  75690. get: function () {
  75691. var gamepad = this.inputs.attached["gamepad"];
  75692. if (gamepad)
  75693. return gamepad.gamepadAngularSensibility;
  75694. return 0;
  75695. },
  75696. set: function (value) {
  75697. var gamepad = this.inputs.attached["gamepad"];
  75698. if (gamepad)
  75699. gamepad.gamepadAngularSensibility = value;
  75700. },
  75701. enumerable: true,
  75702. configurable: true
  75703. });
  75704. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  75705. get: function () {
  75706. var gamepad = this.inputs.attached["gamepad"];
  75707. if (gamepad)
  75708. return gamepad.gamepadMoveSensibility;
  75709. return 0;
  75710. },
  75711. set: function (value) {
  75712. var gamepad = this.inputs.attached["gamepad"];
  75713. if (gamepad)
  75714. gamepad.gamepadMoveSensibility = value;
  75715. },
  75716. enumerable: true,
  75717. configurable: true
  75718. });
  75719. UniversalCamera.prototype.getClassName = function () {
  75720. return "UniversalCamera";
  75721. };
  75722. return UniversalCamera;
  75723. }(BABYLON.TouchCamera));
  75724. BABYLON.UniversalCamera = UniversalCamera;
  75725. })(BABYLON || (BABYLON = {}));
  75726. //# sourceMappingURL=babylon.universalCamera.js.map
  75727. var BABYLON;
  75728. (function (BABYLON) {
  75729. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  75730. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  75731. });
  75732. // We're mainly based on the logic defined into the FreeCamera code
  75733. var GamepadCamera = /** @class */ (function (_super) {
  75734. __extends(GamepadCamera, _super);
  75735. //-- end properties for backward compatibility for inputs
  75736. function GamepadCamera(name, position, scene) {
  75737. return _super.call(this, name, position, scene) || this;
  75738. }
  75739. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  75740. //-- Begin properties for backward compatibility for inputs
  75741. get: function () {
  75742. var gamepad = this.inputs.attached["gamepad"];
  75743. if (gamepad)
  75744. return gamepad.gamepadAngularSensibility;
  75745. return 0;
  75746. },
  75747. set: function (value) {
  75748. var gamepad = this.inputs.attached["gamepad"];
  75749. if (gamepad)
  75750. gamepad.gamepadAngularSensibility = value;
  75751. },
  75752. enumerable: true,
  75753. configurable: true
  75754. });
  75755. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  75756. get: function () {
  75757. var gamepad = this.inputs.attached["gamepad"];
  75758. if (gamepad)
  75759. return gamepad.gamepadMoveSensibility;
  75760. return 0;
  75761. },
  75762. set: function (value) {
  75763. var gamepad = this.inputs.attached["gamepad"];
  75764. if (gamepad)
  75765. gamepad.gamepadMoveSensibility = value;
  75766. },
  75767. enumerable: true,
  75768. configurable: true
  75769. });
  75770. GamepadCamera.prototype.getClassName = function () {
  75771. return "GamepadCamera";
  75772. };
  75773. return GamepadCamera;
  75774. }(BABYLON.UniversalCamera));
  75775. BABYLON.GamepadCamera = GamepadCamera;
  75776. })(BABYLON || (BABYLON = {}));
  75777. //# sourceMappingURL=babylon.gamepadCamera.js.map
  75778. var BABYLON;
  75779. (function (BABYLON) {
  75780. var PostProcessRenderPipelineManager = /** @class */ (function () {
  75781. function PostProcessRenderPipelineManager() {
  75782. this._renderPipelines = {};
  75783. }
  75784. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  75785. this._renderPipelines[renderPipeline._name] = renderPipeline;
  75786. };
  75787. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  75788. if (unique === void 0) { unique = false; }
  75789. var renderPipeline = this._renderPipelines[renderPipelineName];
  75790. if (!renderPipeline) {
  75791. return;
  75792. }
  75793. renderPipeline._attachCameras(cameras, unique);
  75794. };
  75795. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  75796. var renderPipeline = this._renderPipelines[renderPipelineName];
  75797. if (!renderPipeline) {
  75798. return;
  75799. }
  75800. renderPipeline._detachCameras(cameras);
  75801. };
  75802. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  75803. var renderPipeline = this._renderPipelines[renderPipelineName];
  75804. if (!renderPipeline) {
  75805. return;
  75806. }
  75807. renderPipeline._enableEffect(renderEffectName, cameras);
  75808. };
  75809. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  75810. var renderPipeline = this._renderPipelines[renderPipelineName];
  75811. if (!renderPipeline) {
  75812. return;
  75813. }
  75814. renderPipeline._disableEffect(renderEffectName, cameras);
  75815. };
  75816. PostProcessRenderPipelineManager.prototype.update = function () {
  75817. for (var renderPipelineName in this._renderPipelines) {
  75818. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  75819. var pipeline = this._renderPipelines[renderPipelineName];
  75820. if (!pipeline.isSupported) {
  75821. pipeline.dispose();
  75822. delete this._renderPipelines[renderPipelineName];
  75823. }
  75824. else {
  75825. pipeline._update();
  75826. }
  75827. }
  75828. }
  75829. };
  75830. /** @hidden */
  75831. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  75832. for (var renderPipelineName in this._renderPipelines) {
  75833. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  75834. var pipeline = this._renderPipelines[renderPipelineName];
  75835. pipeline._rebuild();
  75836. }
  75837. }
  75838. };
  75839. PostProcessRenderPipelineManager.prototype.dispose = function () {
  75840. for (var renderPipelineName in this._renderPipelines) {
  75841. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  75842. var pipeline = this._renderPipelines[renderPipelineName];
  75843. pipeline.dispose();
  75844. }
  75845. }
  75846. };
  75847. return PostProcessRenderPipelineManager;
  75848. }());
  75849. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  75850. })(BABYLON || (BABYLON = {}));
  75851. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  75852. var BABYLON;
  75853. (function (BABYLON) {
  75854. /**
  75855. * This represents a set of one or more post processes in Babylon.
  75856. * A post process can be used to apply a shader to a texture after it is rendered.
  75857. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  75858. */
  75859. var PostProcessRenderEffect = /** @class */ (function () {
  75860. /**
  75861. * Instantiates a post process render effect.
  75862. * A post process can be used to apply a shader to a texture after it is rendered.
  75863. * @param engine The engine the effect is tied to
  75864. * @param name The name of the effect
  75865. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  75866. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  75867. */
  75868. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  75869. this._name = name;
  75870. this._singleInstance = singleInstance || true;
  75871. this._getPostProcesses = getPostProcesses;
  75872. this._cameras = {};
  75873. this._indicesForCamera = {};
  75874. this._postProcesses = {};
  75875. }
  75876. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  75877. /**
  75878. * Checks if all the post processes in the effect are supported.
  75879. */
  75880. get: function () {
  75881. for (var index in this._postProcesses) {
  75882. if (this._postProcesses.hasOwnProperty(index)) {
  75883. var pps = this._postProcesses[index];
  75884. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  75885. if (!pps[ppIndex].isSupported) {
  75886. return false;
  75887. }
  75888. }
  75889. }
  75890. }
  75891. return true;
  75892. },
  75893. enumerable: true,
  75894. configurable: true
  75895. });
  75896. /**
  75897. * Updates the current state of the effect
  75898. * @hidden
  75899. */
  75900. PostProcessRenderEffect.prototype._update = function () {
  75901. };
  75902. /**
  75903. * Attaches the effect on cameras
  75904. * @param cameras The camera to attach to.
  75905. * @hidden
  75906. */
  75907. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  75908. var _this = this;
  75909. var cameraKey;
  75910. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  75911. if (!cams) {
  75912. return;
  75913. }
  75914. for (var i = 0; i < cams.length; i++) {
  75915. var camera = cams[i];
  75916. var cameraName = camera.name;
  75917. if (this._singleInstance) {
  75918. cameraKey = 0;
  75919. }
  75920. else {
  75921. cameraKey = cameraName;
  75922. }
  75923. if (!this._postProcesses[cameraKey]) {
  75924. var postProcess = this._getPostProcesses();
  75925. if (postProcess) {
  75926. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  75927. }
  75928. }
  75929. if (!this._indicesForCamera[cameraName]) {
  75930. this._indicesForCamera[cameraName] = [];
  75931. }
  75932. this._postProcesses[cameraKey].forEach(function (postProcess) {
  75933. var index = camera.attachPostProcess(postProcess);
  75934. _this._indicesForCamera[cameraName].push(index);
  75935. });
  75936. if (!this._cameras[cameraName]) {
  75937. this._cameras[cameraName] = camera;
  75938. }
  75939. }
  75940. };
  75941. /**
  75942. * Detatches the effect on cameras
  75943. * @param cameras The camera to detatch from.
  75944. * @hidden
  75945. */
  75946. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  75947. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  75948. if (!cams) {
  75949. return;
  75950. }
  75951. for (var i = 0; i < cams.length; i++) {
  75952. var camera = cams[i];
  75953. var cameraName = camera.name;
  75954. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  75955. camera.detachPostProcess(postProcess);
  75956. });
  75957. if (this._cameras[cameraName]) {
  75958. //this._indicesForCamera.splice(index, 1);
  75959. this._cameras[cameraName] = null;
  75960. }
  75961. }
  75962. };
  75963. /**
  75964. * Enables the effect on given cameras
  75965. * @param cameras The camera to enable.
  75966. * @hidden
  75967. */
  75968. PostProcessRenderEffect.prototype._enable = function (cameras) {
  75969. var _this = this;
  75970. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  75971. if (!cams) {
  75972. return;
  75973. }
  75974. for (var i = 0; i < cams.length; i++) {
  75975. var camera = cams[i];
  75976. var cameraName = camera.name;
  75977. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  75978. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  75979. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  75980. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  75981. });
  75982. }
  75983. }
  75984. }
  75985. };
  75986. /**
  75987. * Disables the effect on the given cameras
  75988. * @param cameras The camera to disable.
  75989. * @hidden
  75990. */
  75991. PostProcessRenderEffect.prototype._disable = function (cameras) {
  75992. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  75993. if (!cams) {
  75994. return;
  75995. }
  75996. for (var i = 0; i < cams.length; i++) {
  75997. var camera = cams[i];
  75998. var cameraName = camera.name;
  75999. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  76000. camera.detachPostProcess(postProcess);
  76001. });
  76002. }
  76003. };
  76004. /**
  76005. * Gets a list of the post processes contained in the effect.
  76006. * @param camera The camera to get the post processes on.
  76007. * @returns The list of the post processes in the effect.
  76008. */
  76009. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  76010. if (this._singleInstance) {
  76011. return this._postProcesses[0];
  76012. }
  76013. else {
  76014. if (!camera) {
  76015. return null;
  76016. }
  76017. return this._postProcesses[camera.name];
  76018. }
  76019. };
  76020. return PostProcessRenderEffect;
  76021. }());
  76022. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  76023. })(BABYLON || (BABYLON = {}));
  76024. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  76025. var BABYLON;
  76026. (function (BABYLON) {
  76027. var PostProcessRenderPipeline = /** @class */ (function () {
  76028. function PostProcessRenderPipeline(engine, name) {
  76029. this.engine = engine;
  76030. this._name = name;
  76031. this._renderEffects = {};
  76032. this._renderEffectsForIsolatedPass = new Array();
  76033. this._cameras = [];
  76034. }
  76035. PostProcessRenderPipeline.prototype.getClassName = function () {
  76036. return "PostProcessRenderPipeline";
  76037. };
  76038. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  76039. get: function () {
  76040. for (var renderEffectName in this._renderEffects) {
  76041. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  76042. if (!this._renderEffects[renderEffectName].isSupported) {
  76043. return false;
  76044. }
  76045. }
  76046. }
  76047. return true;
  76048. },
  76049. enumerable: true,
  76050. configurable: true
  76051. });
  76052. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  76053. this._renderEffects[renderEffect._name] = renderEffect;
  76054. };
  76055. // private
  76056. /** @hidden */
  76057. PostProcessRenderPipeline.prototype._rebuild = function () {
  76058. };
  76059. /** @hidden */
  76060. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  76061. var renderEffects = this._renderEffects[renderEffectName];
  76062. if (!renderEffects) {
  76063. return;
  76064. }
  76065. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  76066. };
  76067. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  76068. var renderEffects = this._renderEffects[renderEffectName];
  76069. if (!renderEffects) {
  76070. return;
  76071. }
  76072. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  76073. };
  76074. /** @hidden */
  76075. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  76076. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  76077. if (!cams) {
  76078. return;
  76079. }
  76080. var indicesToDelete = [];
  76081. var i;
  76082. for (i = 0; i < cams.length; i++) {
  76083. var camera = cams[i];
  76084. var cameraName = camera.name;
  76085. if (this._cameras.indexOf(camera) === -1) {
  76086. this._cameras[cameraName] = camera;
  76087. }
  76088. else if (unique) {
  76089. indicesToDelete.push(i);
  76090. }
  76091. }
  76092. for (i = 0; i < indicesToDelete.length; i++) {
  76093. cameras.splice(indicesToDelete[i], 1);
  76094. }
  76095. for (var renderEffectName in this._renderEffects) {
  76096. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  76097. this._renderEffects[renderEffectName]._attachCameras(cams);
  76098. }
  76099. }
  76100. };
  76101. /** @hidden */
  76102. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  76103. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  76104. if (!cams) {
  76105. return;
  76106. }
  76107. for (var renderEffectName in this._renderEffects) {
  76108. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  76109. this._renderEffects[renderEffectName]._detachCameras(cams);
  76110. }
  76111. }
  76112. for (var i = 0; i < cams.length; i++) {
  76113. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  76114. }
  76115. };
  76116. /** @hidden */
  76117. PostProcessRenderPipeline.prototype._update = function () {
  76118. for (var renderEffectName in this._renderEffects) {
  76119. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  76120. this._renderEffects[renderEffectName]._update();
  76121. }
  76122. }
  76123. for (var i = 0; i < this._cameras.length; i++) {
  76124. var cameraName = this._cameras[i].name;
  76125. if (this._renderEffectsForIsolatedPass[cameraName]) {
  76126. this._renderEffectsForIsolatedPass[cameraName]._update();
  76127. }
  76128. }
  76129. };
  76130. /** @hidden */
  76131. PostProcessRenderPipeline.prototype._reset = function () {
  76132. this._renderEffects = {};
  76133. this._renderEffectsForIsolatedPass = new Array();
  76134. };
  76135. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  76136. // 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)
  76137. var effectKeys = Object.keys(this._renderEffects);
  76138. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  76139. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  76140. if (postProcesses) {
  76141. postProcesses[0].samples = sampleCount;
  76142. return true;
  76143. }
  76144. }
  76145. return false;
  76146. };
  76147. PostProcessRenderPipeline.prototype.dispose = function () {
  76148. // Must be implemented by children
  76149. };
  76150. __decorate([
  76151. BABYLON.serialize()
  76152. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  76153. return PostProcessRenderPipeline;
  76154. }());
  76155. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  76156. })(BABYLON || (BABYLON = {}));
  76157. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  76158. var BABYLON;
  76159. (function (BABYLON) {
  76160. /**
  76161. * This represents a depth renderer in Babylon.
  76162. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  76163. */
  76164. var DepthRenderer = /** @class */ (function () {
  76165. /**
  76166. * Instantiates a depth renderer
  76167. * @param scene The scene the renderer belongs to
  76168. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  76169. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  76170. */
  76171. function DepthRenderer(scene, type, camera) {
  76172. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  76173. if (camera === void 0) { camera = null; }
  76174. var _this = this;
  76175. this._scene = scene;
  76176. this._camera = camera;
  76177. var engine = scene.getEngine();
  76178. // Render target
  76179. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  76180. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76181. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76182. this._depthMap.refreshRate = 1;
  76183. this._depthMap.renderParticles = false;
  76184. this._depthMap.renderList = null;
  76185. // Camera to get depth map from to support multiple concurrent cameras
  76186. this._depthMap.activeCamera = this._camera;
  76187. this._depthMap.ignoreCameraViewport = true;
  76188. this._depthMap.useCameraPostProcesses = false;
  76189. // set default depth value to 1.0 (far away)
  76190. this._depthMap.onClearObservable.add(function (engine) {
  76191. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  76192. });
  76193. // Custom render function
  76194. var renderSubMesh = function (subMesh) {
  76195. var mesh = subMesh.getRenderingMesh();
  76196. var scene = _this._scene;
  76197. var engine = scene.getEngine();
  76198. var material = subMesh.getMaterial();
  76199. if (!material) {
  76200. return;
  76201. }
  76202. // Culling and reverse (right handed system)
  76203. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76204. // Managing instances
  76205. var batch = mesh._getInstancesRenderList(subMesh._id);
  76206. if (batch.mustReturn) {
  76207. return;
  76208. }
  76209. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76210. var camera = _this._camera || scene.activeCamera;
  76211. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  76212. engine.enableEffect(_this._effect);
  76213. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76214. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76215. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  76216. // Alpha test
  76217. if (material && material.needAlphaTesting()) {
  76218. var alphaTexture = material.getAlphaTestTexture();
  76219. if (alphaTexture) {
  76220. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76221. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76222. }
  76223. }
  76224. // Bones
  76225. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76226. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76227. }
  76228. // Draw
  76229. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76230. }
  76231. };
  76232. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76233. var index;
  76234. if (depthOnlySubMeshes.length) {
  76235. engine.setColorWrite(false);
  76236. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76237. renderSubMesh(depthOnlySubMeshes.data[index]);
  76238. }
  76239. engine.setColorWrite(true);
  76240. }
  76241. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76242. renderSubMesh(opaqueSubMeshes.data[index]);
  76243. }
  76244. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76245. renderSubMesh(alphaTestSubMeshes.data[index]);
  76246. }
  76247. };
  76248. }
  76249. /**
  76250. * Creates the depth rendering effect and checks if the effect is ready.
  76251. * @param subMesh The submesh to be used to render the depth map of
  76252. * @param useInstances If multiple world instances should be used
  76253. * @returns if the depth renderer is ready to render the depth map
  76254. */
  76255. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  76256. var material = subMesh.getMaterial();
  76257. if (material.disableDepthWrite) {
  76258. return false;
  76259. }
  76260. var defines = [];
  76261. var attribs = [BABYLON.VertexBuffer.PositionKind];
  76262. var mesh = subMesh.getMesh();
  76263. // Alpha test
  76264. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  76265. defines.push("#define ALPHATEST");
  76266. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76267. attribs.push(BABYLON.VertexBuffer.UVKind);
  76268. defines.push("#define UV1");
  76269. }
  76270. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76271. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76272. defines.push("#define UV2");
  76273. }
  76274. }
  76275. // Bones
  76276. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76277. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76278. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76279. if (mesh.numBoneInfluencers > 4) {
  76280. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76281. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76282. }
  76283. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76284. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76285. }
  76286. else {
  76287. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76288. }
  76289. // Instances
  76290. if (useInstances) {
  76291. defines.push("#define INSTANCES");
  76292. attribs.push("world0");
  76293. attribs.push("world1");
  76294. attribs.push("world2");
  76295. attribs.push("world3");
  76296. }
  76297. // Get correct effect
  76298. var join = defines.join("\n");
  76299. if (this._cachedDefines !== join) {
  76300. this._cachedDefines = join;
  76301. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  76302. }
  76303. return this._effect.isReady();
  76304. };
  76305. /**
  76306. * Gets the texture which the depth map will be written to.
  76307. * @returns The depth map texture
  76308. */
  76309. DepthRenderer.prototype.getDepthMap = function () {
  76310. return this._depthMap;
  76311. };
  76312. /**
  76313. * Disposes of the depth renderer.
  76314. */
  76315. DepthRenderer.prototype.dispose = function () {
  76316. this._depthMap.dispose();
  76317. };
  76318. return DepthRenderer;
  76319. }());
  76320. BABYLON.DepthRenderer = DepthRenderer;
  76321. })(BABYLON || (BABYLON = {}));
  76322. //# sourceMappingURL=babylon.depthRenderer.js.map
  76323. var BABYLON;
  76324. (function (BABYLON) {
  76325. var SSAORenderingPipeline = /** @class */ (function (_super) {
  76326. __extends(SSAORenderingPipeline, _super);
  76327. /**
  76328. * @constructor
  76329. * @param {string} name - The rendering pipeline name
  76330. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  76331. * @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 }
  76332. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  76333. */
  76334. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  76335. var _this = _super.call(this, scene.getEngine(), name) || this;
  76336. // Members
  76337. /**
  76338. * The PassPostProcess id in the pipeline that contains the original scene color
  76339. */
  76340. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  76341. /**
  76342. * The SSAO PostProcess id in the pipeline
  76343. */
  76344. _this.SSAORenderEffect = "SSAORenderEffect";
  76345. /**
  76346. * The horizontal blur PostProcess id in the pipeline
  76347. */
  76348. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  76349. /**
  76350. * The vertical blur PostProcess id in the pipeline
  76351. */
  76352. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  76353. /**
  76354. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  76355. */
  76356. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  76357. /**
  76358. * The output strength of the SSAO post-process. Default value is 1.0.
  76359. */
  76360. _this.totalStrength = 1.0;
  76361. /**
  76362. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  76363. */
  76364. _this.radius = 0.0001;
  76365. /**
  76366. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  76367. * Must not be equal to fallOff and superior to fallOff.
  76368. * Default value is 0.975
  76369. */
  76370. _this.area = 0.0075;
  76371. /**
  76372. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  76373. * Must not be equal to area and inferior to area.
  76374. * Default value is 0.0
  76375. */
  76376. _this.fallOff = 0.000001;
  76377. /**
  76378. * The base color of the SSAO post-process
  76379. * The final result is "base + ssao" between [0, 1]
  76380. */
  76381. _this.base = 0.5;
  76382. _this._firstUpdate = true;
  76383. _this._scene = scene;
  76384. // Set up assets
  76385. _this._createRandomTexture();
  76386. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  76387. var ssaoRatio = ratio.ssaoRatio || ratio;
  76388. var combineRatio = ratio.combineRatio || ratio;
  76389. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  76390. _this._createSSAOPostProcess(ssaoRatio);
  76391. _this._createBlurPostProcess(ssaoRatio);
  76392. _this._createSSAOCombinePostProcess(combineRatio);
  76393. // Set up pipeline
  76394. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  76395. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  76396. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  76397. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  76398. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  76399. // Finish
  76400. scene.postProcessRenderPipelineManager.addPipeline(_this);
  76401. if (cameras)
  76402. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  76403. return _this;
  76404. }
  76405. // Public Methods
  76406. /**
  76407. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  76408. */
  76409. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  76410. if (disableDepthRender === void 0) { disableDepthRender = false; }
  76411. for (var i = 0; i < this._scene.cameras.length; i++) {
  76412. var camera = this._scene.cameras[i];
  76413. this._originalColorPostProcess.dispose(camera);
  76414. this._ssaoPostProcess.dispose(camera);
  76415. this._blurHPostProcess.dispose(camera);
  76416. this._blurVPostProcess.dispose(camera);
  76417. this._ssaoCombinePostProcess.dispose(camera);
  76418. }
  76419. this._randomTexture.dispose();
  76420. if (disableDepthRender)
  76421. this._scene.disableDepthRenderer();
  76422. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  76423. _super.prototype.dispose.call(this);
  76424. };
  76425. // Private Methods
  76426. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  76427. var _this = this;
  76428. var size = 16;
  76429. 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);
  76430. 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);
  76431. this._blurHPostProcess.onActivateObservable.add(function () {
  76432. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  76433. _this._blurHPostProcess.kernel = size * dw;
  76434. });
  76435. this._blurVPostProcess.onActivateObservable.add(function () {
  76436. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  76437. _this._blurVPostProcess.kernel = size * dw;
  76438. });
  76439. };
  76440. /** @hidden */
  76441. SSAORenderingPipeline.prototype._rebuild = function () {
  76442. this._firstUpdate = true;
  76443. _super.prototype._rebuild.call(this);
  76444. };
  76445. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  76446. var _this = this;
  76447. var numSamples = 16;
  76448. var sampleSphere = [
  76449. 0.5381, 0.1856, -0.4319,
  76450. 0.1379, 0.2486, 0.4430,
  76451. 0.3371, 0.5679, -0.0057,
  76452. -0.6999, -0.0451, -0.0019,
  76453. 0.0689, -0.1598, -0.8547,
  76454. 0.0560, 0.0069, -0.1843,
  76455. -0.0146, 0.1402, 0.0762,
  76456. 0.0100, -0.1924, -0.0344,
  76457. -0.3577, -0.5301, -0.4358,
  76458. -0.3169, 0.1063, 0.0158,
  76459. 0.0103, -0.5869, 0.0046,
  76460. -0.0897, -0.4940, 0.3287,
  76461. 0.7119, -0.0154, -0.0918,
  76462. -0.0533, 0.0596, -0.5411,
  76463. 0.0352, -0.0631, 0.5460,
  76464. -0.4776, 0.2847, -0.0271
  76465. ];
  76466. var samplesFactor = 1.0 / numSamples;
  76467. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  76468. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  76469. "area", "fallOff", "base", "range", "viewport"
  76470. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  76471. this._ssaoPostProcess.onApply = function (effect) {
  76472. if (_this._firstUpdate) {
  76473. effect.setArray3("sampleSphere", sampleSphere);
  76474. effect.setFloat("samplesFactor", samplesFactor);
  76475. effect.setFloat("randTextureTiles", 4.0);
  76476. }
  76477. effect.setFloat("totalStrength", _this.totalStrength);
  76478. effect.setFloat("radius", _this.radius);
  76479. effect.setFloat("area", _this.area);
  76480. effect.setFloat("fallOff", _this.fallOff);
  76481. effect.setFloat("base", _this.base);
  76482. effect.setTexture("textureSampler", _this._depthTexture);
  76483. effect.setTexture("randomSampler", _this._randomTexture);
  76484. };
  76485. };
  76486. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  76487. var _this = this;
  76488. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  76489. this._ssaoCombinePostProcess.onApply = function (effect) {
  76490. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  76491. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  76492. };
  76493. };
  76494. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  76495. var size = 512;
  76496. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  76497. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  76498. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  76499. var context = this._randomTexture.getContext();
  76500. var rand = function (min, max) {
  76501. return Math.random() * (max - min) + min;
  76502. };
  76503. var randVector = BABYLON.Vector3.Zero();
  76504. for (var x = 0; x < size; x++) {
  76505. for (var y = 0; y < size; y++) {
  76506. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  76507. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  76508. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  76509. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  76510. context.fillRect(x, y, 1, 1);
  76511. }
  76512. }
  76513. this._randomTexture.update(false);
  76514. };
  76515. __decorate([
  76516. BABYLON.serialize()
  76517. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  76518. __decorate([
  76519. BABYLON.serialize()
  76520. ], SSAORenderingPipeline.prototype, "radius", void 0);
  76521. __decorate([
  76522. BABYLON.serialize()
  76523. ], SSAORenderingPipeline.prototype, "area", void 0);
  76524. __decorate([
  76525. BABYLON.serialize()
  76526. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  76527. __decorate([
  76528. BABYLON.serialize()
  76529. ], SSAORenderingPipeline.prototype, "base", void 0);
  76530. return SSAORenderingPipeline;
  76531. }(BABYLON.PostProcessRenderPipeline));
  76532. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  76533. })(BABYLON || (BABYLON = {}));
  76534. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  76535. var BABYLON;
  76536. (function (BABYLON) {
  76537. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  76538. __extends(SSAO2RenderingPipeline, _super);
  76539. /**
  76540. * @constructor
  76541. * @param {string} name - The rendering pipeline name
  76542. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  76543. * @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 }
  76544. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  76545. */
  76546. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  76547. var _this = _super.call(this, scene.getEngine(), name) || this;
  76548. // Members
  76549. /**
  76550. * The PassPostProcess id in the pipeline that contains the original scene color
  76551. */
  76552. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  76553. /**
  76554. * The SSAO PostProcess id in the pipeline
  76555. */
  76556. _this.SSAORenderEffect = "SSAORenderEffect";
  76557. /**
  76558. * The horizontal blur PostProcess id in the pipeline
  76559. */
  76560. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  76561. /**
  76562. * The vertical blur PostProcess id in the pipeline
  76563. */
  76564. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  76565. /**
  76566. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  76567. */
  76568. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  76569. /**
  76570. * The output strength of the SSAO post-process. Default value is 1.0.
  76571. */
  76572. _this.totalStrength = 1.0;
  76573. /**
  76574. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  76575. */
  76576. _this.maxZ = 100.0;
  76577. /**
  76578. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  76579. */
  76580. _this.minZAspect = 0.2;
  76581. /**
  76582. * Number of samples used for the SSAO calculations. Default value is 8
  76583. */
  76584. _this._samples = 8;
  76585. /**
  76586. * Are we using bilateral blur ?
  76587. */
  76588. _this._expensiveBlur = true;
  76589. /**
  76590. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  76591. */
  76592. _this.radius = 2.0;
  76593. /**
  76594. * The base color of the SSAO post-process
  76595. * The final result is "base + ssao" between [0, 1]
  76596. */
  76597. _this.base = 0.1;
  76598. _this._firstUpdate = true;
  76599. _this._scene = scene;
  76600. _this._ratio = ratio;
  76601. if (!_this.isSupported) {
  76602. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  76603. return _this;
  76604. }
  76605. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  76606. var blurRatio = _this._ratio.blurRatio || ratio;
  76607. // Set up assets
  76608. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  76609. _this._createRandomTexture();
  76610. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  76611. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  76612. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  76613. _this._createSSAOPostProcess(1.0);
  76614. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  76615. _this._createSSAOCombinePostProcess(blurRatio);
  76616. // Set up pipeline
  76617. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  76618. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  76619. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  76620. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  76621. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  76622. // Finish
  76623. scene.postProcessRenderPipelineManager.addPipeline(_this);
  76624. if (cameras)
  76625. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  76626. return _this;
  76627. }
  76628. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  76629. get: function () {
  76630. return this._samples;
  76631. },
  76632. set: function (n) {
  76633. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  76634. this._samples = n;
  76635. this._sampleSphere = this._generateHemisphere();
  76636. this._firstUpdate = true;
  76637. },
  76638. enumerable: true,
  76639. configurable: true
  76640. });
  76641. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  76642. get: function () {
  76643. return this._expensiveBlur;
  76644. },
  76645. set: function (b) {
  76646. 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"]);
  76647. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  76648. this._expensiveBlur = b;
  76649. this._firstUpdate = true;
  76650. },
  76651. enumerable: true,
  76652. configurable: true
  76653. });
  76654. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  76655. /**
  76656. * Support test.
  76657. */
  76658. get: function () {
  76659. var engine = BABYLON.Engine.LastCreatedEngine;
  76660. if (!engine) {
  76661. return false;
  76662. }
  76663. return engine.getCaps().drawBuffersExtension;
  76664. },
  76665. enumerable: true,
  76666. configurable: true
  76667. });
  76668. // Public Methods
  76669. /**
  76670. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  76671. */
  76672. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  76673. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  76674. for (var i = 0; i < this._scene.cameras.length; i++) {
  76675. var camera = this._scene.cameras[i];
  76676. this._originalColorPostProcess.dispose(camera);
  76677. this._ssaoPostProcess.dispose(camera);
  76678. this._blurHPostProcess.dispose(camera);
  76679. this._blurVPostProcess.dispose(camera);
  76680. this._ssaoCombinePostProcess.dispose(camera);
  76681. }
  76682. this._randomTexture.dispose();
  76683. if (disableGeometryBufferRenderer)
  76684. this._scene.disableGeometryBufferRenderer();
  76685. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  76686. _super.prototype.dispose.call(this);
  76687. };
  76688. // Private Methods
  76689. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  76690. var _this = this;
  76691. this._samplerOffsets = [];
  76692. var expensive = this.expensiveBlur;
  76693. for (var i = -8; i < 8; i++) {
  76694. this._samplerOffsets.push(i * 2 + 0.5);
  76695. }
  76696. 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");
  76697. this._blurHPostProcess.onApply = function (effect) {
  76698. if (!_this._scene.activeCamera) {
  76699. return;
  76700. }
  76701. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  76702. effect.setFloat("near", _this._scene.activeCamera.minZ);
  76703. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  76704. effect.setFloat("radius", _this.radius);
  76705. effect.setTexture("depthSampler", _this._depthTexture);
  76706. if (_this._firstUpdate) {
  76707. effect.setArray("samplerOffsets", _this._samplerOffsets);
  76708. }
  76709. };
  76710. 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");
  76711. this._blurVPostProcess.onApply = function (effect) {
  76712. if (!_this._scene.activeCamera) {
  76713. return;
  76714. }
  76715. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  76716. effect.setFloat("near", _this._scene.activeCamera.minZ);
  76717. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  76718. effect.setFloat("radius", _this.radius);
  76719. effect.setTexture("depthSampler", _this._depthTexture);
  76720. if (_this._firstUpdate) {
  76721. effect.setArray("samplerOffsets", _this._samplerOffsets);
  76722. _this._firstUpdate = false;
  76723. }
  76724. };
  76725. };
  76726. /** @hidden */
  76727. SSAO2RenderingPipeline.prototype._rebuild = function () {
  76728. this._firstUpdate = true;
  76729. _super.prototype._rebuild.call(this);
  76730. };
  76731. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  76732. var numSamples = this.samples;
  76733. var result = [];
  76734. var vector, scale;
  76735. var rand = function (min, max) {
  76736. return Math.random() * (max - min) + min;
  76737. };
  76738. var i = 0;
  76739. while (i < numSamples) {
  76740. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  76741. vector.normalize();
  76742. scale = i / numSamples;
  76743. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  76744. vector.scaleInPlace(scale);
  76745. result.push(vector.x, vector.y, vector.z);
  76746. i++;
  76747. }
  76748. return result;
  76749. };
  76750. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  76751. var _this = this;
  76752. var numSamples = this.samples;
  76753. this._sampleSphere = this._generateHemisphere();
  76754. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  76755. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  76756. "base", "range", "projection", "near", "far", "texelSize",
  76757. "xViewport", "yViewport", "maxZ", "minZAspect"
  76758. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  76759. this._ssaoPostProcess.onApply = function (effect) {
  76760. if (_this._firstUpdate) {
  76761. effect.setArray3("sampleSphere", _this._sampleSphere);
  76762. effect.setFloat("randTextureTiles", 4.0);
  76763. }
  76764. if (!_this._scene.activeCamera) {
  76765. return;
  76766. }
  76767. effect.setFloat("samplesFactor", 1 / _this.samples);
  76768. effect.setFloat("totalStrength", _this.totalStrength);
  76769. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  76770. effect.setFloat("radius", _this.radius);
  76771. effect.setFloat("maxZ", _this.maxZ);
  76772. effect.setFloat("minZAspect", _this.minZAspect);
  76773. effect.setFloat("base", _this.base);
  76774. effect.setFloat("near", _this._scene.activeCamera.minZ);
  76775. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  76776. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  76777. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  76778. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  76779. effect.setTexture("textureSampler", _this._depthTexture);
  76780. effect.setTexture("normalSampler", _this._normalTexture);
  76781. effect.setTexture("randomSampler", _this._randomTexture);
  76782. };
  76783. };
  76784. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  76785. var _this = this;
  76786. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  76787. this._ssaoCombinePostProcess.onApply = function (effect) {
  76788. var viewport = _this._scene.activeCamera.viewport;
  76789. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  76790. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  76791. };
  76792. };
  76793. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  76794. var size = 512;
  76795. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  76796. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  76797. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  76798. var context = this._randomTexture.getContext();
  76799. var rand = function (min, max) {
  76800. return Math.random() * (max - min) + min;
  76801. };
  76802. var randVector = BABYLON.Vector3.Zero();
  76803. for (var x = 0; x < size; x++) {
  76804. for (var y = 0; y < size; y++) {
  76805. randVector.x = rand(0.0, 1.0);
  76806. randVector.y = rand(0.0, 1.0);
  76807. randVector.z = 0.0;
  76808. randVector.normalize();
  76809. randVector.scaleInPlace(255);
  76810. randVector.x = Math.floor(randVector.x);
  76811. randVector.y = Math.floor(randVector.y);
  76812. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  76813. context.fillRect(x, y, 1, 1);
  76814. }
  76815. }
  76816. this._randomTexture.update(false);
  76817. };
  76818. /**
  76819. * Serialize the rendering pipeline (Used when exporting)
  76820. * @returns the serialized object
  76821. */
  76822. SSAO2RenderingPipeline.prototype.serialize = function () {
  76823. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76824. serializationObject.customType = "SSAO2RenderingPipeline";
  76825. return serializationObject;
  76826. };
  76827. /**
  76828. * Parse the serialized pipeline
  76829. * @param source Source pipeline.
  76830. * @param scene The scene to load the pipeline to.
  76831. * @param rootUrl The URL of the serialized pipeline.
  76832. * @returns An instantiated pipeline from the serialized object.
  76833. */
  76834. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  76835. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  76836. };
  76837. __decorate([
  76838. BABYLON.serialize()
  76839. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  76840. __decorate([
  76841. BABYLON.serialize()
  76842. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  76843. __decorate([
  76844. BABYLON.serialize()
  76845. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  76846. __decorate([
  76847. BABYLON.serialize("samples")
  76848. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  76849. __decorate([
  76850. BABYLON.serialize()
  76851. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  76852. __decorate([
  76853. BABYLON.serialize("expensiveBlur")
  76854. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  76855. __decorate([
  76856. BABYLON.serialize()
  76857. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  76858. __decorate([
  76859. BABYLON.serialize()
  76860. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  76861. return SSAO2RenderingPipeline;
  76862. }(BABYLON.PostProcessRenderPipeline));
  76863. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  76864. })(BABYLON || (BABYLON = {}));
  76865. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  76866. // BABYLON.JS Chromatic Aberration GLSL Shader
  76867. // Author: Olivier Guyot
  76868. // Separates very slightly R, G and B colors on the edges of the screen
  76869. // Inspired by Francois Tarlier & Martins Upitis
  76870. var BABYLON;
  76871. (function (BABYLON) {
  76872. var LensRenderingPipeline = /** @class */ (function (_super) {
  76873. __extends(LensRenderingPipeline, _super);
  76874. /**
  76875. * @constructor
  76876. *
  76877. * Effect parameters are as follow:
  76878. * {
  76879. * chromatic_aberration: number; // from 0 to x (1 for realism)
  76880. * edge_blur: number; // from 0 to x (1 for realism)
  76881. * distortion: number; // from 0 to x (1 for realism)
  76882. * grain_amount: number; // from 0 to 1
  76883. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  76884. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  76885. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  76886. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  76887. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  76888. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  76889. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  76890. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  76891. * }
  76892. * Note: if an effect parameter is unset, effect is disabled
  76893. *
  76894. * @param {string} name - The rendering pipeline name
  76895. * @param {object} parameters - An object containing all parameters (see above)
  76896. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  76897. * @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)
  76898. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  76899. */
  76900. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  76901. if (ratio === void 0) { ratio = 1.0; }
  76902. var _this = _super.call(this, scene.getEngine(), name) || this;
  76903. // Lens effects can be of the following:
  76904. // - chromatic aberration (slight shift of RGB colors)
  76905. // - blur on the edge of the lens
  76906. // - lens distortion
  76907. // - depth-of-field blur & highlights enhancing
  76908. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  76909. // - grain effect (noise or custom texture)
  76910. // Two additional texture samplers are needed:
  76911. // - depth map (for depth-of-field)
  76912. // - grain texture
  76913. /**
  76914. * The chromatic aberration PostProcess id in the pipeline
  76915. */
  76916. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  76917. /**
  76918. * The highlights enhancing PostProcess id in the pipeline
  76919. */
  76920. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  76921. /**
  76922. * The depth-of-field PostProcess id in the pipeline
  76923. */
  76924. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  76925. _this._scene = scene;
  76926. // Fetch texture samplers
  76927. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  76928. if (parameters.grain_texture) {
  76929. _this._grainTexture = parameters.grain_texture;
  76930. }
  76931. else {
  76932. _this._createGrainTexture();
  76933. }
  76934. // save parameters
  76935. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  76936. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  76937. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  76938. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  76939. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  76940. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  76941. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  76942. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  76943. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  76944. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  76945. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  76946. // Create effects
  76947. _this._createChromaticAberrationPostProcess(ratio);
  76948. _this._createHighlightsPostProcess(ratio);
  76949. _this._createDepthOfFieldPostProcess(ratio / 4);
  76950. // Set up pipeline
  76951. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  76952. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  76953. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  76954. if (_this._highlightsGain === -1) {
  76955. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  76956. }
  76957. // Finish
  76958. scene.postProcessRenderPipelineManager.addPipeline(_this);
  76959. if (cameras) {
  76960. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  76961. }
  76962. return _this;
  76963. }
  76964. // public methods (self explanatory)
  76965. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  76966. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  76967. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  76968. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  76969. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  76970. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  76971. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  76972. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  76973. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  76974. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  76975. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  76976. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  76977. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  76978. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  76979. };
  76980. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  76981. this._highlightsPostProcess.updateEffect();
  76982. };
  76983. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  76984. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  76985. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  76986. this._highlightsGain = amount;
  76987. };
  76988. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  76989. if (this._highlightsGain === -1) {
  76990. this._highlightsGain = 1.0;
  76991. }
  76992. this._highlightsThreshold = amount;
  76993. };
  76994. LensRenderingPipeline.prototype.disableHighlights = function () {
  76995. this._highlightsGain = -1;
  76996. };
  76997. /**
  76998. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  76999. */
  77000. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  77001. if (disableDepthRender === void 0) { disableDepthRender = false; }
  77002. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  77003. this._chromaticAberrationPostProcess = null;
  77004. this._highlightsPostProcess = null;
  77005. this._depthOfFieldPostProcess = null;
  77006. this._grainTexture.dispose();
  77007. if (disableDepthRender)
  77008. this._scene.disableDepthRenderer();
  77009. };
  77010. // colors shifting and distortion
  77011. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  77012. var _this = this;
  77013. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  77014. [], // samplers
  77015. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  77016. this._chromaticAberrationPostProcess.onApply = function (effect) {
  77017. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  77018. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  77019. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  77020. effect.setFloat('radialIntensity', 1);
  77021. effect.setFloat2('direction', 17, 17);
  77022. effect.setFloat2('centerPosition', 0.5, 0.5);
  77023. };
  77024. };
  77025. // highlights enhancing
  77026. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  77027. var _this = this;
  77028. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  77029. [], // samplers
  77030. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  77031. this._highlightsPostProcess.onApply = function (effect) {
  77032. effect.setFloat('gain', _this._highlightsGain);
  77033. effect.setFloat('threshold', _this._highlightsThreshold);
  77034. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  77035. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  77036. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  77037. };
  77038. };
  77039. // colors shifting and distortion
  77040. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  77041. var _this = this;
  77042. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  77043. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  77044. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  77045. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  77046. this._depthOfFieldPostProcess.onApply = function (effect) {
  77047. effect.setTexture("depthSampler", _this._depthTexture);
  77048. effect.setTexture("grainSampler", _this._grainTexture);
  77049. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  77050. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  77051. effect.setFloat('grain_amount', _this._grainAmount);
  77052. effect.setBool('blur_noise', _this._blurNoise);
  77053. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  77054. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  77055. effect.setFloat('distortion', _this._distortion);
  77056. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  77057. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  77058. effect.setFloat('aperture', _this._dofAperture);
  77059. effect.setFloat('darken', _this._dofDarken);
  77060. effect.setFloat('edge_blur', _this._edgeBlur);
  77061. effect.setBool('highlights', (_this._highlightsGain !== -1));
  77062. if (_this._scene.activeCamera) {
  77063. effect.setFloat('near', _this._scene.activeCamera.minZ);
  77064. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  77065. }
  77066. };
  77067. };
  77068. // creates a black and white random noise texture, 512x512
  77069. LensRenderingPipeline.prototype._createGrainTexture = function () {
  77070. var size = 512;
  77071. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77072. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  77073. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  77074. var context = this._grainTexture.getContext();
  77075. var rand = function (min, max) {
  77076. return Math.random() * (max - min) + min;
  77077. };
  77078. var value;
  77079. for (var x = 0; x < size; x++) {
  77080. for (var y = 0; y < size; y++) {
  77081. value = Math.floor(rand(0.42, 0.58) * 255);
  77082. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  77083. context.fillRect(x, y, 1, 1);
  77084. }
  77085. }
  77086. this._grainTexture.update(false);
  77087. };
  77088. return LensRenderingPipeline;
  77089. }(BABYLON.PostProcessRenderPipeline));
  77090. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  77091. })(BABYLON || (BABYLON = {}));
  77092. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  77093. var BABYLON;
  77094. (function (BABYLON) {
  77095. var StandardRenderingPipeline = /** @class */ (function (_super) {
  77096. __extends(StandardRenderingPipeline, _super);
  77097. /**
  77098. * @constructor
  77099. * @param {string} name - The rendering pipeline name
  77100. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  77101. * @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)
  77102. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  77103. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  77104. */
  77105. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  77106. if (originalPostProcess === void 0) { originalPostProcess = null; }
  77107. var _this = _super.call(this, scene.getEngine(), name) || this;
  77108. _this.downSampleX4PostProcess = null;
  77109. _this.brightPassPostProcess = null;
  77110. _this.blurHPostProcesses = [];
  77111. _this.blurVPostProcesses = [];
  77112. _this.textureAdderPostProcess = null;
  77113. _this.volumetricLightPostProcess = null;
  77114. _this.volumetricLightSmoothXPostProcess = null;
  77115. _this.volumetricLightSmoothYPostProcess = null;
  77116. _this.volumetricLightMergePostProces = null;
  77117. _this.volumetricLightFinalPostProcess = null;
  77118. _this.luminancePostProcess = null;
  77119. _this.luminanceDownSamplePostProcesses = [];
  77120. _this.hdrPostProcess = null;
  77121. _this.textureAdderFinalPostProcess = null;
  77122. _this.lensFlareFinalPostProcess = null;
  77123. _this.hdrFinalPostProcess = null;
  77124. _this.lensFlarePostProcess = null;
  77125. _this.lensFlareComposePostProcess = null;
  77126. _this.motionBlurPostProcess = null;
  77127. _this.depthOfFieldPostProcess = null;
  77128. // Values
  77129. _this.brightThreshold = 1.0;
  77130. _this.blurWidth = 512.0;
  77131. _this.horizontalBlur = false;
  77132. _this.exposure = 1.0;
  77133. _this.lensTexture = null;
  77134. _this.volumetricLightCoefficient = 0.2;
  77135. _this.volumetricLightPower = 4.0;
  77136. _this.volumetricLightBlurScale = 64.0;
  77137. _this.sourceLight = null;
  77138. _this.hdrMinimumLuminance = 1.0;
  77139. _this.hdrDecreaseRate = 0.5;
  77140. _this.hdrIncreaseRate = 0.5;
  77141. _this.lensColorTexture = null;
  77142. _this.lensFlareStrength = 20.0;
  77143. _this.lensFlareGhostDispersal = 1.4;
  77144. _this.lensFlareHaloWidth = 0.7;
  77145. _this.lensFlareDistortionStrength = 16.0;
  77146. _this.lensStarTexture = null;
  77147. _this.lensFlareDirtTexture = null;
  77148. _this.depthOfFieldDistance = 10.0;
  77149. _this.depthOfFieldBlurWidth = 64.0;
  77150. _this.motionStrength = 1.0;
  77151. // IAnimatable
  77152. _this.animations = [];
  77153. _this._currentDepthOfFieldSource = null;
  77154. _this._hdrCurrentLuminance = 1.0;
  77155. // Getters and setters
  77156. _this._bloomEnabled = true;
  77157. _this._depthOfFieldEnabled = false;
  77158. _this._vlsEnabled = false;
  77159. _this._lensFlareEnabled = false;
  77160. _this._hdrEnabled = false;
  77161. _this._motionBlurEnabled = false;
  77162. _this._motionBlurSamples = 64.0;
  77163. _this._volumetricLightStepsCount = 50.0;
  77164. _this._cameras = cameras || [];
  77165. // Initialize
  77166. _this._scene = scene;
  77167. _this._basePostProcess = originalPostProcess;
  77168. _this._ratio = ratio;
  77169. // Misc
  77170. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77171. // Finish
  77172. scene.postProcessRenderPipelineManager.addPipeline(_this);
  77173. _this._buildPipeline();
  77174. return _this;
  77175. }
  77176. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  77177. get: function () {
  77178. return this._bloomEnabled;
  77179. },
  77180. set: function (enabled) {
  77181. if (this._bloomEnabled === enabled) {
  77182. return;
  77183. }
  77184. this._bloomEnabled = enabled;
  77185. this._buildPipeline();
  77186. },
  77187. enumerable: true,
  77188. configurable: true
  77189. });
  77190. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  77191. get: function () {
  77192. return this._depthOfFieldEnabled;
  77193. },
  77194. set: function (enabled) {
  77195. if (this._depthOfFieldEnabled === enabled) {
  77196. return;
  77197. }
  77198. this._depthOfFieldEnabled = enabled;
  77199. this._buildPipeline();
  77200. },
  77201. enumerable: true,
  77202. configurable: true
  77203. });
  77204. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  77205. get: function () {
  77206. return this._lensFlareEnabled;
  77207. },
  77208. set: function (enabled) {
  77209. if (this._lensFlareEnabled === enabled) {
  77210. return;
  77211. }
  77212. this._lensFlareEnabled = enabled;
  77213. this._buildPipeline();
  77214. },
  77215. enumerable: true,
  77216. configurable: true
  77217. });
  77218. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  77219. get: function () {
  77220. return this._hdrEnabled;
  77221. },
  77222. set: function (enabled) {
  77223. if (this._hdrEnabled === enabled) {
  77224. return;
  77225. }
  77226. this._hdrEnabled = enabled;
  77227. this._buildPipeline();
  77228. },
  77229. enumerable: true,
  77230. configurable: true
  77231. });
  77232. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  77233. get: function () {
  77234. return this._vlsEnabled;
  77235. },
  77236. set: function (enabled) {
  77237. if (this._vlsEnabled === enabled) {
  77238. return;
  77239. }
  77240. if (enabled) {
  77241. var geometry = this._scene.enableGeometryBufferRenderer();
  77242. if (!geometry) {
  77243. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  77244. return;
  77245. }
  77246. }
  77247. this._vlsEnabled = enabled;
  77248. this._buildPipeline();
  77249. },
  77250. enumerable: true,
  77251. configurable: true
  77252. });
  77253. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  77254. get: function () {
  77255. return this._motionBlurEnabled;
  77256. },
  77257. set: function (enabled) {
  77258. if (this._motionBlurEnabled === enabled) {
  77259. return;
  77260. }
  77261. this._motionBlurEnabled = enabled;
  77262. this._buildPipeline();
  77263. },
  77264. enumerable: true,
  77265. configurable: true
  77266. });
  77267. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  77268. get: function () {
  77269. return this._volumetricLightStepsCount;
  77270. },
  77271. set: function (count) {
  77272. if (this.volumetricLightPostProcess) {
  77273. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  77274. }
  77275. this._volumetricLightStepsCount = count;
  77276. },
  77277. enumerable: true,
  77278. configurable: true
  77279. });
  77280. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  77281. get: function () {
  77282. return this._motionBlurSamples;
  77283. },
  77284. set: function (samples) {
  77285. if (this.motionBlurPostProcess) {
  77286. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  77287. }
  77288. this._motionBlurSamples = samples;
  77289. },
  77290. enumerable: true,
  77291. configurable: true
  77292. });
  77293. StandardRenderingPipeline.prototype._buildPipeline = function () {
  77294. var _this = this;
  77295. var ratio = this._ratio;
  77296. var scene = this._scene;
  77297. this._disposePostProcesses();
  77298. this._reset();
  77299. // Create pass post-process
  77300. if (!this._basePostProcess) {
  77301. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  77302. this.originalPostProcess.onApply = function (effect) {
  77303. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  77304. };
  77305. }
  77306. else {
  77307. this.originalPostProcess = this._basePostProcess;
  77308. }
  77309. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  77310. this._currentDepthOfFieldSource = this.originalPostProcess;
  77311. if (this._bloomEnabled) {
  77312. // Create down sample X4 post-process
  77313. this._createDownSampleX4PostProcess(scene, ratio / 2);
  77314. // Create bright pass post-process
  77315. this._createBrightPassPostProcess(scene, ratio / 2);
  77316. // Create gaussian blur post-processes (down sampling blurs)
  77317. this._createBlurPostProcesses(scene, ratio / 4, 1);
  77318. // Create texture adder post-process
  77319. this._createTextureAdderPostProcess(scene, ratio);
  77320. // Create depth-of-field source post-process
  77321. 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);
  77322. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  77323. }
  77324. if (this._vlsEnabled) {
  77325. // Create volumetric light
  77326. this._createVolumetricLightPostProcess(scene, ratio);
  77327. // Create volumetric light final post-process
  77328. 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);
  77329. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  77330. }
  77331. if (this._lensFlareEnabled) {
  77332. // Create lens flare post-process
  77333. this._createLensFlarePostProcess(scene, ratio);
  77334. // Create depth-of-field source post-process post lens-flare and disable it now
  77335. 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);
  77336. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  77337. }
  77338. if (this._hdrEnabled) {
  77339. // Create luminance
  77340. this._createLuminancePostProcesses(scene, this._floatTextureType);
  77341. // Create HDR
  77342. this._createHdrPostProcess(scene, ratio);
  77343. // Create depth-of-field source post-process post hdr and disable it now
  77344. 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);
  77345. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  77346. }
  77347. if (this._depthOfFieldEnabled) {
  77348. // Create gaussian blur used by depth-of-field
  77349. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  77350. // Create depth-of-field post-process
  77351. this._createDepthOfFieldPostProcess(scene, ratio);
  77352. }
  77353. if (this._motionBlurEnabled) {
  77354. // Create motion blur post-process
  77355. this._createMotionBlurPostProcess(scene, ratio);
  77356. }
  77357. if (this._cameras !== null) {
  77358. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  77359. }
  77360. };
  77361. // Down Sample X4 Post-Processs
  77362. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  77363. var _this = this;
  77364. var downSampleX4Offsets = new Array(32);
  77365. 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);
  77366. this.downSampleX4PostProcess.onApply = function (effect) {
  77367. var id = 0;
  77368. var width = _this.downSampleX4PostProcess.width;
  77369. var height = _this.downSampleX4PostProcess.height;
  77370. for (var i = -2; i < 2; i++) {
  77371. for (var j = -2; j < 2; j++) {
  77372. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  77373. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  77374. id += 2;
  77375. }
  77376. }
  77377. effect.setArray2("dsOffsets", downSampleX4Offsets);
  77378. };
  77379. // Add to pipeline
  77380. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  77381. };
  77382. // Brightpass Post-Process
  77383. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  77384. var _this = this;
  77385. var brightOffsets = new Array(8);
  77386. 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);
  77387. this.brightPassPostProcess.onApply = function (effect) {
  77388. var sU = (1.0 / _this.brightPassPostProcess.width);
  77389. var sV = (1.0 / _this.brightPassPostProcess.height);
  77390. brightOffsets[0] = -0.5 * sU;
  77391. brightOffsets[1] = 0.5 * sV;
  77392. brightOffsets[2] = 0.5 * sU;
  77393. brightOffsets[3] = 0.5 * sV;
  77394. brightOffsets[4] = -0.5 * sU;
  77395. brightOffsets[5] = -0.5 * sV;
  77396. brightOffsets[6] = 0.5 * sU;
  77397. brightOffsets[7] = -0.5 * sV;
  77398. effect.setArray2("dsOffsets", brightOffsets);
  77399. effect.setFloat("brightThreshold", _this.brightThreshold);
  77400. };
  77401. // Add to pipeline
  77402. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  77403. };
  77404. // Create blur H&V post-processes
  77405. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  77406. var _this = this;
  77407. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  77408. var engine = scene.getEngine();
  77409. 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);
  77410. 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);
  77411. blurX.onActivateObservable.add(function () {
  77412. var dw = blurX.width / engine.getRenderWidth();
  77413. blurX.kernel = _this[blurWidthKey] * dw;
  77414. });
  77415. blurY.onActivateObservable.add(function () {
  77416. var dw = blurY.height / engine.getRenderHeight();
  77417. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  77418. });
  77419. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  77420. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  77421. this.blurHPostProcesses.push(blurX);
  77422. this.blurVPostProcesses.push(blurY);
  77423. };
  77424. // Create texture adder post-process
  77425. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  77426. var _this = this;
  77427. 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);
  77428. this.textureAdderPostProcess.onApply = function (effect) {
  77429. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  77430. effect.setTexture("lensSampler", _this.lensTexture);
  77431. effect.setFloat("exposure", _this.exposure);
  77432. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  77433. };
  77434. // Add to pipeline
  77435. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  77436. };
  77437. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  77438. var _this = this;
  77439. var geometryRenderer = scene.enableGeometryBufferRenderer();
  77440. geometryRenderer.enablePosition = true;
  77441. var geometry = geometryRenderer.getGBuffer();
  77442. // Base post-process
  77443. 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));
  77444. var depthValues = BABYLON.Vector2.Zero();
  77445. this.volumetricLightPostProcess.onApply = function (effect) {
  77446. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  77447. var generator = _this.sourceLight.getShadowGenerator();
  77448. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  77449. effect.setTexture("positionSampler", geometry.textures[2]);
  77450. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  77451. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  77452. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  77453. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  77454. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  77455. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  77456. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  77457. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  77458. effect.setVector2("depthValues", depthValues);
  77459. }
  77460. };
  77461. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  77462. // Smooth
  77463. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  77464. // Merge
  77465. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  77466. this.volumetricLightMergePostProces.onApply = function (effect) {
  77467. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  77468. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  77469. };
  77470. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  77471. };
  77472. // Create luminance
  77473. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  77474. var _this = this;
  77475. // Create luminance
  77476. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  77477. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  77478. var offsets = [];
  77479. this.luminancePostProcess.onApply = function (effect) {
  77480. var sU = (1.0 / _this.luminancePostProcess.width);
  77481. var sV = (1.0 / _this.luminancePostProcess.height);
  77482. offsets[0] = -0.5 * sU;
  77483. offsets[1] = 0.5 * sV;
  77484. offsets[2] = 0.5 * sU;
  77485. offsets[3] = 0.5 * sV;
  77486. offsets[4] = -0.5 * sU;
  77487. offsets[5] = -0.5 * sV;
  77488. offsets[6] = 0.5 * sU;
  77489. offsets[7] = -0.5 * sV;
  77490. effect.setArray2("lumOffsets", offsets);
  77491. };
  77492. // Add to pipeline
  77493. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  77494. // Create down sample luminance
  77495. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  77496. var size = Math.pow(3, i);
  77497. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  77498. if (i === 0) {
  77499. defines += "#define FINAL_DOWN_SAMPLER";
  77500. }
  77501. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  77502. this.luminanceDownSamplePostProcesses.push(postProcess);
  77503. }
  77504. // Create callbacks and add effects
  77505. var lastLuminance = this.luminancePostProcess;
  77506. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  77507. var downSampleOffsets = new Array(18);
  77508. pp.onApply = function (effect) {
  77509. if (!lastLuminance) {
  77510. return;
  77511. }
  77512. var id = 0;
  77513. for (var x = -1; x < 2; x++) {
  77514. for (var y = -1; y < 2; y++) {
  77515. downSampleOffsets[id] = x / lastLuminance.width;
  77516. downSampleOffsets[id + 1] = y / lastLuminance.height;
  77517. id += 2;
  77518. }
  77519. }
  77520. effect.setArray2("dsOffsets", downSampleOffsets);
  77521. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  77522. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  77523. lastLuminance = _this.luminancePostProcess;
  77524. }
  77525. else {
  77526. lastLuminance = pp;
  77527. }
  77528. };
  77529. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  77530. pp.onAfterRender = function (effect) {
  77531. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  77532. 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);
  77533. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  77534. };
  77535. }
  77536. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  77537. });
  77538. };
  77539. // Create HDR post-process
  77540. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  77541. var _this = this;
  77542. 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);
  77543. var outputLiminance = 1;
  77544. var time = 0;
  77545. var lastTime = 0;
  77546. this.hdrPostProcess.onApply = function (effect) {
  77547. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  77548. time += scene.getEngine().getDeltaTime();
  77549. if (outputLiminance < 0) {
  77550. outputLiminance = _this._hdrCurrentLuminance;
  77551. }
  77552. else {
  77553. var dt = (lastTime - time) / 1000.0;
  77554. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  77555. outputLiminance += _this.hdrDecreaseRate * dt;
  77556. }
  77557. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  77558. outputLiminance -= _this.hdrIncreaseRate * dt;
  77559. }
  77560. else {
  77561. outputLiminance = _this._hdrCurrentLuminance;
  77562. }
  77563. }
  77564. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  77565. effect.setFloat("averageLuminance", outputLiminance);
  77566. lastTime = time;
  77567. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  77568. };
  77569. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  77570. };
  77571. // Create lens flare post-process
  77572. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  77573. var _this = this;
  77574. 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);
  77575. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  77576. this._createBlurPostProcesses(scene, ratio / 4, 2);
  77577. 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);
  77578. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  77579. var resolution = new BABYLON.Vector2(0, 0);
  77580. // Lens flare
  77581. this.lensFlarePostProcess.onApply = function (effect) {
  77582. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  77583. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  77584. effect.setFloat("strength", _this.lensFlareStrength);
  77585. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  77586. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  77587. // Shift
  77588. resolution.x = _this.lensFlarePostProcess.width;
  77589. resolution.y = _this.lensFlarePostProcess.height;
  77590. effect.setVector2("resolution", resolution);
  77591. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  77592. };
  77593. // Compose
  77594. 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);
  77595. 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);
  77596. this.lensFlareComposePostProcess.onApply = function (effect) {
  77597. if (!_this._scene.activeCamera) {
  77598. return;
  77599. }
  77600. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  77601. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  77602. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  77603. // Lens start rotation matrix
  77604. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  77605. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  77606. 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));
  77607. camRot *= 4.0;
  77608. 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);
  77609. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  77610. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  77611. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  77612. };
  77613. };
  77614. // Create depth-of-field post-process
  77615. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  77616. var _this = this;
  77617. 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);
  77618. this.depthOfFieldPostProcess.onApply = function (effect) {
  77619. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  77620. effect.setTexture("depthSampler", _this._getDepthTexture());
  77621. effect.setFloat("distance", _this.depthOfFieldDistance);
  77622. };
  77623. // Add to pipeline
  77624. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  77625. };
  77626. // Create motion blur post-process
  77627. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  77628. var _this = this;
  77629. 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);
  77630. var motionScale = 0;
  77631. var prevViewProjection = BABYLON.Matrix.Identity();
  77632. var invViewProjection = BABYLON.Matrix.Identity();
  77633. var viewProjection = BABYLON.Matrix.Identity();
  77634. var screenSize = BABYLON.Vector2.Zero();
  77635. this.motionBlurPostProcess.onApply = function (effect) {
  77636. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  77637. viewProjection.invertToRef(invViewProjection);
  77638. effect.setMatrix("inverseViewProjection", invViewProjection);
  77639. effect.setMatrix("prevViewProjection", prevViewProjection);
  77640. prevViewProjection = viewProjection;
  77641. screenSize.x = _this.motionBlurPostProcess.width;
  77642. screenSize.y = _this.motionBlurPostProcess.height;
  77643. effect.setVector2("screenSize", screenSize);
  77644. motionScale = scene.getEngine().getFps() / 60.0;
  77645. effect.setFloat("motionScale", motionScale);
  77646. effect.setFloat("motionStrength", _this.motionStrength);
  77647. effect.setTexture("depthSampler", _this._getDepthTexture());
  77648. };
  77649. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  77650. };
  77651. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  77652. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  77653. var renderer = this._scene.enableGeometryBufferRenderer();
  77654. return renderer.getGBuffer().textures[0];
  77655. }
  77656. return this._scene.enableDepthRenderer().getDepthMap();
  77657. };
  77658. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  77659. for (var i = 0; i < this._cameras.length; i++) {
  77660. var camera = this._cameras[i];
  77661. if (this.originalPostProcess) {
  77662. this.originalPostProcess.dispose(camera);
  77663. }
  77664. if (this.downSampleX4PostProcess) {
  77665. this.downSampleX4PostProcess.dispose(camera);
  77666. }
  77667. if (this.brightPassPostProcess) {
  77668. this.brightPassPostProcess.dispose(camera);
  77669. }
  77670. if (this.textureAdderPostProcess) {
  77671. this.textureAdderPostProcess.dispose(camera);
  77672. }
  77673. if (this.textureAdderFinalPostProcess) {
  77674. this.textureAdderFinalPostProcess.dispose(camera);
  77675. }
  77676. if (this.volumetricLightPostProcess) {
  77677. this.volumetricLightPostProcess.dispose(camera);
  77678. }
  77679. if (this.volumetricLightSmoothXPostProcess) {
  77680. this.volumetricLightSmoothXPostProcess.dispose(camera);
  77681. }
  77682. if (this.volumetricLightSmoothYPostProcess) {
  77683. this.volumetricLightSmoothYPostProcess.dispose(camera);
  77684. }
  77685. if (this.volumetricLightMergePostProces) {
  77686. this.volumetricLightMergePostProces.dispose(camera);
  77687. }
  77688. if (this.volumetricLightFinalPostProcess) {
  77689. this.volumetricLightFinalPostProcess.dispose(camera);
  77690. }
  77691. if (this.lensFlarePostProcess) {
  77692. this.lensFlarePostProcess.dispose(camera);
  77693. }
  77694. if (this.lensFlareComposePostProcess) {
  77695. this.lensFlareComposePostProcess.dispose(camera);
  77696. }
  77697. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  77698. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  77699. }
  77700. if (this.luminancePostProcess) {
  77701. this.luminancePostProcess.dispose(camera);
  77702. }
  77703. if (this.hdrPostProcess) {
  77704. this.hdrPostProcess.dispose(camera);
  77705. }
  77706. if (this.hdrFinalPostProcess) {
  77707. this.hdrFinalPostProcess.dispose(camera);
  77708. }
  77709. if (this.depthOfFieldPostProcess) {
  77710. this.depthOfFieldPostProcess.dispose(camera);
  77711. }
  77712. if (this.motionBlurPostProcess) {
  77713. this.motionBlurPostProcess.dispose(camera);
  77714. }
  77715. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  77716. this.blurHPostProcesses[j].dispose(camera);
  77717. }
  77718. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  77719. this.blurVPostProcesses[j].dispose(camera);
  77720. }
  77721. }
  77722. this.originalPostProcess = null;
  77723. this.downSampleX4PostProcess = null;
  77724. this.brightPassPostProcess = null;
  77725. this.textureAdderPostProcess = null;
  77726. this.textureAdderFinalPostProcess = null;
  77727. this.volumetricLightPostProcess = null;
  77728. this.volumetricLightSmoothXPostProcess = null;
  77729. this.volumetricLightSmoothYPostProcess = null;
  77730. this.volumetricLightMergePostProces = null;
  77731. this.volumetricLightFinalPostProcess = null;
  77732. this.lensFlarePostProcess = null;
  77733. this.lensFlareComposePostProcess = null;
  77734. this.luminancePostProcess = null;
  77735. this.hdrPostProcess = null;
  77736. this.hdrFinalPostProcess = null;
  77737. this.depthOfFieldPostProcess = null;
  77738. this.motionBlurPostProcess = null;
  77739. this.luminanceDownSamplePostProcesses = [];
  77740. this.blurHPostProcesses = [];
  77741. this.blurVPostProcesses = [];
  77742. };
  77743. /**
  77744. * Dispose of the pipeline and stop all post processes
  77745. */
  77746. StandardRenderingPipeline.prototype.dispose = function () {
  77747. this._disposePostProcesses();
  77748. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  77749. _super.prototype.dispose.call(this);
  77750. };
  77751. /**
  77752. * Serialize the rendering pipeline (Used when exporting)
  77753. * @returns the serialized object
  77754. */
  77755. StandardRenderingPipeline.prototype.serialize = function () {
  77756. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  77757. if (this.sourceLight) {
  77758. serializationObject.sourceLightId = this.sourceLight.id;
  77759. }
  77760. serializationObject.customType = "StandardRenderingPipeline";
  77761. return serializationObject;
  77762. };
  77763. /**
  77764. * Parse the serialized pipeline
  77765. * @param source Source pipeline.
  77766. * @param scene The scene to load the pipeline to.
  77767. * @param rootUrl The URL of the serialized pipeline.
  77768. * @returns An instantiated pipeline from the serialized object.
  77769. */
  77770. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  77771. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  77772. if (source.sourceLightId) {
  77773. p.sourceLight = scene.getLightByID(source.sourceLightId);
  77774. }
  77775. return p;
  77776. };
  77777. // Luminance steps
  77778. StandardRenderingPipeline.LuminanceSteps = 6;
  77779. __decorate([
  77780. BABYLON.serialize()
  77781. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  77782. __decorate([
  77783. BABYLON.serialize()
  77784. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  77785. __decorate([
  77786. BABYLON.serialize()
  77787. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  77788. __decorate([
  77789. BABYLON.serialize()
  77790. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  77791. __decorate([
  77792. BABYLON.serializeAsTexture("lensTexture")
  77793. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  77794. __decorate([
  77795. BABYLON.serialize()
  77796. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  77797. __decorate([
  77798. BABYLON.serialize()
  77799. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  77800. __decorate([
  77801. BABYLON.serialize()
  77802. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  77803. __decorate([
  77804. BABYLON.serialize()
  77805. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  77806. __decorate([
  77807. BABYLON.serialize()
  77808. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  77809. __decorate([
  77810. BABYLON.serialize()
  77811. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  77812. __decorate([
  77813. BABYLON.serializeAsTexture("lensColorTexture")
  77814. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  77815. __decorate([
  77816. BABYLON.serialize()
  77817. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  77818. __decorate([
  77819. BABYLON.serialize()
  77820. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  77821. __decorate([
  77822. BABYLON.serialize()
  77823. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  77824. __decorate([
  77825. BABYLON.serialize()
  77826. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  77827. __decorate([
  77828. BABYLON.serializeAsTexture("lensStarTexture")
  77829. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  77830. __decorate([
  77831. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  77832. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  77833. __decorate([
  77834. BABYLON.serialize()
  77835. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  77836. __decorate([
  77837. BABYLON.serialize()
  77838. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  77839. __decorate([
  77840. BABYLON.serialize()
  77841. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  77842. __decorate([
  77843. BABYLON.serialize()
  77844. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  77845. __decorate([
  77846. BABYLON.serialize()
  77847. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  77848. __decorate([
  77849. BABYLON.serialize()
  77850. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  77851. __decorate([
  77852. BABYLON.serialize()
  77853. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  77854. __decorate([
  77855. BABYLON.serialize()
  77856. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  77857. __decorate([
  77858. BABYLON.serialize()
  77859. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  77860. __decorate([
  77861. BABYLON.serialize()
  77862. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  77863. __decorate([
  77864. BABYLON.serialize()
  77865. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  77866. __decorate([
  77867. BABYLON.serialize()
  77868. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  77869. return StandardRenderingPipeline;
  77870. }(BABYLON.PostProcessRenderPipeline));
  77871. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  77872. })(BABYLON || (BABYLON = {}));
  77873. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  77874. var BABYLON;
  77875. (function (BABYLON) {
  77876. var FxaaPostProcess = /** @class */ (function (_super) {
  77877. __extends(FxaaPostProcess, _super);
  77878. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  77879. if (camera === void 0) { camera = null; }
  77880. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77881. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  77882. var defines = _this._getDefines();
  77883. _this.updateEffect(defines);
  77884. _this.onApplyObservable.add(function (effect) {
  77885. var texelSize = _this.texelSize;
  77886. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  77887. });
  77888. return _this;
  77889. }
  77890. FxaaPostProcess.prototype._getDefines = function () {
  77891. var engine = this.getEngine();
  77892. if (!engine) {
  77893. return null;
  77894. }
  77895. var glInfo = engine.getGlInfo();
  77896. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  77897. return "#define MALI 1\n";
  77898. }
  77899. return null;
  77900. };
  77901. return FxaaPostProcess;
  77902. }(BABYLON.PostProcess));
  77903. BABYLON.FxaaPostProcess = FxaaPostProcess;
  77904. })(BABYLON || (BABYLON = {}));
  77905. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  77906. var BABYLON;
  77907. (function (BABYLON) {
  77908. /**
  77909. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  77910. */
  77911. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  77912. __extends(ChromaticAberrationPostProcess, _super);
  77913. /**
  77914. * Creates a new instance ChromaticAberrationPostProcess
  77915. * @param name The name of the effect.
  77916. * @param screenWidth The width of the screen to apply the effect on.
  77917. * @param screenHeight The height of the screen to apply the effect on.
  77918. * @param options The required width/height ratio to downsize to before computing the render pass.
  77919. * @param camera The camera to apply the render pass to.
  77920. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77921. * @param engine The engine which the post process will be applied. (default: current engine)
  77922. * @param reusable If the post process can be reused on the same frame. (default: false)
  77923. * @param textureType Type of textures used when performing the post process. (default: 0)
  77924. * @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)
  77925. */
  77926. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77927. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77928. if (blockCompilation === void 0) { blockCompilation = false; }
  77929. 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;
  77930. /**
  77931. * The amount of seperation of rgb channels (default: 30)
  77932. */
  77933. _this.aberrationAmount = 30;
  77934. /**
  77935. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  77936. */
  77937. _this.radialIntensity = 0;
  77938. /**
  77939. * 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))
  77940. */
  77941. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  77942. /**
  77943. * 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))
  77944. */
  77945. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  77946. _this.onApplyObservable.add(function (effect) {
  77947. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  77948. effect.setFloat('screen_width', screenWidth);
  77949. effect.setFloat('screen_height', screenHeight);
  77950. effect.setFloat('radialIntensity', _this.radialIntensity);
  77951. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  77952. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  77953. });
  77954. return _this;
  77955. }
  77956. return ChromaticAberrationPostProcess;
  77957. }(BABYLON.PostProcess));
  77958. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  77959. })(BABYLON || (BABYLON = {}));
  77960. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  77961. var BABYLON;
  77962. (function (BABYLON) {
  77963. /**
  77964. * The GrainPostProcess adds noise to the image at mid luminance levels
  77965. */
  77966. var GrainPostProcess = /** @class */ (function (_super) {
  77967. __extends(GrainPostProcess, _super);
  77968. /**
  77969. * Creates a new instance of @see GrainPostProcess
  77970. * @param name The name of the effect.
  77971. * @param options The required width/height ratio to downsize to before computing the render pass.
  77972. * @param camera The camera to apply the render pass to.
  77973. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  77974. * @param engine The engine which the post process will be applied. (default: current engine)
  77975. * @param reusable If the post process can be reused on the same frame. (default: false)
  77976. * @param textureType Type of textures used when performing the post process. (default: 0)
  77977. * @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)
  77978. */
  77979. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  77980. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77981. if (blockCompilation === void 0) { blockCompilation = false; }
  77982. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  77983. /**
  77984. * The intensity of the grain added (default: 30)
  77985. */
  77986. _this.intensity = 30;
  77987. /**
  77988. * If the grain should be randomized on every frame
  77989. */
  77990. _this.animated = false;
  77991. _this.onApplyObservable.add(function (effect) {
  77992. effect.setFloat('intensity', _this.intensity);
  77993. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  77994. });
  77995. return _this;
  77996. }
  77997. return GrainPostProcess;
  77998. }(BABYLON.PostProcess));
  77999. BABYLON.GrainPostProcess = GrainPostProcess;
  78000. })(BABYLON || (BABYLON = {}));
  78001. //# sourceMappingURL=babylon.grainPostProcess.js.map
  78002. var BABYLON;
  78003. (function (BABYLON) {
  78004. /**
  78005. * The SharpenPostProcess applies a sharpen kernel to every pixel
  78006. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  78007. */
  78008. var SharpenPostProcess = /** @class */ (function (_super) {
  78009. __extends(SharpenPostProcess, _super);
  78010. /**
  78011. * Creates a new instance ConvolutionPostProcess
  78012. * @param name The name of the effect.
  78013. * @param options The required width/height ratio to downsize to before computing the render pass.
  78014. * @param camera The camera to apply the render pass to.
  78015. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78016. * @param engine The engine which the post process will be applied. (default: current engine)
  78017. * @param reusable If the post process can be reused on the same frame. (default: false)
  78018. * @param textureType Type of textures used when performing the post process. (default: 0)
  78019. * @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)
  78020. */
  78021. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  78022. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78023. if (blockCompilation === void 0) { blockCompilation = false; }
  78024. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  78025. /**
  78026. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  78027. */
  78028. _this.colorAmount = 1.0;
  78029. /**
  78030. * How much sharpness should be applied (default: 0.3)
  78031. */
  78032. _this.edgeAmount = 0.3;
  78033. _this.onApply = function (effect) {
  78034. effect.setFloat2("screenSize", _this.width, _this.height);
  78035. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  78036. };
  78037. return _this;
  78038. }
  78039. return SharpenPostProcess;
  78040. }(BABYLON.PostProcess));
  78041. BABYLON.SharpenPostProcess = SharpenPostProcess;
  78042. })(BABYLON || (BABYLON = {}));
  78043. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  78044. var BABYLON;
  78045. (function (BABYLON) {
  78046. /**
  78047. * The Blur Post Process which blurs an image based on a kernel and direction.
  78048. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  78049. */
  78050. var BlurPostProcess = /** @class */ (function (_super) {
  78051. __extends(BlurPostProcess, _super);
  78052. /**
  78053. * Creates a new instance BlurPostProcess
  78054. * @param name The name of the effect.
  78055. * @param direction The direction in which to blur the image.
  78056. * @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.
  78057. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  78058. * @param camera The camera to apply the render pass to.
  78059. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78060. * @param engine The engine which the post process will be applied. (default: current engine)
  78061. * @param reusable If the post process can be reused on the same frame. (default: false)
  78062. * @param textureType Type of textures used when performing the post process. (default: 0)
  78063. * @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)
  78064. */
  78065. function BlurPostProcess(name,
  78066. /** The direction in which to blur the image. */
  78067. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  78068. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  78069. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78070. if (defines === void 0) { defines = ""; }
  78071. if (blockCompilation === void 0) { blockCompilation = false; }
  78072. 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;
  78073. _this.direction = direction;
  78074. _this.blockCompilation = blockCompilation;
  78075. _this._packedFloat = false;
  78076. _this._staticDefines = "";
  78077. _this._staticDefines = defines;
  78078. _this.onApplyObservable.add(function (effect) {
  78079. if (_this._outputTexture) {
  78080. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  78081. }
  78082. else {
  78083. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  78084. }
  78085. });
  78086. _this.kernel = kernel;
  78087. return _this;
  78088. }
  78089. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  78090. /**
  78091. * Gets the length in pixels of the blur sample region
  78092. */
  78093. get: function () {
  78094. return this._idealKernel;
  78095. },
  78096. /**
  78097. * Sets the length in pixels of the blur sample region
  78098. */
  78099. set: function (v) {
  78100. if (this._idealKernel === v) {
  78101. return;
  78102. }
  78103. v = Math.max(v, 1);
  78104. this._idealKernel = v;
  78105. this._kernel = this._nearestBestKernel(v);
  78106. if (!this.blockCompilation) {
  78107. this._updateParameters();
  78108. }
  78109. },
  78110. enumerable: true,
  78111. configurable: true
  78112. });
  78113. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  78114. /**
  78115. * Gets wether or not the blur is unpacking/repacking floats
  78116. */
  78117. get: function () {
  78118. return this._packedFloat;
  78119. },
  78120. /**
  78121. * Sets wether or not the blur needs to unpack/repack floats
  78122. */
  78123. set: function (v) {
  78124. if (this._packedFloat === v) {
  78125. return;
  78126. }
  78127. this._packedFloat = v;
  78128. if (!this.blockCompilation) {
  78129. this._updateParameters();
  78130. }
  78131. },
  78132. enumerable: true,
  78133. configurable: true
  78134. });
  78135. /**
  78136. * Updates the effect with the current post process compile time values and recompiles the shader.
  78137. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  78138. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  78139. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  78140. * @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
  78141. * @param onCompiled Called when the shader has been compiled.
  78142. * @param onError Called if there is an error when compiling a shader.
  78143. */
  78144. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  78145. if (defines === void 0) { defines = null; }
  78146. if (uniforms === void 0) { uniforms = null; }
  78147. if (samplers === void 0) { samplers = null; }
  78148. this._updateParameters(onCompiled, onError);
  78149. };
  78150. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  78151. // Generate sampling offsets and weights
  78152. var N = this._kernel;
  78153. var centerIndex = (N - 1) / 2;
  78154. // Generate Gaussian sampling weights over kernel
  78155. var offsets = [];
  78156. var weights = [];
  78157. var totalWeight = 0;
  78158. for (var i = 0; i < N; i++) {
  78159. var u = i / (N - 1);
  78160. var w = this._gaussianWeight(u * 2.0 - 1);
  78161. offsets[i] = (i - centerIndex);
  78162. weights[i] = w;
  78163. totalWeight += w;
  78164. }
  78165. // Normalize weights
  78166. for (var i = 0; i < weights.length; i++) {
  78167. weights[i] /= totalWeight;
  78168. }
  78169. // Optimize: combine samples to take advantage of hardware linear sampling
  78170. // Walk from left to center, combining pairs (symmetrically)
  78171. var linearSamplingWeights = [];
  78172. var linearSamplingOffsets = [];
  78173. var linearSamplingMap = [];
  78174. for (var i = 0; i <= centerIndex; i += 2) {
  78175. var j = Math.min(i + 1, Math.floor(centerIndex));
  78176. var singleCenterSample = i === j;
  78177. if (singleCenterSample) {
  78178. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  78179. }
  78180. else {
  78181. var sharedCell = j === centerIndex;
  78182. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  78183. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  78184. if (offsetLinear === 0) {
  78185. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  78186. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  78187. }
  78188. else {
  78189. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  78190. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  78191. }
  78192. }
  78193. }
  78194. for (var i = 0; i < linearSamplingMap.length; i++) {
  78195. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  78196. linearSamplingWeights[i] = linearSamplingMap[i].w;
  78197. }
  78198. // Replace with optimized
  78199. offsets = linearSamplingOffsets;
  78200. weights = linearSamplingWeights;
  78201. // Generate shaders
  78202. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  78203. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  78204. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  78205. var defines = "";
  78206. defines += this._staticDefines;
  78207. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  78208. if (this._staticDefines.indexOf("DOF") != -1) {
  78209. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  78210. varyingCount--;
  78211. }
  78212. for (var i = 0; i < varyingCount; i++) {
  78213. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  78214. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  78215. }
  78216. var depCount = 0;
  78217. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  78218. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  78219. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  78220. depCount++;
  78221. }
  78222. if (this.packedFloat) {
  78223. defines += "#define PACKEDFLOAT 1";
  78224. }
  78225. this.blockCompilation = false;
  78226. _super.prototype.updateEffect.call(this, defines, null, null, {
  78227. varyingCount: varyingCount,
  78228. depCount: depCount
  78229. }, onCompiled, onError);
  78230. };
  78231. /**
  78232. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  78233. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  78234. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  78235. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  78236. * The gaps between physical kernels are compensated for in the weighting of the samples
  78237. * @param idealKernel Ideal blur kernel.
  78238. * @return Nearest best kernel.
  78239. */
  78240. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  78241. var v = Math.round(idealKernel);
  78242. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  78243. var k = _a[_i];
  78244. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  78245. return Math.max(k, 3);
  78246. }
  78247. }
  78248. return Math.max(v, 3);
  78249. };
  78250. /**
  78251. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  78252. * @param x The point on the Gaussian distribution to sample.
  78253. * @return the value of the Gaussian function at x.
  78254. */
  78255. BlurPostProcess.prototype._gaussianWeight = function (x) {
  78256. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  78257. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  78258. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  78259. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  78260. // truncated at around 1.3% of peak strength.
  78261. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  78262. var sigma = (1 / 3);
  78263. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  78264. var exponent = -((x * x) / (2.0 * sigma * sigma));
  78265. var weight = (1.0 / denominator) * Math.exp(exponent);
  78266. return weight;
  78267. };
  78268. /**
  78269. * Generates a string that can be used as a floating point number in GLSL.
  78270. * @param x Value to print.
  78271. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  78272. * @return GLSL float string.
  78273. */
  78274. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  78275. if (decimalFigures === void 0) { decimalFigures = 8; }
  78276. return x.toFixed(decimalFigures).replace(/0+$/, '');
  78277. };
  78278. return BlurPostProcess;
  78279. }(BABYLON.PostProcess));
  78280. BABYLON.BlurPostProcess = BlurPostProcess;
  78281. })(BABYLON || (BABYLON = {}));
  78282. //# sourceMappingURL=babylon.blurPostProcess.js.map
  78283. var BABYLON;
  78284. (function (BABYLON) {
  78285. /**
  78286. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  78287. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  78288. * based on samples that have a large difference in distance than the center pixel.
  78289. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  78290. */
  78291. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  78292. __extends(DepthOfFieldBlurPostProcess, _super);
  78293. /**
  78294. * Creates a new instance CircleOfConfusionPostProcess
  78295. * @param name The name of the effect.
  78296. * @param scene The scene the effect belongs to.
  78297. * @param direction The direction the blur should be applied.
  78298. * @param kernel The size of the kernel used to blur.
  78299. * @param options The required width/height ratio to downsize to before computing the render pass.
  78300. * @param camera The camera to apply the render pass to.
  78301. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  78302. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  78303. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78304. * @param engine The engine which the post process will be applied. (default: current engine)
  78305. * @param reusable If the post process can be reused on the same frame. (default: false)
  78306. * @param textureType Type of textures used when performing the post process. (default: 0)
  78307. * @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)
  78308. */
  78309. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  78310. if (imageToBlur === void 0) { imageToBlur = null; }
  78311. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  78312. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78313. if (blockCompilation === void 0) { blockCompilation = false; }
  78314. 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;
  78315. _this.direction = direction;
  78316. _this.onApplyObservable.add(function (effect) {
  78317. if (imageToBlur != null) {
  78318. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  78319. }
  78320. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  78321. if (scene.activeCamera) {
  78322. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  78323. }
  78324. });
  78325. return _this;
  78326. }
  78327. return DepthOfFieldBlurPostProcess;
  78328. }(BABYLON.BlurPostProcess));
  78329. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  78330. })(BABYLON || (BABYLON = {}));
  78331. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  78332. var BABYLON;
  78333. (function (BABYLON) {
  78334. /**
  78335. * Options to be set when merging outputs from the default pipeline.
  78336. */
  78337. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  78338. function DepthOfFieldMergePostProcessOptions() {
  78339. }
  78340. return DepthOfFieldMergePostProcessOptions;
  78341. }());
  78342. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  78343. /**
  78344. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  78345. */
  78346. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  78347. __extends(DepthOfFieldMergePostProcess, _super);
  78348. /**
  78349. * Creates a new instance of DepthOfFieldMergePostProcess
  78350. * @param name The name of the effect.
  78351. * @param originalFromInput Post process which's input will be used for the merge.
  78352. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  78353. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  78354. * @param options The required width/height ratio to downsize to before computing the render pass.
  78355. * @param camera The camera to apply the render pass to.
  78356. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78357. * @param engine The engine which the post process will be applied. (default: current engine)
  78358. * @param reusable If the post process can be reused on the same frame. (default: false)
  78359. * @param textureType Type of textures used when performing the post process. (default: 0)
  78360. * @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)
  78361. */
  78362. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  78363. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78364. if (blockCompilation === void 0) { blockCompilation = false; }
  78365. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  78366. _this.blurSteps = blurSteps;
  78367. _this.onApplyObservable.add(function (effect) {
  78368. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  78369. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  78370. blurSteps.forEach(function (step, index) {
  78371. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  78372. });
  78373. });
  78374. if (!blockCompilation) {
  78375. _this.updateEffect();
  78376. }
  78377. return _this;
  78378. }
  78379. /**
  78380. * Updates the effect with the current post process compile time values and recompiles the shader.
  78381. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  78382. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  78383. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  78384. * @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
  78385. * @param onCompiled Called when the shader has been compiled.
  78386. * @param onError Called if there is an error when compiling a shader.
  78387. */
  78388. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  78389. if (defines === void 0) { defines = null; }
  78390. if (uniforms === void 0) { uniforms = null; }
  78391. if (samplers === void 0) { samplers = null; }
  78392. if (!defines) {
  78393. defines = "";
  78394. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  78395. }
  78396. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  78397. };
  78398. return DepthOfFieldMergePostProcess;
  78399. }(BABYLON.PostProcess));
  78400. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  78401. })(BABYLON || (BABYLON = {}));
  78402. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  78403. var BABYLON;
  78404. (function (BABYLON) {
  78405. /**
  78406. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  78407. */
  78408. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  78409. __extends(CircleOfConfusionPostProcess, _super);
  78410. /**
  78411. * Creates a new instance CircleOfConfusionPostProcess
  78412. * @param name The name of the effect.
  78413. * @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.
  78414. * @param options The required width/height ratio to downsize to before computing the render pass.
  78415. * @param camera The camera to apply the render pass to.
  78416. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78417. * @param engine The engine which the post process will be applied. (default: current engine)
  78418. * @param reusable If the post process can be reused on the same frame. (default: false)
  78419. * @param textureType Type of textures used when performing the post process. (default: 0)
  78420. * @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)
  78421. */
  78422. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  78423. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78424. if (blockCompilation === void 0) { blockCompilation = false; }
  78425. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  78426. /**
  78427. * 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.
  78428. */
  78429. _this.lensSize = 50;
  78430. /**
  78431. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  78432. */
  78433. _this.fStop = 1.4;
  78434. /**
  78435. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  78436. */
  78437. _this.focusDistance = 2000;
  78438. /**
  78439. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  78440. */
  78441. _this.focalLength = 50;
  78442. _this._depthTexture = null;
  78443. _this._depthTexture = depthTexture;
  78444. _this.onApplyObservable.add(function (effect) {
  78445. if (!_this._depthTexture) {
  78446. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  78447. return;
  78448. }
  78449. effect.setTexture("depthSampler", _this._depthTexture);
  78450. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  78451. var aperture = _this.lensSize / _this.fStop;
  78452. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  78453. effect.setFloat('focusDistance', _this.focusDistance);
  78454. effect.setFloat('cocPrecalculation', cocPrecalculation);
  78455. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  78456. });
  78457. return _this;
  78458. }
  78459. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  78460. /**
  78461. * 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.
  78462. */
  78463. set: function (value) {
  78464. this._depthTexture = value;
  78465. },
  78466. enumerable: true,
  78467. configurable: true
  78468. });
  78469. return CircleOfConfusionPostProcess;
  78470. }(BABYLON.PostProcess));
  78471. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  78472. })(BABYLON || (BABYLON = {}));
  78473. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  78474. var BABYLON;
  78475. (function (BABYLON) {
  78476. /**
  78477. * Specifies the level of max blur that should be applied when using the depth of field effect
  78478. */
  78479. var DepthOfFieldEffectBlurLevel;
  78480. (function (DepthOfFieldEffectBlurLevel) {
  78481. /**
  78482. * Subtle blur
  78483. */
  78484. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  78485. /**
  78486. * Medium blur
  78487. */
  78488. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  78489. /**
  78490. * Large blur
  78491. */
  78492. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  78493. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  78494. ;
  78495. /**
  78496. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  78497. */
  78498. var DepthOfFieldEffect = /** @class */ (function (_super) {
  78499. __extends(DepthOfFieldEffect, _super);
  78500. /**
  78501. * Creates a new instance DepthOfFieldEffect
  78502. * @param scene The scene the effect belongs to.
  78503. * @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.
  78504. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  78505. * @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)
  78506. */
  78507. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  78508. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  78509. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  78510. if (blockCompilation === void 0) { blockCompilation = false; }
  78511. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  78512. return _this._effects;
  78513. }, true) || this;
  78514. /**
  78515. * @hidden Internal post processes in depth of field effect
  78516. */
  78517. _this._effects = [];
  78518. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  78519. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  78520. // 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)
  78521. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  78522. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  78523. _this._depthOfFieldBlurY = [];
  78524. _this._depthOfFieldBlurX = [];
  78525. var blurCount = 1;
  78526. var kernelSize = 15;
  78527. switch (blurLevel) {
  78528. case DepthOfFieldEffectBlurLevel.High: {
  78529. blurCount = 3;
  78530. kernelSize = 51;
  78531. break;
  78532. }
  78533. case DepthOfFieldEffectBlurLevel.Medium: {
  78534. blurCount = 2;
  78535. kernelSize = 31;
  78536. break;
  78537. }
  78538. default: {
  78539. kernelSize = 15;
  78540. blurCount = 1;
  78541. break;
  78542. }
  78543. }
  78544. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  78545. var ratio = 1.0;
  78546. for (var i = 0; i < blurCount; i++) {
  78547. 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);
  78548. blurY.autoClear = false;
  78549. ratio = 0.75 / Math.pow(2, i);
  78550. 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);
  78551. blurX.autoClear = false;
  78552. _this._depthOfFieldBlurY.push(blurY);
  78553. _this._depthOfFieldBlurX.push(blurX);
  78554. }
  78555. // Set all post processes on the effect.
  78556. _this._effects = [_this._circleOfConfusion];
  78557. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  78558. _this._effects.push(_this._depthOfFieldBlurY[i]);
  78559. _this._effects.push(_this._depthOfFieldBlurX[i]);
  78560. }
  78561. // Merge blurred images with original image based on circleOfConfusion
  78562. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  78563. _this._dofMerge.autoClear = false;
  78564. _this._effects.push(_this._dofMerge);
  78565. return _this;
  78566. }
  78567. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  78568. get: function () {
  78569. return this._circleOfConfusion.focalLength;
  78570. },
  78571. /**
  78572. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  78573. */
  78574. set: function (value) {
  78575. this._circleOfConfusion.focalLength = value;
  78576. },
  78577. enumerable: true,
  78578. configurable: true
  78579. });
  78580. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  78581. get: function () {
  78582. return this._circleOfConfusion.fStop;
  78583. },
  78584. /**
  78585. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  78586. */
  78587. set: function (value) {
  78588. this._circleOfConfusion.fStop = value;
  78589. },
  78590. enumerable: true,
  78591. configurable: true
  78592. });
  78593. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  78594. get: function () {
  78595. return this._circleOfConfusion.focusDistance;
  78596. },
  78597. /**
  78598. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  78599. */
  78600. set: function (value) {
  78601. this._circleOfConfusion.focusDistance = value;
  78602. },
  78603. enumerable: true,
  78604. configurable: true
  78605. });
  78606. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  78607. get: function () {
  78608. return this._circleOfConfusion.lensSize;
  78609. },
  78610. /**
  78611. * 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.
  78612. */
  78613. set: function (value) {
  78614. this._circleOfConfusion.lensSize = value;
  78615. },
  78616. enumerable: true,
  78617. configurable: true
  78618. });
  78619. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  78620. /**
  78621. * 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.
  78622. */
  78623. set: function (value) {
  78624. this._circleOfConfusion.depthTexture = value;
  78625. },
  78626. enumerable: true,
  78627. configurable: true
  78628. });
  78629. /**
  78630. * Disposes each of the internal effects for a given camera.
  78631. * @param camera The camera to dispose the effect on.
  78632. */
  78633. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  78634. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  78635. this._effects[effectIndex].dispose(camera);
  78636. }
  78637. };
  78638. /**
  78639. * @hidden Internal
  78640. */
  78641. DepthOfFieldEffect.prototype._updateEffects = function () {
  78642. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  78643. this._effects[effectIndex].updateEffect();
  78644. }
  78645. };
  78646. /**
  78647. * Internal
  78648. * @returns if all the contained post processes are ready.
  78649. * @hidden
  78650. */
  78651. DepthOfFieldEffect.prototype._isReady = function () {
  78652. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  78653. if (!this._effects[effectIndex].isReady()) {
  78654. return false;
  78655. }
  78656. }
  78657. return true;
  78658. };
  78659. return DepthOfFieldEffect;
  78660. }(BABYLON.PostProcessRenderEffect));
  78661. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  78662. })(BABYLON || (BABYLON = {}));
  78663. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  78664. var BABYLON;
  78665. (function (BABYLON) {
  78666. /**
  78667. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  78668. */
  78669. var BloomMergePostProcess = /** @class */ (function (_super) {
  78670. __extends(BloomMergePostProcess, _super);
  78671. /**
  78672. * Creates a new instance of @see BloomMergePostProcess
  78673. * @param name The name of the effect.
  78674. * @param originalFromInput Post process which's input will be used for the merge.
  78675. * @param blurred Blurred highlights post process which's output will be used.
  78676. * @param weight Weight of the bloom to be added to the original input.
  78677. * @param options The required width/height ratio to downsize to before computing the render pass.
  78678. * @param camera The camera to apply the render pass to.
  78679. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78680. * @param engine The engine which the post process will be applied. (default: current engine)
  78681. * @param reusable If the post process can be reused on the same frame. (default: false)
  78682. * @param textureType Type of textures used when performing the post process. (default: 0)
  78683. * @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)
  78684. */
  78685. function BloomMergePostProcess(name, originalFromInput, blurred,
  78686. /** Weight of the bloom to be added to the original input. */
  78687. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  78688. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78689. if (blockCompilation === void 0) { blockCompilation = false; }
  78690. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  78691. _this.weight = weight;
  78692. _this.onApplyObservable.add(function (effect) {
  78693. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  78694. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  78695. effect.setFloat("bloomWeight", _this.weight);
  78696. });
  78697. if (!blockCompilation) {
  78698. _this.updateEffect();
  78699. }
  78700. return _this;
  78701. }
  78702. return BloomMergePostProcess;
  78703. }(BABYLON.PostProcess));
  78704. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  78705. })(BABYLON || (BABYLON = {}));
  78706. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  78707. var BABYLON;
  78708. (function (BABYLON) {
  78709. /**
  78710. * 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.
  78711. */
  78712. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  78713. __extends(ExtractHighlightsPostProcess, _super);
  78714. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  78715. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78716. if (blockCompilation === void 0) { blockCompilation = false; }
  78717. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  78718. /**
  78719. * The luminance threshold, pixels below this value will be set to black.
  78720. */
  78721. _this.threshold = 0.9;
  78722. /** @hidden */
  78723. _this._exposure = 1;
  78724. /**
  78725. * Post process which has the input texture to be used when performing highlight extraction
  78726. * @hidden
  78727. */
  78728. _this._inputPostProcess = null;
  78729. _this.onApplyObservable.add(function (effect) {
  78730. if (_this._inputPostProcess) {
  78731. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  78732. }
  78733. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  78734. effect.setFloat('exposure', _this._exposure);
  78735. });
  78736. return _this;
  78737. }
  78738. return ExtractHighlightsPostProcess;
  78739. }(BABYLON.PostProcess));
  78740. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  78741. })(BABYLON || (BABYLON = {}));
  78742. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  78743. var BABYLON;
  78744. (function (BABYLON) {
  78745. /**
  78746. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  78747. */
  78748. var BloomEffect = /** @class */ (function (_super) {
  78749. __extends(BloomEffect, _super);
  78750. /**
  78751. * Creates a new instance of @see BloomEffect
  78752. * @param scene The scene the effect belongs to.
  78753. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  78754. * @param bloomKernel The size of the kernel to be used when applying the blur.
  78755. * @param bloomWeight The the strength of bloom.
  78756. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  78757. * @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)
  78758. */
  78759. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  78760. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  78761. if (blockCompilation === void 0) { blockCompilation = false; }
  78762. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  78763. return _this._effects;
  78764. }, true) || this;
  78765. _this.bloomScale = bloomScale;
  78766. /**
  78767. * @hidden Internal
  78768. */
  78769. _this._effects = [];
  78770. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  78771. _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);
  78772. _this._blurX.alwaysForcePOT = true;
  78773. _this._blurX.autoClear = false;
  78774. _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);
  78775. _this._blurY.alwaysForcePOT = true;
  78776. _this._blurY.autoClear = false;
  78777. _this.kernel = bloomKernel;
  78778. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  78779. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  78780. _this._merge.autoClear = false;
  78781. _this._effects.push(_this._merge);
  78782. return _this;
  78783. }
  78784. Object.defineProperty(BloomEffect.prototype, "threshold", {
  78785. /**
  78786. * The luminance threshold to find bright areas of the image to bloom.
  78787. */
  78788. get: function () {
  78789. return this._downscale.threshold;
  78790. },
  78791. set: function (value) {
  78792. this._downscale.threshold = value;
  78793. },
  78794. enumerable: true,
  78795. configurable: true
  78796. });
  78797. Object.defineProperty(BloomEffect.prototype, "weight", {
  78798. /**
  78799. * The strength of the bloom.
  78800. */
  78801. get: function () {
  78802. return this._merge.weight;
  78803. },
  78804. set: function (value) {
  78805. this._merge.weight = value;
  78806. },
  78807. enumerable: true,
  78808. configurable: true
  78809. });
  78810. Object.defineProperty(BloomEffect.prototype, "kernel", {
  78811. /**
  78812. * Specifies the size of the bloom blur kernel, relative to the final output size
  78813. */
  78814. get: function () {
  78815. return this._blurX.kernel / this.bloomScale;
  78816. },
  78817. set: function (value) {
  78818. this._blurX.kernel = value * this.bloomScale;
  78819. this._blurY.kernel = value * this.bloomScale;
  78820. },
  78821. enumerable: true,
  78822. configurable: true
  78823. });
  78824. /**
  78825. * Disposes each of the internal effects for a given camera.
  78826. * @param camera The camera to dispose the effect on.
  78827. */
  78828. BloomEffect.prototype.disposeEffects = function (camera) {
  78829. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  78830. this._effects[effectIndex].dispose(camera);
  78831. }
  78832. };
  78833. /**
  78834. * @hidden Internal
  78835. */
  78836. BloomEffect.prototype._updateEffects = function () {
  78837. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  78838. this._effects[effectIndex].updateEffect();
  78839. }
  78840. };
  78841. /**
  78842. * Internal
  78843. * @returns if all the contained post processes are ready.
  78844. * @hidden
  78845. */
  78846. BloomEffect.prototype._isReady = function () {
  78847. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  78848. if (!this._effects[effectIndex].isReady()) {
  78849. return false;
  78850. }
  78851. }
  78852. return true;
  78853. };
  78854. return BloomEffect;
  78855. }(BABYLON.PostProcessRenderEffect));
  78856. BABYLON.BloomEffect = BloomEffect;
  78857. })(BABYLON || (BABYLON = {}));
  78858. //# sourceMappingURL=babylon.bloomEffect.js.map
  78859. var BABYLON;
  78860. (function (BABYLON) {
  78861. /**
  78862. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  78863. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  78864. */
  78865. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  78866. __extends(DefaultRenderingPipeline, _super);
  78867. /**
  78868. * @constructor
  78869. * @param {string} name - The rendering pipeline name (default: "")
  78870. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  78871. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  78872. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  78873. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  78874. */
  78875. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  78876. if (name === void 0) { name = ""; }
  78877. if (hdr === void 0) { hdr = true; }
  78878. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  78879. if (automaticBuild === void 0) { automaticBuild = true; }
  78880. var _this = _super.call(this, scene.getEngine(), name) || this;
  78881. _this._camerasToBeAttached = [];
  78882. /**
  78883. * ID of the sharpen post process,
  78884. */
  78885. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  78886. /**
  78887. * ID of the image processing post process;
  78888. */
  78889. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  78890. /**
  78891. * ID of the Fast Approximate Anti-Aliasing post process;
  78892. */
  78893. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  78894. /**
  78895. * ID of the chromatic aberration post process,
  78896. */
  78897. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  78898. /**
  78899. * ID of the grain post process
  78900. */
  78901. _this.GrainPostProcessId = "GrainPostProcessEffect";
  78902. /**
  78903. * Glow post process which adds a glow to emmisive areas of the image
  78904. */
  78905. _this._glowLayer = null;
  78906. /**
  78907. * Animations which can be used to tweak settings over a period of time
  78908. */
  78909. _this.animations = [];
  78910. _this._imageProcessingConfigurationObserver = null;
  78911. // Values
  78912. _this._sharpenEnabled = false;
  78913. _this._bloomEnabled = false;
  78914. _this._depthOfFieldEnabled = false;
  78915. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  78916. _this._fxaaEnabled = false;
  78917. _this._imageProcessingEnabled = true;
  78918. _this._bloomScale = 0.5;
  78919. _this._chromaticAberrationEnabled = false;
  78920. _this._grainEnabled = false;
  78921. _this._buildAllowed = true;
  78922. _this._resizeObserver = null;
  78923. _this._hardwareScaleLevel = 1.0;
  78924. _this._bloomKernel = 64;
  78925. /**
  78926. * Specifies the weight of the bloom in the final rendering
  78927. */
  78928. _this._bloomWeight = 0.15;
  78929. /**
  78930. * Specifies the luma threshold for the area that will be blurred by the bloom
  78931. */
  78932. _this._bloomThreshold = 0.9;
  78933. _this._samples = 1;
  78934. _this._hasCleared = false;
  78935. _this._prevPostProcess = null;
  78936. _this._prevPrevPostProcess = null;
  78937. _this._cameras = cameras || scene.cameras;
  78938. _this._cameras = _this._cameras.slice();
  78939. _this._camerasToBeAttached = _this._cameras.slice();
  78940. _this._buildAllowed = automaticBuild;
  78941. // Initialize
  78942. _this._scene = scene;
  78943. var caps = _this._scene.getEngine().getCaps();
  78944. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  78945. // Misc
  78946. if (_this._hdr) {
  78947. if (caps.textureHalfFloatRender) {
  78948. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  78949. }
  78950. else if (caps.textureFloatRender) {
  78951. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  78952. }
  78953. }
  78954. else {
  78955. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  78956. }
  78957. // Attach
  78958. scene.postProcessRenderPipelineManager.addPipeline(_this);
  78959. var engine = _this._scene.getEngine();
  78960. // Create post processes before hand so they can be modified before enabled.
  78961. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  78962. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  78963. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  78964. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  78965. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  78966. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  78967. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  78968. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  78969. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  78970. _this._resizeObserver = engine.onResizeObservable.add(function () {
  78971. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  78972. _this.bloomKernel = _this.bloomKernel;
  78973. });
  78974. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  78975. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  78976. });
  78977. _this._buildPipeline();
  78978. return _this;
  78979. }
  78980. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  78981. get: function () {
  78982. return this._sharpenEnabled;
  78983. },
  78984. /**
  78985. * Enable or disable the sharpen process from the pipeline
  78986. */
  78987. set: function (enabled) {
  78988. if (this._sharpenEnabled === enabled) {
  78989. return;
  78990. }
  78991. this._sharpenEnabled = enabled;
  78992. this._buildPipeline();
  78993. },
  78994. enumerable: true,
  78995. configurable: true
  78996. });
  78997. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  78998. /**
  78999. * Specifies the size of the bloom blur kernel, relative to the final output size
  79000. */
  79001. get: function () {
  79002. return this._bloomKernel;
  79003. },
  79004. set: function (value) {
  79005. this._bloomKernel = value;
  79006. this.bloom.kernel = value / this._hardwareScaleLevel;
  79007. },
  79008. enumerable: true,
  79009. configurable: true
  79010. });
  79011. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  79012. get: function () {
  79013. return this._bloomWeight;
  79014. },
  79015. /**
  79016. * The strength of the bloom.
  79017. */
  79018. set: function (value) {
  79019. if (this._bloomWeight === value) {
  79020. return;
  79021. }
  79022. this.bloom.weight = value;
  79023. this._bloomWeight = value;
  79024. },
  79025. enumerable: true,
  79026. configurable: true
  79027. });
  79028. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  79029. get: function () {
  79030. return this._bloomThreshold;
  79031. },
  79032. /**
  79033. * The strength of the bloom.
  79034. */
  79035. set: function (value) {
  79036. if (this._bloomThreshold === value) {
  79037. return;
  79038. }
  79039. this.bloom.threshold = value;
  79040. this._bloomThreshold = value;
  79041. },
  79042. enumerable: true,
  79043. configurable: true
  79044. });
  79045. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  79046. get: function () {
  79047. return this._bloomScale;
  79048. },
  79049. /**
  79050. * The scale of the bloom, lower value will provide better performance.
  79051. */
  79052. set: function (value) {
  79053. if (this._bloomScale === value) {
  79054. return;
  79055. }
  79056. this._bloomScale = value;
  79057. // recreate bloom and dispose old as this setting is not dynamic
  79058. this._rebuildBloom();
  79059. this._buildPipeline();
  79060. },
  79061. enumerable: true,
  79062. configurable: true
  79063. });
  79064. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  79065. get: function () {
  79066. return this._bloomEnabled;
  79067. },
  79068. /**
  79069. * Enable or disable the bloom from the pipeline
  79070. */
  79071. set: function (enabled) {
  79072. if (this._bloomEnabled === enabled) {
  79073. return;
  79074. }
  79075. this._bloomEnabled = enabled;
  79076. this._buildPipeline();
  79077. },
  79078. enumerable: true,
  79079. configurable: true
  79080. });
  79081. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  79082. // recreate bloom and dispose old as this setting is not dynamic
  79083. var oldBloom = this.bloom;
  79084. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  79085. this.bloom.threshold = oldBloom.threshold;
  79086. for (var i = 0; i < this._cameras.length; i++) {
  79087. oldBloom.disposeEffects(this._cameras[i]);
  79088. }
  79089. };
  79090. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  79091. /**
  79092. * If the depth of field is enabled.
  79093. */
  79094. get: function () {
  79095. return this._depthOfFieldEnabled;
  79096. },
  79097. set: function (enabled) {
  79098. if (this._depthOfFieldEnabled === enabled) {
  79099. return;
  79100. }
  79101. this._depthOfFieldEnabled = enabled;
  79102. this._buildPipeline();
  79103. },
  79104. enumerable: true,
  79105. configurable: true
  79106. });
  79107. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  79108. /**
  79109. * Blur level of the depth of field effect. (Higher blur will effect performance)
  79110. */
  79111. get: function () {
  79112. return this._depthOfFieldBlurLevel;
  79113. },
  79114. set: function (value) {
  79115. if (this._depthOfFieldBlurLevel === value) {
  79116. return;
  79117. }
  79118. this._depthOfFieldBlurLevel = value;
  79119. // recreate dof and dispose old as this setting is not dynamic
  79120. var oldDof = this.depthOfField;
  79121. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  79122. this.depthOfField.focalLength = oldDof.focalLength;
  79123. this.depthOfField.focusDistance = oldDof.focusDistance;
  79124. this.depthOfField.fStop = oldDof.fStop;
  79125. this.depthOfField.lensSize = oldDof.lensSize;
  79126. for (var i = 0; i < this._cameras.length; i++) {
  79127. oldDof.disposeEffects(this._cameras[i]);
  79128. }
  79129. this._buildPipeline();
  79130. },
  79131. enumerable: true,
  79132. configurable: true
  79133. });
  79134. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  79135. get: function () {
  79136. return this._fxaaEnabled;
  79137. },
  79138. /**
  79139. * If the anti aliasing is enabled.
  79140. */
  79141. set: function (enabled) {
  79142. if (this._fxaaEnabled === enabled) {
  79143. return;
  79144. }
  79145. this._fxaaEnabled = enabled;
  79146. this._buildPipeline();
  79147. },
  79148. enumerable: true,
  79149. configurable: true
  79150. });
  79151. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  79152. get: function () {
  79153. return this._samples;
  79154. },
  79155. /**
  79156. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  79157. */
  79158. set: function (sampleCount) {
  79159. if (this._samples === sampleCount) {
  79160. return;
  79161. }
  79162. this._samples = sampleCount;
  79163. this._buildPipeline();
  79164. },
  79165. enumerable: true,
  79166. configurable: true
  79167. });
  79168. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  79169. get: function () {
  79170. return this._imageProcessingEnabled;
  79171. },
  79172. /**
  79173. * If image processing is enabled.
  79174. */
  79175. set: function (enabled) {
  79176. if (this._imageProcessingEnabled === enabled) {
  79177. return;
  79178. }
  79179. this._imageProcessingEnabled = enabled;
  79180. this._buildPipeline();
  79181. },
  79182. enumerable: true,
  79183. configurable: true
  79184. });
  79185. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  79186. get: function () {
  79187. return this._glowLayer == null;
  79188. },
  79189. /**
  79190. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  79191. */
  79192. set: function (enabled) {
  79193. if (enabled && !this._glowLayer) {
  79194. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  79195. }
  79196. else if (!enabled && this._glowLayer) {
  79197. this._glowLayer.dispose();
  79198. this._glowLayer = null;
  79199. }
  79200. },
  79201. enumerable: true,
  79202. configurable: true
  79203. });
  79204. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  79205. get: function () {
  79206. return this._chromaticAberrationEnabled;
  79207. },
  79208. /**
  79209. * Enable or disable the chromaticAberration process from the pipeline
  79210. */
  79211. set: function (enabled) {
  79212. if (this._chromaticAberrationEnabled === enabled) {
  79213. return;
  79214. }
  79215. this._chromaticAberrationEnabled = enabled;
  79216. this._buildPipeline();
  79217. },
  79218. enumerable: true,
  79219. configurable: true
  79220. });
  79221. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  79222. get: function () {
  79223. return this._grainEnabled;
  79224. },
  79225. /**
  79226. * Enable or disable the grain process from the pipeline
  79227. */
  79228. set: function (enabled) {
  79229. if (this._grainEnabled === enabled) {
  79230. return;
  79231. }
  79232. this._grainEnabled = enabled;
  79233. this._buildPipeline();
  79234. },
  79235. enumerable: true,
  79236. configurable: true
  79237. });
  79238. /**
  79239. * Force the compilation of the entire pipeline.
  79240. */
  79241. DefaultRenderingPipeline.prototype.prepare = function () {
  79242. var previousState = this._buildAllowed;
  79243. this._buildAllowed = true;
  79244. this._buildPipeline();
  79245. this._buildAllowed = previousState;
  79246. };
  79247. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  79248. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  79249. if (this._hasCleared) {
  79250. postProcess.autoClear = false;
  79251. }
  79252. else {
  79253. postProcess.autoClear = true;
  79254. this._scene.autoClear = false;
  79255. this._hasCleared = true;
  79256. }
  79257. if (!skipTextureSharing) {
  79258. if (this._prevPrevPostProcess) {
  79259. postProcess.shareOutputWith(this._prevPrevPostProcess);
  79260. }
  79261. else {
  79262. postProcess.useOwnOutput();
  79263. }
  79264. if (this._prevPostProcess) {
  79265. this._prevPrevPostProcess = this._prevPostProcess;
  79266. }
  79267. this._prevPostProcess = postProcess;
  79268. }
  79269. };
  79270. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  79271. var _this = this;
  79272. if (!this._buildAllowed) {
  79273. return;
  79274. }
  79275. this._scene.autoClear = true;
  79276. var engine = this._scene.getEngine();
  79277. this._disposePostProcesses();
  79278. if (this._cameras !== null) {
  79279. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  79280. // get back cameras to be used to reattach pipeline
  79281. this._cameras = this._camerasToBeAttached.slice();
  79282. }
  79283. this._reset();
  79284. this._prevPostProcess = null;
  79285. this._prevPrevPostProcess = null;
  79286. this._hasCleared = false;
  79287. if (this.depthOfFieldEnabled) {
  79288. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  79289. this.depthOfField.depthTexture = depthTexture;
  79290. if (!this.depthOfField._isReady()) {
  79291. this.depthOfField._updateEffects();
  79292. }
  79293. this.addEffect(this.depthOfField);
  79294. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  79295. }
  79296. if (this.bloomEnabled) {
  79297. if (!this.bloom._isReady()) {
  79298. this.bloom._updateEffects();
  79299. }
  79300. this.addEffect(this.bloom);
  79301. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  79302. }
  79303. if (this._imageProcessingEnabled) {
  79304. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  79305. if (this._hdr) {
  79306. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  79307. this._setAutoClearAndTextureSharing(this.imageProcessing);
  79308. }
  79309. else {
  79310. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  79311. }
  79312. }
  79313. if (this.sharpenEnabled) {
  79314. if (!this.sharpen.isReady()) {
  79315. this.sharpen.updateEffect();
  79316. }
  79317. this.addEffect(this._sharpenEffect);
  79318. this._setAutoClearAndTextureSharing(this.sharpen);
  79319. }
  79320. if (this.grainEnabled) {
  79321. if (!this.grain.isReady()) {
  79322. this.grain.updateEffect();
  79323. }
  79324. this.addEffect(this._grainEffect);
  79325. this._setAutoClearAndTextureSharing(this.grain);
  79326. }
  79327. if (this.chromaticAberrationEnabled) {
  79328. if (!this.chromaticAberration.isReady()) {
  79329. this.chromaticAberration.updateEffect();
  79330. }
  79331. this.addEffect(this._chromaticAberrationEffect);
  79332. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  79333. }
  79334. if (this.fxaaEnabled) {
  79335. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  79336. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  79337. this._setAutoClearAndTextureSharing(this.fxaa, true);
  79338. }
  79339. if (this._cameras !== null) {
  79340. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  79341. }
  79342. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  79343. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  79344. }
  79345. };
  79346. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  79347. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  79348. for (var i = 0; i < this._cameras.length; i++) {
  79349. var camera = this._cameras[i];
  79350. if (this.imageProcessing) {
  79351. this.imageProcessing.dispose(camera);
  79352. }
  79353. if (this.fxaa) {
  79354. this.fxaa.dispose(camera);
  79355. }
  79356. // These are created in the constructor and should not be disposed on every pipeline change
  79357. if (disposeNonRecreated) {
  79358. if (this.sharpen) {
  79359. this.sharpen.dispose(camera);
  79360. }
  79361. if (this.depthOfField) {
  79362. this.depthOfField.disposeEffects(camera);
  79363. }
  79364. if (this.bloom) {
  79365. this.bloom.disposeEffects(camera);
  79366. }
  79367. if (this.chromaticAberration) {
  79368. this.chromaticAberration.dispose(camera);
  79369. }
  79370. if (this.grain) {
  79371. this.grain.dispose(camera);
  79372. }
  79373. if (this._glowLayer) {
  79374. this._glowLayer.dispose();
  79375. }
  79376. }
  79377. }
  79378. this.imageProcessing = null;
  79379. this.fxaa = null;
  79380. if (disposeNonRecreated) {
  79381. this.sharpen = null;
  79382. this._sharpenEffect = null;
  79383. this.depthOfField = null;
  79384. this.bloom = null;
  79385. this.chromaticAberration = null;
  79386. this._chromaticAberrationEffect = null;
  79387. this.grain = null;
  79388. this._grainEffect = null;
  79389. this._glowLayer = null;
  79390. }
  79391. };
  79392. /**
  79393. * Adds a camera to the pipeline
  79394. * @param camera the camera to be added
  79395. */
  79396. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  79397. this._camerasToBeAttached.push(camera);
  79398. this._buildPipeline();
  79399. };
  79400. /**
  79401. * Removes a camera from the pipeline
  79402. * @param camera the camera to remove
  79403. */
  79404. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  79405. var index = this._camerasToBeAttached.indexOf(camera);
  79406. this._camerasToBeAttached.splice(index, 1);
  79407. this._buildPipeline();
  79408. };
  79409. /**
  79410. * Dispose of the pipeline and stop all post processes
  79411. */
  79412. DefaultRenderingPipeline.prototype.dispose = function () {
  79413. this._disposePostProcesses(true);
  79414. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  79415. this._scene.autoClear = true;
  79416. if (this._resizeObserver) {
  79417. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  79418. this._resizeObserver = null;
  79419. }
  79420. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  79421. _super.prototype.dispose.call(this);
  79422. };
  79423. /**
  79424. * Serialize the rendering pipeline (Used when exporting)
  79425. * @returns the serialized object
  79426. */
  79427. DefaultRenderingPipeline.prototype.serialize = function () {
  79428. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  79429. serializationObject.customType = "DefaultRenderingPipeline";
  79430. return serializationObject;
  79431. };
  79432. /**
  79433. * Parse the serialized pipeline
  79434. * @param source Source pipeline.
  79435. * @param scene The scene to load the pipeline to.
  79436. * @param rootUrl The URL of the serialized pipeline.
  79437. * @returns An instantiated pipeline from the serialized object.
  79438. */
  79439. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  79440. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  79441. };
  79442. __decorate([
  79443. BABYLON.serialize()
  79444. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  79445. __decorate([
  79446. BABYLON.serialize()
  79447. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  79448. __decorate([
  79449. BABYLON.serialize()
  79450. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  79451. __decorate([
  79452. BABYLON.serialize()
  79453. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  79454. __decorate([
  79455. BABYLON.serialize()
  79456. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  79457. __decorate([
  79458. BABYLON.serialize()
  79459. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  79460. __decorate([
  79461. BABYLON.serialize()
  79462. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  79463. __decorate([
  79464. BABYLON.serialize()
  79465. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  79466. __decorate([
  79467. BABYLON.serialize()
  79468. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  79469. __decorate([
  79470. BABYLON.serialize()
  79471. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  79472. __decorate([
  79473. BABYLON.serialize()
  79474. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  79475. __decorate([
  79476. BABYLON.serialize()
  79477. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  79478. __decorate([
  79479. BABYLON.serialize()
  79480. ], DefaultRenderingPipeline.prototype, "samples", null);
  79481. __decorate([
  79482. BABYLON.serialize()
  79483. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  79484. __decorate([
  79485. BABYLON.serialize()
  79486. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  79487. __decorate([
  79488. BABYLON.serialize()
  79489. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  79490. __decorate([
  79491. BABYLON.serialize()
  79492. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  79493. return DefaultRenderingPipeline;
  79494. }(BABYLON.PostProcessRenderPipeline));
  79495. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  79496. })(BABYLON || (BABYLON = {}));
  79497. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  79498. var BABYLON;
  79499. (function (BABYLON) {
  79500. /**
  79501. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  79502. */
  79503. var GeometryBufferRenderer = /** @class */ (function () {
  79504. /**
  79505. * Creates a new G Buffer for the scene
  79506. * @param scene The scene the buffer belongs to
  79507. * @param ratio How big is the buffer related to the main canvas.
  79508. */
  79509. function GeometryBufferRenderer(scene, ratio) {
  79510. if (ratio === void 0) { ratio = 1; }
  79511. this._enablePosition = false;
  79512. this._scene = scene;
  79513. this._ratio = ratio;
  79514. // Render target
  79515. this._createRenderTargets();
  79516. }
  79517. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  79518. /**
  79519. * Set the render list (meshes to be rendered) used in the G buffer.
  79520. */
  79521. set: function (meshes) {
  79522. this._multiRenderTarget.renderList = meshes;
  79523. },
  79524. enumerable: true,
  79525. configurable: true
  79526. });
  79527. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  79528. /**
  79529. * Gets wether or not G buffer are supported by the running hardware.
  79530. * This requires draw buffer supports
  79531. */
  79532. get: function () {
  79533. return this._multiRenderTarget.isSupported;
  79534. },
  79535. enumerable: true,
  79536. configurable: true
  79537. });
  79538. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  79539. /**
  79540. * Gets wether or not position are enabled for the G buffer.
  79541. */
  79542. get: function () {
  79543. return this._enablePosition;
  79544. },
  79545. /**
  79546. * Sets wether or not position are enabled for the G buffer.
  79547. */
  79548. set: function (enable) {
  79549. this._enablePosition = enable;
  79550. this.dispose();
  79551. this._createRenderTargets();
  79552. },
  79553. enumerable: true,
  79554. configurable: true
  79555. });
  79556. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  79557. /**
  79558. * Gets the scene associated with the buffer.
  79559. */
  79560. get: function () {
  79561. return this._scene;
  79562. },
  79563. enumerable: true,
  79564. configurable: true
  79565. });
  79566. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  79567. /**
  79568. * Gets the ratio used by the buffer during its creation.
  79569. * How big is the buffer related to the main canvas.
  79570. */
  79571. get: function () {
  79572. return this._ratio;
  79573. },
  79574. enumerable: true,
  79575. configurable: true
  79576. });
  79577. /**
  79578. * Checks wether everything is ready to render a submesh to the G buffer.
  79579. * @param subMesh the submesh to check readiness for
  79580. * @param useInstances is the mesh drawn using instance or not
  79581. * @returns true if ready otherwise false
  79582. */
  79583. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  79584. var material = subMesh.getMaterial();
  79585. if (material && material.disableDepthWrite) {
  79586. return false;
  79587. }
  79588. var defines = [];
  79589. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  79590. var mesh = subMesh.getMesh();
  79591. // Alpha test
  79592. if (material && material.needAlphaTesting()) {
  79593. defines.push("#define ALPHATEST");
  79594. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  79595. attribs.push(BABYLON.VertexBuffer.UVKind);
  79596. defines.push("#define UV1");
  79597. }
  79598. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  79599. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  79600. defines.push("#define UV2");
  79601. }
  79602. }
  79603. // Buffers
  79604. if (this._enablePosition) {
  79605. defines.push("#define POSITION");
  79606. }
  79607. // Bones
  79608. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  79609. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  79610. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  79611. if (mesh.numBoneInfluencers > 4) {
  79612. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  79613. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  79614. }
  79615. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  79616. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  79617. }
  79618. else {
  79619. defines.push("#define NUM_BONE_INFLUENCERS 0");
  79620. }
  79621. // Instances
  79622. if (useInstances) {
  79623. defines.push("#define INSTANCES");
  79624. attribs.push("world0");
  79625. attribs.push("world1");
  79626. attribs.push("world2");
  79627. attribs.push("world3");
  79628. }
  79629. // Get correct effect
  79630. var join = defines.join("\n");
  79631. if (this._cachedDefines !== join) {
  79632. this._cachedDefines = join;
  79633. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  79634. }
  79635. return this._effect.isReady();
  79636. };
  79637. /**
  79638. * Gets the current underlying G Buffer.
  79639. * @returns the buffer
  79640. */
  79641. GeometryBufferRenderer.prototype.getGBuffer = function () {
  79642. return this._multiRenderTarget;
  79643. };
  79644. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  79645. /**
  79646. * Gets the number of samples used to render the buffer (anti aliasing).
  79647. */
  79648. get: function () {
  79649. return this._multiRenderTarget.samples;
  79650. },
  79651. /**
  79652. * Sets the number of samples used to render the buffer (anti aliasing).
  79653. */
  79654. set: function (value) {
  79655. this._multiRenderTarget.samples = value;
  79656. },
  79657. enumerable: true,
  79658. configurable: true
  79659. });
  79660. /**
  79661. * Disposes the renderer and frees up associated resources.
  79662. */
  79663. GeometryBufferRenderer.prototype.dispose = function () {
  79664. this.getGBuffer().dispose();
  79665. };
  79666. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  79667. var _this = this;
  79668. var engine = this._scene.getEngine();
  79669. var count = this._enablePosition ? 3 : 2;
  79670. 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 });
  79671. if (!this.isSupported) {
  79672. return;
  79673. }
  79674. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79675. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79676. this._multiRenderTarget.refreshRate = 1;
  79677. this._multiRenderTarget.renderParticles = false;
  79678. this._multiRenderTarget.renderList = null;
  79679. // set default depth value to 1.0 (far away)
  79680. this._multiRenderTarget.onClearObservable.add(function (engine) {
  79681. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  79682. });
  79683. // Custom render function
  79684. var renderSubMesh = function (subMesh) {
  79685. var mesh = subMesh.getRenderingMesh();
  79686. var scene = _this._scene;
  79687. var engine = scene.getEngine();
  79688. var material = subMesh.getMaterial();
  79689. if (!material) {
  79690. return;
  79691. }
  79692. // Culling
  79693. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  79694. // Managing instances
  79695. var batch = mesh._getInstancesRenderList(subMesh._id);
  79696. if (batch.mustReturn) {
  79697. return;
  79698. }
  79699. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  79700. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  79701. engine.enableEffect(_this._effect);
  79702. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  79703. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  79704. _this._effect.setMatrix("view", scene.getViewMatrix());
  79705. // Alpha test
  79706. if (material && material.needAlphaTesting()) {
  79707. var alphaTexture = material.getAlphaTestTexture();
  79708. if (alphaTexture) {
  79709. _this._effect.setTexture("diffuseSampler", alphaTexture);
  79710. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  79711. }
  79712. }
  79713. // Bones
  79714. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  79715. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  79716. }
  79717. // Draw
  79718. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  79719. }
  79720. };
  79721. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  79722. var index;
  79723. if (depthOnlySubMeshes.length) {
  79724. engine.setColorWrite(false);
  79725. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  79726. renderSubMesh(depthOnlySubMeshes.data[index]);
  79727. }
  79728. engine.setColorWrite(true);
  79729. }
  79730. for (index = 0; index < opaqueSubMeshes.length; index++) {
  79731. renderSubMesh(opaqueSubMeshes.data[index]);
  79732. }
  79733. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  79734. renderSubMesh(alphaTestSubMeshes.data[index]);
  79735. }
  79736. };
  79737. };
  79738. return GeometryBufferRenderer;
  79739. }());
  79740. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  79741. })(BABYLON || (BABYLON = {}));
  79742. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  79743. var BABYLON;
  79744. (function (BABYLON) {
  79745. /**
  79746. * @hidden
  79747. */
  79748. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  79749. __extends(ImageProcessingConfigurationDefines, _super);
  79750. function ImageProcessingConfigurationDefines() {
  79751. var _this = _super.call(this) || this;
  79752. _this.IMAGEPROCESSING = false;
  79753. _this.VIGNETTE = false;
  79754. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  79755. _this.VIGNETTEBLENDMODEOPAQUE = false;
  79756. _this.TONEMAPPING = false;
  79757. _this.TONEMAPPING_ACES = false;
  79758. _this.CONTRAST = false;
  79759. _this.COLORCURVES = false;
  79760. _this.COLORGRADING = false;
  79761. _this.COLORGRADING3D = false;
  79762. _this.SAMPLER3DGREENDEPTH = false;
  79763. _this.SAMPLER3DBGRMAP = false;
  79764. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  79765. _this.EXPOSURE = false;
  79766. _this.rebuild();
  79767. return _this;
  79768. }
  79769. return ImageProcessingConfigurationDefines;
  79770. }(BABYLON.MaterialDefines));
  79771. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  79772. /**
  79773. * This groups together the common properties used for image processing either in direct forward pass
  79774. * or through post processing effect depending on the use of the image processing pipeline in your scene
  79775. * or not.
  79776. */
  79777. var ImageProcessingConfiguration = /** @class */ (function () {
  79778. function ImageProcessingConfiguration() {
  79779. /**
  79780. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  79781. */
  79782. this.colorCurves = new BABYLON.ColorCurves();
  79783. this._colorCurvesEnabled = false;
  79784. this._colorGradingEnabled = false;
  79785. this._colorGradingWithGreenDepth = true;
  79786. this._colorGradingBGR = true;
  79787. /** @hidden */
  79788. this._exposure = 1.0;
  79789. this._toneMappingEnabled = false;
  79790. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  79791. this._contrast = 1.0;
  79792. /**
  79793. * Vignette stretch size.
  79794. */
  79795. this.vignetteStretch = 0;
  79796. /**
  79797. * Vignette centre X Offset.
  79798. */
  79799. this.vignetteCentreX = 0;
  79800. /**
  79801. * Vignette centre Y Offset.
  79802. */
  79803. this.vignetteCentreY = 0;
  79804. /**
  79805. * Vignette weight or intensity of the vignette effect.
  79806. */
  79807. this.vignetteWeight = 1.5;
  79808. /**
  79809. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  79810. * if vignetteEnabled is set to true.
  79811. */
  79812. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  79813. /**
  79814. * Camera field of view used by the Vignette effect.
  79815. */
  79816. this.vignetteCameraFov = 0.5;
  79817. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  79818. this._vignetteEnabled = false;
  79819. this._applyByPostProcess = false;
  79820. this._isEnabled = true;
  79821. /**
  79822. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  79823. */
  79824. this.onUpdateParameters = new BABYLON.Observable();
  79825. }
  79826. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  79827. /**
  79828. * Gets wether the color curves effect is enabled.
  79829. */
  79830. get: function () {
  79831. return this._colorCurvesEnabled;
  79832. },
  79833. /**
  79834. * Sets wether the color curves effect is enabled.
  79835. */
  79836. set: function (value) {
  79837. if (this._colorCurvesEnabled === value) {
  79838. return;
  79839. }
  79840. this._colorCurvesEnabled = value;
  79841. this._updateParameters();
  79842. },
  79843. enumerable: true,
  79844. configurable: true
  79845. });
  79846. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  79847. /**
  79848. * Gets wether the color grading effect is enabled.
  79849. */
  79850. get: function () {
  79851. return this._colorGradingEnabled;
  79852. },
  79853. /**
  79854. * Sets wether the color grading effect is enabled.
  79855. */
  79856. set: function (value) {
  79857. if (this._colorGradingEnabled === value) {
  79858. return;
  79859. }
  79860. this._colorGradingEnabled = value;
  79861. this._updateParameters();
  79862. },
  79863. enumerable: true,
  79864. configurable: true
  79865. });
  79866. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  79867. /**
  79868. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  79869. */
  79870. get: function () {
  79871. return this._colorGradingWithGreenDepth;
  79872. },
  79873. /**
  79874. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  79875. */
  79876. set: function (value) {
  79877. if (this._colorGradingWithGreenDepth === value) {
  79878. return;
  79879. }
  79880. this._colorGradingWithGreenDepth = value;
  79881. this._updateParameters();
  79882. },
  79883. enumerable: true,
  79884. configurable: true
  79885. });
  79886. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  79887. /**
  79888. * Gets wether the color grading texture contains BGR values.
  79889. */
  79890. get: function () {
  79891. return this._colorGradingBGR;
  79892. },
  79893. /**
  79894. * Sets wether the color grading texture contains BGR values.
  79895. */
  79896. set: function (value) {
  79897. if (this._colorGradingBGR === value) {
  79898. return;
  79899. }
  79900. this._colorGradingBGR = value;
  79901. this._updateParameters();
  79902. },
  79903. enumerable: true,
  79904. configurable: true
  79905. });
  79906. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  79907. /**
  79908. * Gets the Exposure used in the effect.
  79909. */
  79910. get: function () {
  79911. return this._exposure;
  79912. },
  79913. /**
  79914. * Sets the Exposure used in the effect.
  79915. */
  79916. set: function (value) {
  79917. if (this._exposure === value) {
  79918. return;
  79919. }
  79920. this._exposure = value;
  79921. this._updateParameters();
  79922. },
  79923. enumerable: true,
  79924. configurable: true
  79925. });
  79926. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  79927. /**
  79928. * Gets wether the tone mapping effect is enabled.
  79929. */
  79930. get: function () {
  79931. return this._toneMappingEnabled;
  79932. },
  79933. /**
  79934. * Sets wether the tone mapping effect is enabled.
  79935. */
  79936. set: function (value) {
  79937. if (this._toneMappingEnabled === value) {
  79938. return;
  79939. }
  79940. this._toneMappingEnabled = value;
  79941. this._updateParameters();
  79942. },
  79943. enumerable: true,
  79944. configurable: true
  79945. });
  79946. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  79947. /**
  79948. * Gets the type of tone mapping effect.
  79949. */
  79950. get: function () {
  79951. return this._toneMappingType;
  79952. },
  79953. /**
  79954. * Sets the type of tone mapping effect used in BabylonJS.
  79955. */
  79956. set: function (value) {
  79957. if (this._toneMappingType === value) {
  79958. return;
  79959. }
  79960. this._toneMappingType = value;
  79961. this._updateParameters();
  79962. },
  79963. enumerable: true,
  79964. configurable: true
  79965. });
  79966. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  79967. /**
  79968. * Gets the contrast used in the effect.
  79969. */
  79970. get: function () {
  79971. return this._contrast;
  79972. },
  79973. /**
  79974. * Sets the contrast used in the effect.
  79975. */
  79976. set: function (value) {
  79977. if (this._contrast === value) {
  79978. return;
  79979. }
  79980. this._contrast = value;
  79981. this._updateParameters();
  79982. },
  79983. enumerable: true,
  79984. configurable: true
  79985. });
  79986. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  79987. /**
  79988. * Gets the vignette blend mode allowing different kind of effect.
  79989. */
  79990. get: function () {
  79991. return this._vignetteBlendMode;
  79992. },
  79993. /**
  79994. * Sets the vignette blend mode allowing different kind of effect.
  79995. */
  79996. set: function (value) {
  79997. if (this._vignetteBlendMode === value) {
  79998. return;
  79999. }
  80000. this._vignetteBlendMode = value;
  80001. this._updateParameters();
  80002. },
  80003. enumerable: true,
  80004. configurable: true
  80005. });
  80006. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  80007. /**
  80008. * Gets wether the vignette effect is enabled.
  80009. */
  80010. get: function () {
  80011. return this._vignetteEnabled;
  80012. },
  80013. /**
  80014. * Sets wether the vignette effect is enabled.
  80015. */
  80016. set: function (value) {
  80017. if (this._vignetteEnabled === value) {
  80018. return;
  80019. }
  80020. this._vignetteEnabled = value;
  80021. this._updateParameters();
  80022. },
  80023. enumerable: true,
  80024. configurable: true
  80025. });
  80026. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  80027. /**
  80028. * Gets wether the image processing is applied through a post process or not.
  80029. */
  80030. get: function () {
  80031. return this._applyByPostProcess;
  80032. },
  80033. /**
  80034. * Sets wether the image processing is applied through a post process or not.
  80035. */
  80036. set: function (value) {
  80037. if (this._applyByPostProcess === value) {
  80038. return;
  80039. }
  80040. this._applyByPostProcess = value;
  80041. this._updateParameters();
  80042. },
  80043. enumerable: true,
  80044. configurable: true
  80045. });
  80046. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  80047. /**
  80048. * Gets wether the image processing is enabled or not.
  80049. */
  80050. get: function () {
  80051. return this._isEnabled;
  80052. },
  80053. /**
  80054. * Sets wether the image processing is enabled or not.
  80055. */
  80056. set: function (value) {
  80057. if (this._isEnabled === value) {
  80058. return;
  80059. }
  80060. this._isEnabled = value;
  80061. this._updateParameters();
  80062. },
  80063. enumerable: true,
  80064. configurable: true
  80065. });
  80066. /**
  80067. * Method called each time the image processing information changes requires to recompile the effect.
  80068. */
  80069. ImageProcessingConfiguration.prototype._updateParameters = function () {
  80070. this.onUpdateParameters.notifyObservers(this);
  80071. };
  80072. ImageProcessingConfiguration.prototype.getClassName = function () {
  80073. return "ImageProcessingConfiguration";
  80074. };
  80075. /**
  80076. * Prepare the list of uniforms associated with the Image Processing effects.
  80077. * @param uniformsList The list of uniforms used in the effect
  80078. * @param defines the list of defines currently in use
  80079. */
  80080. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  80081. if (defines.EXPOSURE) {
  80082. uniforms.push("exposureLinear");
  80083. }
  80084. if (defines.CONTRAST) {
  80085. uniforms.push("contrast");
  80086. }
  80087. if (defines.COLORGRADING) {
  80088. uniforms.push("colorTransformSettings");
  80089. }
  80090. if (defines.VIGNETTE) {
  80091. uniforms.push("vInverseScreenSize");
  80092. uniforms.push("vignetteSettings1");
  80093. uniforms.push("vignetteSettings2");
  80094. }
  80095. if (defines.COLORCURVES) {
  80096. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  80097. }
  80098. };
  80099. /**
  80100. * Prepare the list of samplers associated with the Image Processing effects.
  80101. * @param uniformsList The list of uniforms used in the effect
  80102. * @param defines the list of defines currently in use
  80103. */
  80104. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  80105. if (defines.COLORGRADING) {
  80106. samplersList.push("txColorTransform");
  80107. }
  80108. };
  80109. /**
  80110. * Prepare the list of defines associated to the shader.
  80111. * @param defines the list of defines to complete
  80112. */
  80113. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  80114. if (forPostProcess === void 0) { forPostProcess = false; }
  80115. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  80116. defines.VIGNETTE = false;
  80117. defines.TONEMAPPING = false;
  80118. defines.TONEMAPPING_ACES = false;
  80119. defines.CONTRAST = false;
  80120. defines.EXPOSURE = false;
  80121. defines.COLORCURVES = false;
  80122. defines.COLORGRADING = false;
  80123. defines.COLORGRADING3D = false;
  80124. defines.IMAGEPROCESSING = false;
  80125. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  80126. return;
  80127. }
  80128. defines.VIGNETTE = this.vignetteEnabled;
  80129. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  80130. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  80131. defines.TONEMAPPING = this.toneMappingEnabled;
  80132. switch (this._toneMappingType) {
  80133. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  80134. defines.TONEMAPPING_ACES = true;
  80135. break;
  80136. }
  80137. defines.CONTRAST = (this.contrast !== 1.0);
  80138. defines.EXPOSURE = (this.exposure !== 1.0);
  80139. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  80140. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  80141. if (defines.COLORGRADING) {
  80142. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  80143. }
  80144. else {
  80145. defines.COLORGRADING3D = false;
  80146. }
  80147. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  80148. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  80149. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  80150. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  80151. };
  80152. /**
  80153. * Returns true if all the image processing information are ready.
  80154. */
  80155. ImageProcessingConfiguration.prototype.isReady = function () {
  80156. // Color Grading texure can not be none blocking.
  80157. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  80158. };
  80159. /**
  80160. * Binds the image processing to the shader.
  80161. * @param effect The effect to bind to
  80162. */
  80163. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  80164. if (aspectRatio === void 0) { aspectRatio = 1; }
  80165. // Color Curves
  80166. if (this._colorCurvesEnabled && this.colorCurves) {
  80167. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  80168. }
  80169. // Vignette
  80170. if (this._vignetteEnabled) {
  80171. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  80172. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  80173. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  80174. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  80175. var vignetteScaleX = vignetteScaleY * aspectRatio;
  80176. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  80177. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  80178. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  80179. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  80180. var vignettePower = -2.0 * this.vignetteWeight;
  80181. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  80182. }
  80183. // Exposure
  80184. effect.setFloat("exposureLinear", this.exposure);
  80185. // Contrast
  80186. effect.setFloat("contrast", this.contrast);
  80187. // Color transform settings
  80188. if (this.colorGradingTexture) {
  80189. effect.setTexture("txColorTransform", this.colorGradingTexture);
  80190. var textureSize = this.colorGradingTexture.getSize().height;
  80191. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  80192. 0.5 / textureSize, // textureOffset
  80193. textureSize, // textureSize
  80194. this.colorGradingTexture.level // weight
  80195. );
  80196. }
  80197. };
  80198. /**
  80199. * Clones the current image processing instance.
  80200. * @return The cloned image processing
  80201. */
  80202. ImageProcessingConfiguration.prototype.clone = function () {
  80203. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  80204. };
  80205. /**
  80206. * Serializes the current image processing instance to a json representation.
  80207. * @return a JSON representation
  80208. */
  80209. ImageProcessingConfiguration.prototype.serialize = function () {
  80210. return BABYLON.SerializationHelper.Serialize(this);
  80211. };
  80212. /**
  80213. * Parses the image processing from a json representation.
  80214. * @param source the JSON source to parse
  80215. * @return The parsed image processing
  80216. */
  80217. ImageProcessingConfiguration.Parse = function (source) {
  80218. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  80219. };
  80220. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  80221. /**
  80222. * Used to apply the vignette as a mix with the pixel color.
  80223. */
  80224. get: function () {
  80225. return this._VIGNETTEMODE_MULTIPLY;
  80226. },
  80227. enumerable: true,
  80228. configurable: true
  80229. });
  80230. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  80231. /**
  80232. * Used to apply the vignette as a replacement of the pixel color.
  80233. */
  80234. get: function () {
  80235. return this._VIGNETTEMODE_OPAQUE;
  80236. },
  80237. enumerable: true,
  80238. configurable: true
  80239. });
  80240. /**
  80241. * Default tone mapping applied in BabylonJS.
  80242. */
  80243. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  80244. /**
  80245. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  80246. * to other engines rendering to increase portability.
  80247. */
  80248. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  80249. // Static constants associated to the image processing.
  80250. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  80251. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  80252. __decorate([
  80253. BABYLON.serializeAsColorCurves()
  80254. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  80255. __decorate([
  80256. BABYLON.serialize()
  80257. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  80258. __decorate([
  80259. BABYLON.serializeAsTexture()
  80260. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  80261. __decorate([
  80262. BABYLON.serialize()
  80263. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  80264. __decorate([
  80265. BABYLON.serialize()
  80266. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  80267. __decorate([
  80268. BABYLON.serialize()
  80269. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  80270. __decorate([
  80271. BABYLON.serialize()
  80272. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  80273. __decorate([
  80274. BABYLON.serialize()
  80275. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  80276. __decorate([
  80277. BABYLON.serialize()
  80278. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  80279. __decorate([
  80280. BABYLON.serialize()
  80281. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  80282. __decorate([
  80283. BABYLON.serialize()
  80284. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  80285. __decorate([
  80286. BABYLON.serialize()
  80287. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  80288. __decorate([
  80289. BABYLON.serialize()
  80290. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  80291. __decorate([
  80292. BABYLON.serialize()
  80293. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  80294. __decorate([
  80295. BABYLON.serializeAsColor4()
  80296. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  80297. __decorate([
  80298. BABYLON.serialize()
  80299. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  80300. __decorate([
  80301. BABYLON.serialize()
  80302. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  80303. __decorate([
  80304. BABYLON.serialize()
  80305. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  80306. __decorate([
  80307. BABYLON.serialize()
  80308. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  80309. __decorate([
  80310. BABYLON.serialize()
  80311. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  80312. return ImageProcessingConfiguration;
  80313. }());
  80314. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  80315. })(BABYLON || (BABYLON = {}));
  80316. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  80317. var BABYLON;
  80318. (function (BABYLON) {
  80319. /**
  80320. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  80321. * It can help converting any input color in a desired output one. This can then be used to create effects
  80322. * from sepia, black and white to sixties or futuristic rendering...
  80323. *
  80324. * The only supported format is currently 3dl.
  80325. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  80326. */
  80327. var ColorGradingTexture = /** @class */ (function (_super) {
  80328. __extends(ColorGradingTexture, _super);
  80329. /**
  80330. * Instantiates a ColorGradingTexture from the following parameters.
  80331. *
  80332. * @param url The location of the color gradind data (currently only supporting 3dl)
  80333. * @param scene The scene the texture will be used in
  80334. */
  80335. function ColorGradingTexture(url, scene) {
  80336. var _this = _super.call(this, scene) || this;
  80337. if (!url) {
  80338. return _this;
  80339. }
  80340. _this._engine = scene.getEngine();
  80341. _this._textureMatrix = BABYLON.Matrix.Identity();
  80342. _this.name = url;
  80343. _this.url = url;
  80344. _this.hasAlpha = false;
  80345. _this.isCube = false;
  80346. _this.is3D = _this._engine.webGLVersion > 1;
  80347. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80348. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80349. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80350. _this.anisotropicFilteringLevel = 1;
  80351. _this._texture = _this._getFromCache(url, true);
  80352. if (!_this._texture) {
  80353. if (!scene.useDelayedTextureLoading) {
  80354. _this.loadTexture();
  80355. }
  80356. else {
  80357. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  80358. }
  80359. }
  80360. return _this;
  80361. }
  80362. /**
  80363. * Returns the texture matrix used in most of the material.
  80364. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  80365. */
  80366. ColorGradingTexture.prototype.getTextureMatrix = function () {
  80367. return this._textureMatrix;
  80368. };
  80369. /**
  80370. * Occurs when the file being loaded is a .3dl LUT file.
  80371. */
  80372. ColorGradingTexture.prototype.load3dlTexture = function () {
  80373. var engine = this._engine;
  80374. var texture;
  80375. if (engine.webGLVersion === 1) {
  80376. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  80377. }
  80378. else {
  80379. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  80380. }
  80381. this._texture = texture;
  80382. var callback = function (text) {
  80383. if (typeof text !== "string") {
  80384. return;
  80385. }
  80386. var data = null;
  80387. var tempData = null;
  80388. var line;
  80389. var lines = text.split('\n');
  80390. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  80391. var maxColor = 0;
  80392. for (var i = 0; i < lines.length; i++) {
  80393. line = lines[i];
  80394. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  80395. continue;
  80396. if (line.indexOf('#') === 0)
  80397. continue;
  80398. var words = line.split(" ");
  80399. if (size === 0) {
  80400. // Number of space + one
  80401. size = words.length;
  80402. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  80403. tempData = new Float32Array(size * size * size * 4);
  80404. continue;
  80405. }
  80406. if (size != 0) {
  80407. var r = Math.max(parseInt(words[0]), 0);
  80408. var g = Math.max(parseInt(words[1]), 0);
  80409. var b = Math.max(parseInt(words[2]), 0);
  80410. maxColor = Math.max(r, maxColor);
  80411. maxColor = Math.max(g, maxColor);
  80412. maxColor = Math.max(b, maxColor);
  80413. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  80414. if (tempData) {
  80415. tempData[pixelStorageIndex + 0] = r;
  80416. tempData[pixelStorageIndex + 1] = g;
  80417. tempData[pixelStorageIndex + 2] = b;
  80418. }
  80419. pixelIndexSlice++;
  80420. if (pixelIndexSlice % size == 0) {
  80421. pixelIndexH++;
  80422. pixelIndexSlice = 0;
  80423. if (pixelIndexH % size == 0) {
  80424. pixelIndexW++;
  80425. pixelIndexH = 0;
  80426. }
  80427. }
  80428. }
  80429. }
  80430. if (tempData && data) {
  80431. for (var i = 0; i < tempData.length; i++) {
  80432. if (i > 0 && (i + 1) % 4 === 0) {
  80433. data[i] = 255;
  80434. }
  80435. else {
  80436. var value = tempData[i];
  80437. data[i] = (value / maxColor * 255);
  80438. }
  80439. }
  80440. }
  80441. if (texture.is3D) {
  80442. texture.updateSize(size, size, size);
  80443. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  80444. }
  80445. else {
  80446. texture.updateSize(size * size, size);
  80447. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  80448. }
  80449. };
  80450. var scene = this.getScene();
  80451. if (scene) {
  80452. scene._loadFile(this.url, callback);
  80453. }
  80454. else {
  80455. this._engine._loadFile(this.url, callback);
  80456. }
  80457. return this._texture;
  80458. };
  80459. /**
  80460. * Starts the loading process of the texture.
  80461. */
  80462. ColorGradingTexture.prototype.loadTexture = function () {
  80463. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  80464. this.load3dlTexture();
  80465. }
  80466. };
  80467. /**
  80468. * Clones the color gradind texture.
  80469. */
  80470. ColorGradingTexture.prototype.clone = function () {
  80471. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  80472. // Base texture
  80473. newTexture.level = this.level;
  80474. return newTexture;
  80475. };
  80476. /**
  80477. * Called during delayed load for textures.
  80478. */
  80479. ColorGradingTexture.prototype.delayLoad = function () {
  80480. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  80481. return;
  80482. }
  80483. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  80484. this._texture = this._getFromCache(this.url, true);
  80485. if (!this._texture) {
  80486. this.loadTexture();
  80487. }
  80488. };
  80489. /**
  80490. * Parses a color grading texture serialized by Babylon.
  80491. * @param parsedTexture The texture information being parsedTexture
  80492. * @param scene The scene to load the texture in
  80493. * @param rootUrl The root url of the data assets to load
  80494. * @return A color gradind texture
  80495. */
  80496. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  80497. var texture = null;
  80498. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  80499. texture = new ColorGradingTexture(parsedTexture.name, scene);
  80500. texture.name = parsedTexture.name;
  80501. texture.level = parsedTexture.level;
  80502. }
  80503. return texture;
  80504. };
  80505. /**
  80506. * Serializes the LUT texture to json format.
  80507. */
  80508. ColorGradingTexture.prototype.serialize = function () {
  80509. if (!this.name) {
  80510. return null;
  80511. }
  80512. var serializationObject = {};
  80513. serializationObject.name = this.name;
  80514. serializationObject.level = this.level;
  80515. serializationObject.customType = "BABYLON.ColorGradingTexture";
  80516. return serializationObject;
  80517. };
  80518. /**
  80519. * Empty line regex stored for GC.
  80520. */
  80521. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  80522. return ColorGradingTexture;
  80523. }(BABYLON.BaseTexture));
  80524. BABYLON.ColorGradingTexture = ColorGradingTexture;
  80525. })(BABYLON || (BABYLON = {}));
  80526. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  80527. var BABYLON;
  80528. (function (BABYLON) {
  80529. /**
  80530. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  80531. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  80532. * 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;
  80533. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  80534. */
  80535. var ColorCurves = /** @class */ (function () {
  80536. function ColorCurves() {
  80537. this._dirty = true;
  80538. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  80539. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  80540. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  80541. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  80542. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  80543. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  80544. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  80545. this._globalHue = 30;
  80546. this._globalDensity = 0;
  80547. this._globalSaturation = 0;
  80548. this._globalExposure = 0;
  80549. this._highlightsHue = 30;
  80550. this._highlightsDensity = 0;
  80551. this._highlightsSaturation = 0;
  80552. this._highlightsExposure = 0;
  80553. this._midtonesHue = 30;
  80554. this._midtonesDensity = 0;
  80555. this._midtonesSaturation = 0;
  80556. this._midtonesExposure = 0;
  80557. this._shadowsHue = 30;
  80558. this._shadowsDensity = 0;
  80559. this._shadowsSaturation = 0;
  80560. this._shadowsExposure = 0;
  80561. }
  80562. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  80563. /**
  80564. * Gets the global Hue value.
  80565. * 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).
  80566. */
  80567. get: function () {
  80568. return this._globalHue;
  80569. },
  80570. /**
  80571. * Sets the global Hue value.
  80572. * 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).
  80573. */
  80574. set: function (value) {
  80575. this._globalHue = value;
  80576. this._dirty = true;
  80577. },
  80578. enumerable: true,
  80579. configurable: true
  80580. });
  80581. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  80582. /**
  80583. * Gets the global Density value.
  80584. * 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.
  80585. * Values less than zero provide a filter of opposite hue.
  80586. */
  80587. get: function () {
  80588. return this._globalDensity;
  80589. },
  80590. /**
  80591. * Sets the global Density value.
  80592. * 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.
  80593. * Values less than zero provide a filter of opposite hue.
  80594. */
  80595. set: function (value) {
  80596. this._globalDensity = value;
  80597. this._dirty = true;
  80598. },
  80599. enumerable: true,
  80600. configurable: true
  80601. });
  80602. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  80603. /**
  80604. * Gets the global Saturation value.
  80605. * 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.
  80606. */
  80607. get: function () {
  80608. return this._globalSaturation;
  80609. },
  80610. /**
  80611. * Sets the global Saturation value.
  80612. * 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.
  80613. */
  80614. set: function (value) {
  80615. this._globalSaturation = value;
  80616. this._dirty = true;
  80617. },
  80618. enumerable: true,
  80619. configurable: true
  80620. });
  80621. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  80622. /**
  80623. * Gets the global Exposure value.
  80624. * 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.
  80625. */
  80626. get: function () {
  80627. return this._globalExposure;
  80628. },
  80629. /**
  80630. * Sets the global Exposure value.
  80631. * 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.
  80632. */
  80633. set: function (value) {
  80634. this._globalExposure = value;
  80635. this._dirty = true;
  80636. },
  80637. enumerable: true,
  80638. configurable: true
  80639. });
  80640. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  80641. /**
  80642. * Gets the highlights Hue value.
  80643. * 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).
  80644. */
  80645. get: function () {
  80646. return this._highlightsHue;
  80647. },
  80648. /**
  80649. * Sets the highlights Hue value.
  80650. * 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).
  80651. */
  80652. set: function (value) {
  80653. this._highlightsHue = value;
  80654. this._dirty = true;
  80655. },
  80656. enumerable: true,
  80657. configurable: true
  80658. });
  80659. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  80660. /**
  80661. * Gets the highlights Density value.
  80662. * 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.
  80663. * Values less than zero provide a filter of opposite hue.
  80664. */
  80665. get: function () {
  80666. return this._highlightsDensity;
  80667. },
  80668. /**
  80669. * Sets the highlights Density value.
  80670. * 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.
  80671. * Values less than zero provide a filter of opposite hue.
  80672. */
  80673. set: function (value) {
  80674. this._highlightsDensity = value;
  80675. this._dirty = true;
  80676. },
  80677. enumerable: true,
  80678. configurable: true
  80679. });
  80680. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  80681. /**
  80682. * Gets the highlights Saturation value.
  80683. * 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.
  80684. */
  80685. get: function () {
  80686. return this._highlightsSaturation;
  80687. },
  80688. /**
  80689. * Sets the highlights Saturation value.
  80690. * 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.
  80691. */
  80692. set: function (value) {
  80693. this._highlightsSaturation = value;
  80694. this._dirty = true;
  80695. },
  80696. enumerable: true,
  80697. configurable: true
  80698. });
  80699. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  80700. /**
  80701. * Gets the highlights Exposure value.
  80702. * 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.
  80703. */
  80704. get: function () {
  80705. return this._highlightsExposure;
  80706. },
  80707. /**
  80708. * Sets the highlights Exposure value.
  80709. * 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.
  80710. */
  80711. set: function (value) {
  80712. this._highlightsExposure = value;
  80713. this._dirty = true;
  80714. },
  80715. enumerable: true,
  80716. configurable: true
  80717. });
  80718. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  80719. /**
  80720. * Gets the midtones Hue value.
  80721. * 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).
  80722. */
  80723. get: function () {
  80724. return this._midtonesHue;
  80725. },
  80726. /**
  80727. * Sets the midtones Hue value.
  80728. * 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).
  80729. */
  80730. set: function (value) {
  80731. this._midtonesHue = value;
  80732. this._dirty = true;
  80733. },
  80734. enumerable: true,
  80735. configurable: true
  80736. });
  80737. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  80738. /**
  80739. * Gets the midtones Density value.
  80740. * 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.
  80741. * Values less than zero provide a filter of opposite hue.
  80742. */
  80743. get: function () {
  80744. return this._midtonesDensity;
  80745. },
  80746. /**
  80747. * Sets the midtones Density value.
  80748. * 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.
  80749. * Values less than zero provide a filter of opposite hue.
  80750. */
  80751. set: function (value) {
  80752. this._midtonesDensity = value;
  80753. this._dirty = true;
  80754. },
  80755. enumerable: true,
  80756. configurable: true
  80757. });
  80758. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  80759. /**
  80760. * Gets the midtones Saturation value.
  80761. * 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.
  80762. */
  80763. get: function () {
  80764. return this._midtonesSaturation;
  80765. },
  80766. /**
  80767. * Sets the midtones Saturation value.
  80768. * 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.
  80769. */
  80770. set: function (value) {
  80771. this._midtonesSaturation = value;
  80772. this._dirty = true;
  80773. },
  80774. enumerable: true,
  80775. configurable: true
  80776. });
  80777. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  80778. /**
  80779. * Gets the midtones Exposure value.
  80780. * 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.
  80781. */
  80782. get: function () {
  80783. return this._midtonesExposure;
  80784. },
  80785. /**
  80786. * Sets the midtones Exposure value.
  80787. * 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.
  80788. */
  80789. set: function (value) {
  80790. this._midtonesExposure = value;
  80791. this._dirty = true;
  80792. },
  80793. enumerable: true,
  80794. configurable: true
  80795. });
  80796. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  80797. /**
  80798. * Gets the shadows Hue value.
  80799. * 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).
  80800. */
  80801. get: function () {
  80802. return this._shadowsHue;
  80803. },
  80804. /**
  80805. * Sets the shadows Hue value.
  80806. * 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).
  80807. */
  80808. set: function (value) {
  80809. this._shadowsHue = value;
  80810. this._dirty = true;
  80811. },
  80812. enumerable: true,
  80813. configurable: true
  80814. });
  80815. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  80816. /**
  80817. * Gets the shadows Density value.
  80818. * 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.
  80819. * Values less than zero provide a filter of opposite hue.
  80820. */
  80821. get: function () {
  80822. return this._shadowsDensity;
  80823. },
  80824. /**
  80825. * Sets the shadows Density value.
  80826. * 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.
  80827. * Values less than zero provide a filter of opposite hue.
  80828. */
  80829. set: function (value) {
  80830. this._shadowsDensity = value;
  80831. this._dirty = true;
  80832. },
  80833. enumerable: true,
  80834. configurable: true
  80835. });
  80836. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  80837. /**
  80838. * Gets the shadows Saturation value.
  80839. * 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.
  80840. */
  80841. get: function () {
  80842. return this._shadowsSaturation;
  80843. },
  80844. /**
  80845. * Sets the shadows Saturation value.
  80846. * 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.
  80847. */
  80848. set: function (value) {
  80849. this._shadowsSaturation = value;
  80850. this._dirty = true;
  80851. },
  80852. enumerable: true,
  80853. configurable: true
  80854. });
  80855. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  80856. /**
  80857. * Gets the shadows Exposure value.
  80858. * 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.
  80859. */
  80860. get: function () {
  80861. return this._shadowsExposure;
  80862. },
  80863. /**
  80864. * Sets the shadows Exposure value.
  80865. * 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.
  80866. */
  80867. set: function (value) {
  80868. this._shadowsExposure = value;
  80869. this._dirty = true;
  80870. },
  80871. enumerable: true,
  80872. configurable: true
  80873. });
  80874. ColorCurves.prototype.getClassName = function () {
  80875. return "ColorCurves";
  80876. };
  80877. /**
  80878. * Binds the color curves to the shader.
  80879. * @param colorCurves The color curve to bind
  80880. * @param effect The effect to bind to
  80881. */
  80882. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  80883. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  80884. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  80885. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  80886. if (colorCurves._dirty) {
  80887. colorCurves._dirty = false;
  80888. // Fill in global info.
  80889. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  80890. // Compute highlights info.
  80891. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  80892. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  80893. // Compute midtones info.
  80894. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  80895. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  80896. // Compute shadows info.
  80897. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  80898. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  80899. // Compute deltas (neutral is midtones).
  80900. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  80901. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  80902. }
  80903. if (effect) {
  80904. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  80905. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  80906. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  80907. }
  80908. };
  80909. /**
  80910. * Prepare the list of uniforms associated with the ColorCurves effects.
  80911. * @param uniformsList The list of uniforms used in the effect
  80912. */
  80913. ColorCurves.PrepareUniforms = function (uniformsList) {
  80914. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  80915. };
  80916. /**
  80917. * Returns color grading data based on a hue, density, saturation and exposure value.
  80918. * @param filterHue The hue of the color filter.
  80919. * @param filterDensity The density of the color filter.
  80920. * @param saturation The saturation.
  80921. * @param exposure The exposure.
  80922. * @param result The result data container.
  80923. */
  80924. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  80925. if (hue == null) {
  80926. return;
  80927. }
  80928. hue = ColorCurves.clamp(hue, 0, 360);
  80929. density = ColorCurves.clamp(density, -100, 100);
  80930. saturation = ColorCurves.clamp(saturation, -100, 100);
  80931. exposure = ColorCurves.clamp(exposure, -100, 100);
  80932. // Remap the slider/config filter density with non-linear mapping and also scale by half
  80933. // so that the maximum filter density is only 50% control. This provides fine control
  80934. // for small values and reasonable range.
  80935. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  80936. density *= 0.5;
  80937. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  80938. if (density < 0) {
  80939. density *= -1;
  80940. hue = (hue + 180) % 360;
  80941. }
  80942. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  80943. result.scaleToRef(2, result);
  80944. result.a = 1 + 0.01 * saturation;
  80945. };
  80946. /**
  80947. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  80948. * @param value The input slider value in range [-100,100].
  80949. * @returns Adjusted value.
  80950. */
  80951. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  80952. value /= 100;
  80953. var x = Math.abs(value);
  80954. x = Math.pow(x, 2);
  80955. if (value < 0) {
  80956. x *= -1;
  80957. }
  80958. x *= 100;
  80959. return x;
  80960. };
  80961. /**
  80962. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  80963. * @param hue The hue (H) input.
  80964. * @param saturation The saturation (S) input.
  80965. * @param brightness The brightness (B) input.
  80966. * @result An RGBA color represented as Vector4.
  80967. */
  80968. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  80969. var h = ColorCurves.clamp(hue, 0, 360);
  80970. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  80971. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  80972. if (s === 0) {
  80973. result.r = v;
  80974. result.g = v;
  80975. result.b = v;
  80976. }
  80977. else {
  80978. // sector 0 to 5
  80979. h /= 60;
  80980. var i = Math.floor(h);
  80981. // fractional part of h
  80982. var f = h - i;
  80983. var p = v * (1 - s);
  80984. var q = v * (1 - s * f);
  80985. var t = v * (1 - s * (1 - f));
  80986. switch (i) {
  80987. case 0:
  80988. result.r = v;
  80989. result.g = t;
  80990. result.b = p;
  80991. break;
  80992. case 1:
  80993. result.r = q;
  80994. result.g = v;
  80995. result.b = p;
  80996. break;
  80997. case 2:
  80998. result.r = p;
  80999. result.g = v;
  81000. result.b = t;
  81001. break;
  81002. case 3:
  81003. result.r = p;
  81004. result.g = q;
  81005. result.b = v;
  81006. break;
  81007. case 4:
  81008. result.r = t;
  81009. result.g = p;
  81010. result.b = v;
  81011. break;
  81012. default: // case 5:
  81013. result.r = v;
  81014. result.g = p;
  81015. result.b = q;
  81016. break;
  81017. }
  81018. }
  81019. result.a = 1;
  81020. };
  81021. /**
  81022. * Returns a value clamped between min and max
  81023. * @param value The value to clamp
  81024. * @param min The minimum of value
  81025. * @param max The maximum of value
  81026. * @returns The clamped value.
  81027. */
  81028. ColorCurves.clamp = function (value, min, max) {
  81029. return Math.min(Math.max(value, min), max);
  81030. };
  81031. /**
  81032. * Clones the current color curve instance.
  81033. * @return The cloned curves
  81034. */
  81035. ColorCurves.prototype.clone = function () {
  81036. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  81037. };
  81038. /**
  81039. * Serializes the current color curve instance to a json representation.
  81040. * @return a JSON representation
  81041. */
  81042. ColorCurves.prototype.serialize = function () {
  81043. return BABYLON.SerializationHelper.Serialize(this);
  81044. };
  81045. /**
  81046. * Parses the color curve from a json representation.
  81047. * @param source the JSON source to parse
  81048. * @return The parsed curves
  81049. */
  81050. ColorCurves.Parse = function (source) {
  81051. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  81052. };
  81053. __decorate([
  81054. BABYLON.serialize()
  81055. ], ColorCurves.prototype, "_globalHue", void 0);
  81056. __decorate([
  81057. BABYLON.serialize()
  81058. ], ColorCurves.prototype, "_globalDensity", void 0);
  81059. __decorate([
  81060. BABYLON.serialize()
  81061. ], ColorCurves.prototype, "_globalSaturation", void 0);
  81062. __decorate([
  81063. BABYLON.serialize()
  81064. ], ColorCurves.prototype, "_globalExposure", void 0);
  81065. __decorate([
  81066. BABYLON.serialize()
  81067. ], ColorCurves.prototype, "_highlightsHue", void 0);
  81068. __decorate([
  81069. BABYLON.serialize()
  81070. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  81071. __decorate([
  81072. BABYLON.serialize()
  81073. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  81074. __decorate([
  81075. BABYLON.serialize()
  81076. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  81077. __decorate([
  81078. BABYLON.serialize()
  81079. ], ColorCurves.prototype, "_midtonesHue", void 0);
  81080. __decorate([
  81081. BABYLON.serialize()
  81082. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  81083. __decorate([
  81084. BABYLON.serialize()
  81085. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  81086. __decorate([
  81087. BABYLON.serialize()
  81088. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  81089. return ColorCurves;
  81090. }());
  81091. BABYLON.ColorCurves = ColorCurves;
  81092. })(BABYLON || (BABYLON = {}));
  81093. //# sourceMappingURL=babylon.colorCurves.js.map
  81094. var BABYLON;
  81095. (function (BABYLON) {
  81096. var RefractionPostProcess = /** @class */ (function (_super) {
  81097. __extends(RefractionPostProcess, _super);
  81098. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  81099. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  81100. _this.color = color;
  81101. _this.depth = depth;
  81102. _this.colorLevel = colorLevel;
  81103. _this._ownRefractionTexture = true;
  81104. _this.onActivateObservable.add(function (cam) {
  81105. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  81106. });
  81107. _this.onApplyObservable.add(function (effect) {
  81108. effect.setColor3("baseColor", _this.color);
  81109. effect.setFloat("depth", _this.depth);
  81110. effect.setFloat("colorLevel", _this.colorLevel);
  81111. effect.setTexture("refractionSampler", _this._refTexture);
  81112. });
  81113. return _this;
  81114. }
  81115. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  81116. /**
  81117. * Gets or sets the refraction texture
  81118. * Please note that you are responsible for disposing the texture if you set it manually
  81119. */
  81120. get: function () {
  81121. return this._refTexture;
  81122. },
  81123. set: function (value) {
  81124. if (this._refTexture && this._ownRefractionTexture) {
  81125. this._refTexture.dispose();
  81126. }
  81127. this._refTexture = value;
  81128. this._ownRefractionTexture = false;
  81129. },
  81130. enumerable: true,
  81131. configurable: true
  81132. });
  81133. // Methods
  81134. RefractionPostProcess.prototype.dispose = function (camera) {
  81135. if (this._refTexture && this._ownRefractionTexture) {
  81136. this._refTexture.dispose();
  81137. this._refTexture = null;
  81138. }
  81139. _super.prototype.dispose.call(this, camera);
  81140. };
  81141. return RefractionPostProcess;
  81142. }(BABYLON.PostProcess));
  81143. BABYLON.RefractionPostProcess = RefractionPostProcess;
  81144. })(BABYLON || (BABYLON = {}));
  81145. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  81146. var BABYLON;
  81147. (function (BABYLON) {
  81148. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  81149. __extends(BlackAndWhitePostProcess, _super);
  81150. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  81151. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  81152. _this.degree = 1;
  81153. _this.onApplyObservable.add(function (effect) {
  81154. effect.setFloat("degree", _this.degree);
  81155. });
  81156. return _this;
  81157. }
  81158. return BlackAndWhitePostProcess;
  81159. }(BABYLON.PostProcess));
  81160. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  81161. })(BABYLON || (BABYLON = {}));
  81162. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  81163. var BABYLON;
  81164. (function (BABYLON) {
  81165. /**
  81166. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  81167. * input texture to perform effects such as edge detection or sharpening
  81168. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  81169. */
  81170. var ConvolutionPostProcess = /** @class */ (function (_super) {
  81171. __extends(ConvolutionPostProcess, _super);
  81172. /**
  81173. * Creates a new instance ConvolutionPostProcess
  81174. * @param name The name of the effect.
  81175. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  81176. * @param options The required width/height ratio to downsize to before computing the render pass.
  81177. * @param camera The camera to apply the render pass to.
  81178. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  81179. * @param engine The engine which the post process will be applied. (default: current engine)
  81180. * @param reusable If the post process can be reused on the same frame. (default: false)
  81181. * @param textureType Type of textures used when performing the post process. (default: 0)
  81182. */
  81183. function ConvolutionPostProcess(name,
  81184. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  81185. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  81186. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  81187. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  81188. _this.kernel = kernel;
  81189. _this.onApply = function (effect) {
  81190. effect.setFloat2("screenSize", _this.width, _this.height);
  81191. effect.setArray("kernel", _this.kernel);
  81192. };
  81193. return _this;
  81194. }
  81195. // Statics
  81196. /**
  81197. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  81198. */
  81199. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  81200. /**
  81201. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  81202. */
  81203. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  81204. /**
  81205. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  81206. */
  81207. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  81208. /**
  81209. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  81210. */
  81211. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  81212. /**
  81213. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  81214. */
  81215. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  81216. /**
  81217. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  81218. */
  81219. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  81220. return ConvolutionPostProcess;
  81221. }(BABYLON.PostProcess));
  81222. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  81223. })(BABYLON || (BABYLON = {}));
  81224. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  81225. var BABYLON;
  81226. (function (BABYLON) {
  81227. var FilterPostProcess = /** @class */ (function (_super) {
  81228. __extends(FilterPostProcess, _super);
  81229. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  81230. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  81231. _this.kernelMatrix = kernelMatrix;
  81232. _this.onApply = function (effect) {
  81233. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  81234. };
  81235. return _this;
  81236. }
  81237. return FilterPostProcess;
  81238. }(BABYLON.PostProcess));
  81239. BABYLON.FilterPostProcess = FilterPostProcess;
  81240. })(BABYLON || (BABYLON = {}));
  81241. //# sourceMappingURL=babylon.filterPostProcess.js.map
  81242. var BABYLON;
  81243. (function (BABYLON) {
  81244. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  81245. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  81246. __extends(VolumetricLightScatteringPostProcess, _super);
  81247. /**
  81248. * @constructor
  81249. * @param {string} name - The post-process name
  81250. * @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)
  81251. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  81252. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  81253. * @param {number} samples - The post-process quality, default 100
  81254. * @param {number} samplingMode - The post-process filtering mode
  81255. * @param {BABYLON.Engine} engine - The babylon engine
  81256. * @param {boolean} reusable - If the post-process is reusable
  81257. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  81258. */
  81259. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  81260. if (samples === void 0) { samples = 100; }
  81261. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  81262. 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;
  81263. _this._screenCoordinates = BABYLON.Vector2.Zero();
  81264. /**
  81265. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  81266. */
  81267. _this.customMeshPosition = BABYLON.Vector3.Zero();
  81268. /**
  81269. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  81270. */
  81271. _this.useCustomMeshPosition = false;
  81272. /**
  81273. * If the post-process should inverse the light scattering direction
  81274. */
  81275. _this.invert = true;
  81276. /**
  81277. * Array containing the excluded meshes not rendered in the internal pass
  81278. */
  81279. _this.excludedMeshes = new Array();
  81280. /**
  81281. * Controls the overall intensity of the post-process
  81282. */
  81283. _this.exposure = 0.3;
  81284. /**
  81285. * Dissipates each sample's contribution in range [0, 1]
  81286. */
  81287. _this.decay = 0.96815;
  81288. /**
  81289. * Controls the overall intensity of each sample
  81290. */
  81291. _this.weight = 0.58767;
  81292. /**
  81293. * Controls the density of each sample
  81294. */
  81295. _this.density = 0.926;
  81296. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  81297. engine = scene.getEngine();
  81298. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  81299. // Configure mesh
  81300. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  81301. // Configure
  81302. _this._createPass(scene, ratio.passRatio || ratio);
  81303. _this.onActivate = function (camera) {
  81304. if (!_this.isSupported) {
  81305. _this.dispose(camera);
  81306. }
  81307. _this.onActivate = null;
  81308. };
  81309. _this.onApplyObservable.add(function (effect) {
  81310. _this._updateMeshScreenCoordinates(scene);
  81311. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  81312. effect.setFloat("exposure", _this.exposure);
  81313. effect.setFloat("decay", _this.decay);
  81314. effect.setFloat("weight", _this.weight);
  81315. effect.setFloat("density", _this.density);
  81316. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  81317. });
  81318. return _this;
  81319. }
  81320. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  81321. get: function () {
  81322. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  81323. return false;
  81324. },
  81325. set: function (useDiffuseColor) {
  81326. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  81327. },
  81328. enumerable: true,
  81329. configurable: true
  81330. });
  81331. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  81332. return "VolumetricLightScatteringPostProcess";
  81333. };
  81334. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  81335. var mesh = subMesh.getMesh();
  81336. // Render this.mesh as default
  81337. if (mesh === this.mesh && mesh.material) {
  81338. return mesh.material.isReady(mesh);
  81339. }
  81340. var defines = [];
  81341. var attribs = [BABYLON.VertexBuffer.PositionKind];
  81342. var material = subMesh.getMaterial();
  81343. // Alpha test
  81344. if (material) {
  81345. if (material.needAlphaTesting()) {
  81346. defines.push("#define ALPHATEST");
  81347. }
  81348. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  81349. attribs.push(BABYLON.VertexBuffer.UVKind);
  81350. defines.push("#define UV1");
  81351. }
  81352. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  81353. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  81354. defines.push("#define UV2");
  81355. }
  81356. }
  81357. // Bones
  81358. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  81359. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  81360. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  81361. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  81362. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  81363. }
  81364. else {
  81365. defines.push("#define NUM_BONE_INFLUENCERS 0");
  81366. }
  81367. // Instances
  81368. if (useInstances) {
  81369. defines.push("#define INSTANCES");
  81370. attribs.push("world0");
  81371. attribs.push("world1");
  81372. attribs.push("world2");
  81373. attribs.push("world3");
  81374. }
  81375. // Get correct effect
  81376. var join = defines.join("\n");
  81377. if (this._cachedDefines !== join) {
  81378. this._cachedDefines = join;
  81379. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  81380. }
  81381. return this._volumetricLightScatteringPass.isReady();
  81382. };
  81383. /**
  81384. * Sets the new light position for light scattering effect
  81385. * @param {BABYLON.Vector3} The new custom light position
  81386. */
  81387. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  81388. this.customMeshPosition = position;
  81389. };
  81390. /**
  81391. * Returns the light position for light scattering effect
  81392. * @return {BABYLON.Vector3} The custom light position
  81393. */
  81394. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  81395. return this.customMeshPosition;
  81396. };
  81397. /**
  81398. * Disposes the internal assets and detaches the post-process from the camera
  81399. */
  81400. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  81401. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  81402. if (rttIndex !== -1) {
  81403. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  81404. }
  81405. this._volumetricLightScatteringRTT.dispose();
  81406. _super.prototype.dispose.call(this, camera);
  81407. };
  81408. /**
  81409. * Returns the render target texture used by the post-process
  81410. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  81411. */
  81412. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  81413. return this._volumetricLightScatteringRTT;
  81414. };
  81415. // Private methods
  81416. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  81417. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  81418. return true;
  81419. }
  81420. return false;
  81421. };
  81422. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  81423. var _this = this;
  81424. var engine = scene.getEngine();
  81425. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  81426. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81427. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81428. this._volumetricLightScatteringRTT.renderList = null;
  81429. this._volumetricLightScatteringRTT.renderParticles = false;
  81430. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  81431. var camera = this.getCamera();
  81432. if (camera) {
  81433. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  81434. }
  81435. else {
  81436. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  81437. }
  81438. // Custom render function for submeshes
  81439. var renderSubMesh = function (subMesh) {
  81440. var mesh = subMesh.getRenderingMesh();
  81441. if (_this._meshExcluded(mesh)) {
  81442. return;
  81443. }
  81444. var material = subMesh.getMaterial();
  81445. if (!material) {
  81446. return;
  81447. }
  81448. var scene = mesh.getScene();
  81449. var engine = scene.getEngine();
  81450. // Culling
  81451. engine.setState(material.backFaceCulling);
  81452. // Managing instances
  81453. var batch = mesh._getInstancesRenderList(subMesh._id);
  81454. if (batch.mustReturn) {
  81455. return;
  81456. }
  81457. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  81458. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  81459. var effect = _this._volumetricLightScatteringPass;
  81460. if (mesh === _this.mesh) {
  81461. if (subMesh.effect) {
  81462. effect = subMesh.effect;
  81463. }
  81464. else {
  81465. effect = material.getEffect();
  81466. }
  81467. }
  81468. engine.enableEffect(effect);
  81469. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  81470. if (mesh === _this.mesh) {
  81471. material.bind(mesh.getWorldMatrix(), mesh);
  81472. }
  81473. else {
  81474. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  81475. // Alpha test
  81476. if (material && material.needAlphaTesting()) {
  81477. var alphaTexture = material.getAlphaTestTexture();
  81478. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  81479. if (alphaTexture) {
  81480. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  81481. }
  81482. }
  81483. // Bones
  81484. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  81485. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  81486. }
  81487. }
  81488. // Draw
  81489. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  81490. }
  81491. };
  81492. // Render target texture callbacks
  81493. var savedSceneClearColor;
  81494. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  81495. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  81496. savedSceneClearColor = scene.clearColor;
  81497. scene.clearColor = sceneClearColor;
  81498. });
  81499. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  81500. scene.clearColor = savedSceneClearColor;
  81501. });
  81502. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  81503. var engine = scene.getEngine();
  81504. var index;
  81505. if (depthOnlySubMeshes.length) {
  81506. engine.setColorWrite(false);
  81507. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  81508. renderSubMesh(depthOnlySubMeshes.data[index]);
  81509. }
  81510. engine.setColorWrite(true);
  81511. }
  81512. for (index = 0; index < opaqueSubMeshes.length; index++) {
  81513. renderSubMesh(opaqueSubMeshes.data[index]);
  81514. }
  81515. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  81516. renderSubMesh(alphaTestSubMeshes.data[index]);
  81517. }
  81518. if (transparentSubMeshes.length) {
  81519. // Sort sub meshes
  81520. for (index = 0; index < transparentSubMeshes.length; index++) {
  81521. var submesh = transparentSubMeshes.data[index];
  81522. var boundingInfo = submesh.getBoundingInfo();
  81523. if (boundingInfo && scene.activeCamera) {
  81524. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  81525. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  81526. }
  81527. }
  81528. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  81529. sortedArray.sort(function (a, b) {
  81530. // Alpha index first
  81531. if (a._alphaIndex > b._alphaIndex) {
  81532. return 1;
  81533. }
  81534. if (a._alphaIndex < b._alphaIndex) {
  81535. return -1;
  81536. }
  81537. // Then distance to camera
  81538. if (a._distanceToCamera < b._distanceToCamera) {
  81539. return 1;
  81540. }
  81541. if (a._distanceToCamera > b._distanceToCamera) {
  81542. return -1;
  81543. }
  81544. return 0;
  81545. });
  81546. // Render sub meshes
  81547. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  81548. for (index = 0; index < sortedArray.length; index++) {
  81549. renderSubMesh(sortedArray[index]);
  81550. }
  81551. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  81552. }
  81553. };
  81554. };
  81555. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  81556. var transform = scene.getTransformMatrix();
  81557. var meshPosition;
  81558. if (this.useCustomMeshPosition) {
  81559. meshPosition = this.customMeshPosition;
  81560. }
  81561. else if (this.attachedNode) {
  81562. meshPosition = this.attachedNode.position;
  81563. }
  81564. else {
  81565. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  81566. }
  81567. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  81568. this._screenCoordinates.x = pos.x / this._viewPort.width;
  81569. this._screenCoordinates.y = pos.y / this._viewPort.height;
  81570. if (this.invert)
  81571. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  81572. };
  81573. // Static methods
  81574. /**
  81575. * Creates a default mesh for the Volumeric Light Scattering post-process
  81576. * @param {string} The mesh name
  81577. * @param {BABYLON.Scene} The scene where to create the mesh
  81578. * @return {BABYLON.Mesh} the default mesh
  81579. */
  81580. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  81581. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  81582. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  81583. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  81584. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  81585. mesh.material = material;
  81586. return mesh;
  81587. };
  81588. __decorate([
  81589. BABYLON.serializeAsVector3()
  81590. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  81591. __decorate([
  81592. BABYLON.serialize()
  81593. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  81594. __decorate([
  81595. BABYLON.serialize()
  81596. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  81597. __decorate([
  81598. BABYLON.serializeAsMeshReference()
  81599. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  81600. __decorate([
  81601. BABYLON.serialize()
  81602. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  81603. __decorate([
  81604. BABYLON.serialize()
  81605. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  81606. __decorate([
  81607. BABYLON.serialize()
  81608. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  81609. __decorate([
  81610. BABYLON.serialize()
  81611. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  81612. __decorate([
  81613. BABYLON.serialize()
  81614. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  81615. return VolumetricLightScatteringPostProcess;
  81616. }(BABYLON.PostProcess));
  81617. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  81618. })(BABYLON || (BABYLON = {}));
  81619. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  81620. //
  81621. // This post-process allows the modification of rendered colors by using
  81622. // a 'look-up table' (LUT). This effect is also called Color Grading.
  81623. //
  81624. // The object needs to be provided an url to a texture containing the color
  81625. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  81626. // Use an image editing software to tweak the LUT to match your needs.
  81627. //
  81628. // For an example of a color LUT, see here:
  81629. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  81630. // For explanations on color grading, see here:
  81631. // http://udn.epicgames.com/Three/ColorGrading.html
  81632. //
  81633. var BABYLON;
  81634. (function (BABYLON) {
  81635. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  81636. __extends(ColorCorrectionPostProcess, _super);
  81637. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  81638. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  81639. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  81640. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  81641. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81642. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81643. _this.onApply = function (effect) {
  81644. effect.setTexture("colorTable", _this._colorTableTexture);
  81645. };
  81646. return _this;
  81647. }
  81648. return ColorCorrectionPostProcess;
  81649. }(BABYLON.PostProcess));
  81650. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  81651. })(BABYLON || (BABYLON = {}));
  81652. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  81653. var BABYLON;
  81654. (function (BABYLON) {
  81655. /** Defines operator used for tonemapping */
  81656. var TonemappingOperator;
  81657. (function (TonemappingOperator) {
  81658. /** Hable */
  81659. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  81660. /** Reinhard */
  81661. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  81662. /** HejiDawson */
  81663. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  81664. /** Photographic */
  81665. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  81666. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  81667. ;
  81668. /**
  81669. * Defines a post process to apply tone mapping
  81670. */
  81671. var TonemapPostProcess = /** @class */ (function (_super) {
  81672. __extends(TonemapPostProcess, _super);
  81673. /**
  81674. * Creates a new TonemapPostProcess
  81675. * @param name defines the name of the postprocess
  81676. * @param _operator defines the operator to use
  81677. * @param exposureAdjustment defines the required exposure adjustement
  81678. * @param camera defines the camera to use (can be null)
  81679. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  81680. * @param engine defines the hosting engine (can be ignore if camera is set)
  81681. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  81682. */
  81683. function TonemapPostProcess(name, _operator,
  81684. /** Defines the required exposure adjustement */
  81685. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  81686. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  81687. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  81688. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  81689. _this._operator = _operator;
  81690. _this.exposureAdjustment = exposureAdjustment;
  81691. var defines = "#define ";
  81692. if (_this._operator === TonemappingOperator.Hable)
  81693. defines += "HABLE_TONEMAPPING";
  81694. else if (_this._operator === TonemappingOperator.Reinhard)
  81695. defines += "REINHARD_TONEMAPPING";
  81696. else if (_this._operator === TonemappingOperator.HejiDawson)
  81697. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  81698. else if (_this._operator === TonemappingOperator.Photographic)
  81699. defines += "PHOTOGRAPHIC_TONEMAPPING";
  81700. //sadly a second call to create the effect.
  81701. _this.updateEffect(defines);
  81702. _this.onApply = function (effect) {
  81703. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  81704. };
  81705. return _this;
  81706. }
  81707. return TonemapPostProcess;
  81708. }(BABYLON.PostProcess));
  81709. BABYLON.TonemapPostProcess = TonemapPostProcess;
  81710. })(BABYLON || (BABYLON = {}));
  81711. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  81712. var BABYLON;
  81713. (function (BABYLON) {
  81714. var DisplayPassPostProcess = /** @class */ (function (_super) {
  81715. __extends(DisplayPassPostProcess, _super);
  81716. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  81717. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  81718. }
  81719. return DisplayPassPostProcess;
  81720. }(BABYLON.PostProcess));
  81721. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  81722. })(BABYLON || (BABYLON = {}));
  81723. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  81724. var BABYLON;
  81725. (function (BABYLON) {
  81726. var HighlightsPostProcess = /** @class */ (function (_super) {
  81727. __extends(HighlightsPostProcess, _super);
  81728. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  81729. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  81730. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  81731. }
  81732. return HighlightsPostProcess;
  81733. }(BABYLON.PostProcess));
  81734. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  81735. })(BABYLON || (BABYLON = {}));
  81736. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  81737. var BABYLON;
  81738. (function (BABYLON) {
  81739. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  81740. __extends(ImageProcessingPostProcess, _super);
  81741. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  81742. if (camera === void 0) { camera = null; }
  81743. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  81744. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  81745. _this._fromLinearSpace = true;
  81746. /**
  81747. * Defines cache preventing GC.
  81748. */
  81749. _this._defines = {
  81750. IMAGEPROCESSING: false,
  81751. VIGNETTE: false,
  81752. VIGNETTEBLENDMODEMULTIPLY: false,
  81753. VIGNETTEBLENDMODEOPAQUE: false,
  81754. TONEMAPPING: false,
  81755. TONEMAPPING_ACES: false,
  81756. CONTRAST: false,
  81757. COLORCURVES: false,
  81758. COLORGRADING: false,
  81759. COLORGRADING3D: false,
  81760. FROMLINEARSPACE: false,
  81761. SAMPLER3DGREENDEPTH: false,
  81762. SAMPLER3DBGRMAP: false,
  81763. IMAGEPROCESSINGPOSTPROCESS: false,
  81764. EXPOSURE: false,
  81765. };
  81766. // Setup the configuration as forced by the constructor. This would then not force the
  81767. // scene materials output in linear space and let untouched the default forward pass.
  81768. if (imageProcessingConfiguration) {
  81769. imageProcessingConfiguration.applyByPostProcess = true;
  81770. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  81771. // This will cause the shader to be compiled
  81772. _this.fromLinearSpace = false;
  81773. }
  81774. // Setup the default processing configuration to the scene.
  81775. else {
  81776. _this._attachImageProcessingConfiguration(null, true);
  81777. _this.imageProcessingConfiguration.applyByPostProcess = true;
  81778. }
  81779. _this.onApply = function (effect) {
  81780. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  81781. };
  81782. return _this;
  81783. }
  81784. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  81785. /**
  81786. * Gets the image processing configuration used either in this material.
  81787. */
  81788. get: function () {
  81789. return this._imageProcessingConfiguration;
  81790. },
  81791. /**
  81792. * Sets the Default image processing configuration used either in the this material.
  81793. *
  81794. * If sets to null, the scene one is in use.
  81795. */
  81796. set: function (value) {
  81797. this._attachImageProcessingConfiguration(value);
  81798. },
  81799. enumerable: true,
  81800. configurable: true
  81801. });
  81802. /**
  81803. * Attaches a new image processing configuration to the PBR Material.
  81804. * @param configuration
  81805. */
  81806. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  81807. var _this = this;
  81808. if (doNotBuild === void 0) { doNotBuild = false; }
  81809. if (configuration === this._imageProcessingConfiguration) {
  81810. return;
  81811. }
  81812. // Detaches observer.
  81813. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  81814. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  81815. }
  81816. // Pick the scene configuration if needed.
  81817. if (!configuration) {
  81818. var scene = null;
  81819. var engine = this.getEngine();
  81820. var camera = this.getCamera();
  81821. if (camera) {
  81822. scene = camera.getScene();
  81823. }
  81824. else if (engine && engine.scenes) {
  81825. var scenes = engine.scenes;
  81826. scene = scenes[scenes.length - 1];
  81827. }
  81828. else {
  81829. scene = BABYLON.Engine.LastCreatedScene;
  81830. }
  81831. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  81832. }
  81833. else {
  81834. this._imageProcessingConfiguration = configuration;
  81835. }
  81836. // Attaches observer.
  81837. if (this._imageProcessingConfiguration) {
  81838. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  81839. _this._updateParameters();
  81840. });
  81841. }
  81842. // Ensure the effect will be rebuilt.
  81843. if (!doNotBuild) {
  81844. this._updateParameters();
  81845. }
  81846. };
  81847. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  81848. /**
  81849. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  81850. */
  81851. get: function () {
  81852. return this.imageProcessingConfiguration.colorCurves;
  81853. },
  81854. /**
  81855. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  81856. */
  81857. set: function (value) {
  81858. this.imageProcessingConfiguration.colorCurves = value;
  81859. },
  81860. enumerable: true,
  81861. configurable: true
  81862. });
  81863. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  81864. /**
  81865. * Gets wether the color curves effect is enabled.
  81866. */
  81867. get: function () {
  81868. return this.imageProcessingConfiguration.colorCurvesEnabled;
  81869. },
  81870. /**
  81871. * Sets wether the color curves effect is enabled.
  81872. */
  81873. set: function (value) {
  81874. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  81875. },
  81876. enumerable: true,
  81877. configurable: true
  81878. });
  81879. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  81880. /**
  81881. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  81882. */
  81883. get: function () {
  81884. return this.imageProcessingConfiguration.colorGradingTexture;
  81885. },
  81886. /**
  81887. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  81888. */
  81889. set: function (value) {
  81890. this.imageProcessingConfiguration.colorGradingTexture = value;
  81891. },
  81892. enumerable: true,
  81893. configurable: true
  81894. });
  81895. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  81896. /**
  81897. * Gets wether the color grading effect is enabled.
  81898. */
  81899. get: function () {
  81900. return this.imageProcessingConfiguration.colorGradingEnabled;
  81901. },
  81902. /**
  81903. * Gets wether the color grading effect is enabled.
  81904. */
  81905. set: function (value) {
  81906. this.imageProcessingConfiguration.colorGradingEnabled = value;
  81907. },
  81908. enumerable: true,
  81909. configurable: true
  81910. });
  81911. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  81912. /**
  81913. * Gets exposure used in the effect.
  81914. */
  81915. get: function () {
  81916. return this.imageProcessingConfiguration.exposure;
  81917. },
  81918. /**
  81919. * Sets exposure used in the effect.
  81920. */
  81921. set: function (value) {
  81922. this.imageProcessingConfiguration.exposure = value;
  81923. },
  81924. enumerable: true,
  81925. configurable: true
  81926. });
  81927. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  81928. /**
  81929. * Gets wether tonemapping is enabled or not.
  81930. */
  81931. get: function () {
  81932. return this._imageProcessingConfiguration.toneMappingEnabled;
  81933. },
  81934. /**
  81935. * Sets wether tonemapping is enabled or not
  81936. */
  81937. set: function (value) {
  81938. this._imageProcessingConfiguration.toneMappingEnabled = value;
  81939. },
  81940. enumerable: true,
  81941. configurable: true
  81942. });
  81943. ;
  81944. ;
  81945. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  81946. /**
  81947. * Gets contrast used in the effect.
  81948. */
  81949. get: function () {
  81950. return this.imageProcessingConfiguration.contrast;
  81951. },
  81952. /**
  81953. * Sets contrast used in the effect.
  81954. */
  81955. set: function (value) {
  81956. this.imageProcessingConfiguration.contrast = value;
  81957. },
  81958. enumerable: true,
  81959. configurable: true
  81960. });
  81961. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  81962. /**
  81963. * Gets Vignette stretch size.
  81964. */
  81965. get: function () {
  81966. return this.imageProcessingConfiguration.vignetteStretch;
  81967. },
  81968. /**
  81969. * Sets Vignette stretch size.
  81970. */
  81971. set: function (value) {
  81972. this.imageProcessingConfiguration.vignetteStretch = value;
  81973. },
  81974. enumerable: true,
  81975. configurable: true
  81976. });
  81977. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  81978. /**
  81979. * Gets Vignette centre X Offset.
  81980. */
  81981. get: function () {
  81982. return this.imageProcessingConfiguration.vignetteCentreX;
  81983. },
  81984. /**
  81985. * Sets Vignette centre X Offset.
  81986. */
  81987. set: function (value) {
  81988. this.imageProcessingConfiguration.vignetteCentreX = value;
  81989. },
  81990. enumerable: true,
  81991. configurable: true
  81992. });
  81993. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  81994. /**
  81995. * Gets Vignette centre Y Offset.
  81996. */
  81997. get: function () {
  81998. return this.imageProcessingConfiguration.vignetteCentreY;
  81999. },
  82000. /**
  82001. * Sets Vignette centre Y Offset.
  82002. */
  82003. set: function (value) {
  82004. this.imageProcessingConfiguration.vignetteCentreY = value;
  82005. },
  82006. enumerable: true,
  82007. configurable: true
  82008. });
  82009. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  82010. /**
  82011. * Gets Vignette weight or intensity of the vignette effect.
  82012. */
  82013. get: function () {
  82014. return this.imageProcessingConfiguration.vignetteWeight;
  82015. },
  82016. /**
  82017. * Sets Vignette weight or intensity of the vignette effect.
  82018. */
  82019. set: function (value) {
  82020. this.imageProcessingConfiguration.vignetteWeight = value;
  82021. },
  82022. enumerable: true,
  82023. configurable: true
  82024. });
  82025. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  82026. /**
  82027. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  82028. * if vignetteEnabled is set to true.
  82029. */
  82030. get: function () {
  82031. return this.imageProcessingConfiguration.vignetteColor;
  82032. },
  82033. /**
  82034. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  82035. * if vignetteEnabled is set to true.
  82036. */
  82037. set: function (value) {
  82038. this.imageProcessingConfiguration.vignetteColor = value;
  82039. },
  82040. enumerable: true,
  82041. configurable: true
  82042. });
  82043. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  82044. /**
  82045. * Gets Camera field of view used by the Vignette effect.
  82046. */
  82047. get: function () {
  82048. return this.imageProcessingConfiguration.vignetteCameraFov;
  82049. },
  82050. /**
  82051. * Sets Camera field of view used by the Vignette effect.
  82052. */
  82053. set: function (value) {
  82054. this.imageProcessingConfiguration.vignetteCameraFov = value;
  82055. },
  82056. enumerable: true,
  82057. configurable: true
  82058. });
  82059. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  82060. /**
  82061. * Gets the vignette blend mode allowing different kind of effect.
  82062. */
  82063. get: function () {
  82064. return this.imageProcessingConfiguration.vignetteBlendMode;
  82065. },
  82066. /**
  82067. * Sets the vignette blend mode allowing different kind of effect.
  82068. */
  82069. set: function (value) {
  82070. this.imageProcessingConfiguration.vignetteBlendMode = value;
  82071. },
  82072. enumerable: true,
  82073. configurable: true
  82074. });
  82075. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  82076. /**
  82077. * Gets wether the vignette effect is enabled.
  82078. */
  82079. get: function () {
  82080. return this.imageProcessingConfiguration.vignetteEnabled;
  82081. },
  82082. /**
  82083. * Sets wether the vignette effect is enabled.
  82084. */
  82085. set: function (value) {
  82086. this.imageProcessingConfiguration.vignetteEnabled = value;
  82087. },
  82088. enumerable: true,
  82089. configurable: true
  82090. });
  82091. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  82092. /**
  82093. * Gets wether the input of the processing is in Gamma or Linear Space.
  82094. */
  82095. get: function () {
  82096. return this._fromLinearSpace;
  82097. },
  82098. /**
  82099. * Sets wether the input of the processing is in Gamma or Linear Space.
  82100. */
  82101. set: function (value) {
  82102. if (this._fromLinearSpace === value) {
  82103. return;
  82104. }
  82105. this._fromLinearSpace = value;
  82106. this._updateParameters();
  82107. },
  82108. enumerable: true,
  82109. configurable: true
  82110. });
  82111. ImageProcessingPostProcess.prototype.getClassName = function () {
  82112. return "ImageProcessingPostProcess";
  82113. };
  82114. ImageProcessingPostProcess.prototype._updateParameters = function () {
  82115. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  82116. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  82117. var defines = "";
  82118. for (var define in this._defines) {
  82119. if (this._defines[define]) {
  82120. defines += "#define " + define + ";\r\n";
  82121. }
  82122. }
  82123. var samplers = ["textureSampler"];
  82124. var uniforms = ["scale"];
  82125. if (BABYLON.ImageProcessingConfiguration) {
  82126. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  82127. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  82128. }
  82129. this.updateEffect(defines, uniforms, samplers);
  82130. };
  82131. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  82132. _super.prototype.dispose.call(this, camera);
  82133. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  82134. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  82135. }
  82136. if (this._imageProcessingConfiguration) {
  82137. this.imageProcessingConfiguration.applyByPostProcess = false;
  82138. }
  82139. };
  82140. __decorate([
  82141. BABYLON.serialize()
  82142. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  82143. return ImageProcessingPostProcess;
  82144. }(BABYLON.PostProcess));
  82145. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  82146. })(BABYLON || (BABYLON = {}));
  82147. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  82148. var BABYLON;
  82149. (function (BABYLON) {
  82150. /**
  82151. * Class used to store bone information
  82152. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  82153. */
  82154. var Bone = /** @class */ (function (_super) {
  82155. __extends(Bone, _super);
  82156. /**
  82157. * Create a new bone
  82158. * @param name defines the bone name
  82159. * @param skeleton defines the parent skeleton
  82160. * @param parentBone defines the parent (can be null if the bone is the root)
  82161. * @param localMatrix defines the local matrix
  82162. * @param restPose defines the rest pose matrix
  82163. * @param baseMatrix defines the base matrix
  82164. * @param index defines index of the bone in the hiearchy
  82165. */
  82166. function Bone(
  82167. /**
  82168. * defines the bone name
  82169. */
  82170. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  82171. if (parentBone === void 0) { parentBone = null; }
  82172. if (localMatrix === void 0) { localMatrix = null; }
  82173. if (restPose === void 0) { restPose = null; }
  82174. if (baseMatrix === void 0) { baseMatrix = null; }
  82175. if (index === void 0) { index = null; }
  82176. var _this = _super.call(this, name, skeleton.getScene()) || this;
  82177. _this.name = name;
  82178. /**
  82179. * Gets the list of child bones
  82180. */
  82181. _this.children = new Array();
  82182. /** Gets the animations associated with this bone */
  82183. _this.animations = new Array();
  82184. /**
  82185. * @hidden Internal only
  82186. * Set this value to map this bone to a different index in the transform matrices
  82187. * Set this value to -1 to exclude the bone from the transform matrices
  82188. */
  82189. _this._index = null;
  82190. _this._absoluteTransform = new BABYLON.Matrix();
  82191. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  82192. _this._scalingDeterminant = 1;
  82193. _this._worldTransform = new BABYLON.Matrix();
  82194. _this._needToDecompose = true;
  82195. _this._needToCompose = false;
  82196. _this._skeleton = skeleton;
  82197. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  82198. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  82199. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  82200. _this._index = index;
  82201. skeleton.bones.push(_this);
  82202. _this.setParent(parentBone, false);
  82203. if (baseMatrix || localMatrix) {
  82204. _this._updateDifferenceMatrix();
  82205. }
  82206. return _this;
  82207. }
  82208. Object.defineProperty(Bone.prototype, "_matrix", {
  82209. /** @hidden */
  82210. get: function () {
  82211. this._compose();
  82212. return this._localMatrix;
  82213. },
  82214. /** @hidden */
  82215. set: function (value) {
  82216. this._localMatrix.copyFrom(value);
  82217. this._needToDecompose = true;
  82218. },
  82219. enumerable: true,
  82220. configurable: true
  82221. });
  82222. // Members
  82223. /**
  82224. * Gets the parent skeleton
  82225. * @returns a skeleton
  82226. */
  82227. Bone.prototype.getSkeleton = function () {
  82228. return this._skeleton;
  82229. };
  82230. /**
  82231. * Gets parent bone
  82232. * @returns a bone or null if the bone is the root of the bone hierarchy
  82233. */
  82234. Bone.prototype.getParent = function () {
  82235. return this._parent;
  82236. };
  82237. /**
  82238. * Sets the parent bone
  82239. * @param parent defines the parent (can be null if the bone is the root)
  82240. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  82241. */
  82242. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  82243. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  82244. if (this._parent === parent) {
  82245. return;
  82246. }
  82247. if (this._parent) {
  82248. var index = this._parent.children.indexOf(this);
  82249. if (index !== -1) {
  82250. this._parent.children.splice(index, 1);
  82251. }
  82252. }
  82253. this._parent = parent;
  82254. if (this._parent) {
  82255. this._parent.children.push(this);
  82256. }
  82257. if (updateDifferenceMatrix) {
  82258. this._updateDifferenceMatrix();
  82259. }
  82260. this.markAsDirty();
  82261. };
  82262. /**
  82263. * Gets the local matrix
  82264. * @returns a matrix
  82265. */
  82266. Bone.prototype.getLocalMatrix = function () {
  82267. this._compose();
  82268. return this._localMatrix;
  82269. };
  82270. /**
  82271. * Gets the base matrix (initial matrix which remains unchanged)
  82272. * @returns a matrix
  82273. */
  82274. Bone.prototype.getBaseMatrix = function () {
  82275. return this._baseMatrix;
  82276. };
  82277. /**
  82278. * Gets the rest pose matrix
  82279. * @returns a matrix
  82280. */
  82281. Bone.prototype.getRestPose = function () {
  82282. return this._restPose;
  82283. };
  82284. /**
  82285. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  82286. */
  82287. Bone.prototype.getWorldMatrix = function () {
  82288. return this._worldTransform;
  82289. };
  82290. /**
  82291. * Sets the local matrix to rest pose matrix
  82292. */
  82293. Bone.prototype.returnToRest = function () {
  82294. this.updateMatrix(this._restPose.clone());
  82295. };
  82296. /**
  82297. * Gets the inverse of the absolute transform matrix.
  82298. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  82299. * @returns a matrix
  82300. */
  82301. Bone.prototype.getInvertedAbsoluteTransform = function () {
  82302. return this._invertedAbsoluteTransform;
  82303. };
  82304. /**
  82305. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  82306. * @returns a matrix
  82307. */
  82308. Bone.prototype.getAbsoluteTransform = function () {
  82309. return this._absoluteTransform;
  82310. };
  82311. Object.defineProperty(Bone.prototype, "position", {
  82312. // Properties (matches AbstractMesh properties)
  82313. /** Gets or sets current position (in local space) */
  82314. get: function () {
  82315. this._decompose();
  82316. return this._localPosition;
  82317. },
  82318. set: function (newPosition) {
  82319. this._decompose();
  82320. this._localPosition.copyFrom(newPosition);
  82321. this._markAsDirtyAndCompose();
  82322. },
  82323. enumerable: true,
  82324. configurable: true
  82325. });
  82326. Object.defineProperty(Bone.prototype, "rotation", {
  82327. /** Gets or sets current rotation (in local space) */
  82328. get: function () {
  82329. return this.getRotation();
  82330. },
  82331. set: function (newRotation) {
  82332. this.setRotation(newRotation);
  82333. },
  82334. enumerable: true,
  82335. configurable: true
  82336. });
  82337. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  82338. /** Gets or sets current rotation quaternion (in local space) */
  82339. get: function () {
  82340. this._decompose();
  82341. return this._localRotation;
  82342. },
  82343. set: function (newRotation) {
  82344. this.setRotationQuaternion(newRotation);
  82345. },
  82346. enumerable: true,
  82347. configurable: true
  82348. });
  82349. Object.defineProperty(Bone.prototype, "scaling", {
  82350. /** Gets or sets current scaling (in local space) */
  82351. get: function () {
  82352. return this.getScale();
  82353. },
  82354. set: function (newScaling) {
  82355. this.setScale(newScaling);
  82356. },
  82357. enumerable: true,
  82358. configurable: true
  82359. });
  82360. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  82361. /**
  82362. * Gets the animation properties override
  82363. */
  82364. get: function () {
  82365. return this._skeleton.animationPropertiesOverride;
  82366. },
  82367. enumerable: true,
  82368. configurable: true
  82369. });
  82370. // Methods
  82371. Bone.prototype._decompose = function () {
  82372. if (!this._needToDecompose) {
  82373. return;
  82374. }
  82375. this._needToDecompose = false;
  82376. if (!this._localScaling) {
  82377. this._localScaling = BABYLON.Vector3.Zero();
  82378. this._localRotation = BABYLON.Quaternion.Zero();
  82379. this._localPosition = BABYLON.Vector3.Zero();
  82380. }
  82381. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  82382. };
  82383. Bone.prototype._compose = function () {
  82384. if (!this._needToCompose) {
  82385. return;
  82386. }
  82387. this._needToCompose = false;
  82388. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  82389. };
  82390. /**
  82391. * Update the base and local matrices
  82392. * @param matrix defines the new base or local matrix
  82393. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  82394. * @param updateLocalMatrix defines if the local matrix should be updated
  82395. */
  82396. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  82397. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  82398. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  82399. this._baseMatrix.copyFrom(matrix);
  82400. if (updateDifferenceMatrix) {
  82401. this._updateDifferenceMatrix();
  82402. }
  82403. if (updateLocalMatrix) {
  82404. this._localMatrix.copyFrom(matrix);
  82405. this._markAsDirtyAndDecompose();
  82406. }
  82407. else {
  82408. this.markAsDirty();
  82409. }
  82410. };
  82411. /** @hidden */
  82412. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  82413. if (updateChildren === void 0) { updateChildren = true; }
  82414. if (!rootMatrix) {
  82415. rootMatrix = this._baseMatrix;
  82416. }
  82417. if (this._parent) {
  82418. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  82419. }
  82420. else {
  82421. this._absoluteTransform.copyFrom(rootMatrix);
  82422. }
  82423. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  82424. if (updateChildren) {
  82425. for (var index = 0; index < this.children.length; index++) {
  82426. this.children[index]._updateDifferenceMatrix();
  82427. }
  82428. }
  82429. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  82430. };
  82431. /**
  82432. * Flag the bone as dirty (Forcing it to update everything)
  82433. */
  82434. Bone.prototype.markAsDirty = function () {
  82435. this._currentRenderId++;
  82436. this._childRenderId++;
  82437. this._skeleton._markAsDirty();
  82438. };
  82439. Bone.prototype._markAsDirtyAndCompose = function () {
  82440. this.markAsDirty();
  82441. this._needToCompose = true;
  82442. };
  82443. Bone.prototype._markAsDirtyAndDecompose = function () {
  82444. this.markAsDirty();
  82445. this._needToDecompose = true;
  82446. };
  82447. /**
  82448. * Copy an animation range from another bone
  82449. * @param source defines the source bone
  82450. * @param rangeName defines the range name to copy
  82451. * @param frameOffset defines the frame offset
  82452. * @param rescaleAsRequired defines if rescaling must be applied if required
  82453. * @param skelDimensionsRatio defines the scaling ratio
  82454. * @returns true if operation was successful
  82455. */
  82456. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  82457. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  82458. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  82459. // all animation may be coming from a library skeleton, so may need to create animation
  82460. if (this.animations.length === 0) {
  82461. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  82462. this.animations[0].setKeys([]);
  82463. }
  82464. // get animation info / verify there is such a range from the source bone
  82465. var sourceRange = source.animations[0].getRange(rangeName);
  82466. if (!sourceRange) {
  82467. return false;
  82468. }
  82469. var from = sourceRange.from;
  82470. var to = sourceRange.to;
  82471. var sourceKeys = source.animations[0].getKeys();
  82472. // rescaling prep
  82473. var sourceBoneLength = source.length;
  82474. var sourceParent = source.getParent();
  82475. var parent = this.getParent();
  82476. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  82477. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  82478. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  82479. var destKeys = this.animations[0].getKeys();
  82480. // loop vars declaration
  82481. var orig;
  82482. var origTranslation;
  82483. var mat;
  82484. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  82485. orig = sourceKeys[key];
  82486. if (orig.frame >= from && orig.frame <= to) {
  82487. if (rescaleAsRequired) {
  82488. mat = orig.value.clone();
  82489. // scale based on parent ratio, when bone has parent
  82490. if (parentScalingReqd) {
  82491. origTranslation = mat.getTranslation();
  82492. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  82493. // scale based on skeleton dimension ratio when root bone, and value is passed
  82494. }
  82495. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  82496. origTranslation = mat.getTranslation();
  82497. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  82498. // use original when root bone, and no data for skelDimensionsRatio
  82499. }
  82500. else {
  82501. mat = orig.value;
  82502. }
  82503. }
  82504. else {
  82505. mat = orig.value;
  82506. }
  82507. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  82508. }
  82509. }
  82510. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  82511. return true;
  82512. };
  82513. /**
  82514. * Translate the bone in local or world space
  82515. * @param vec The amount to translate the bone
  82516. * @param space The space that the translation is in
  82517. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82518. */
  82519. Bone.prototype.translate = function (vec, space, mesh) {
  82520. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82521. var lm = this.getLocalMatrix();
  82522. if (space == BABYLON.Space.LOCAL) {
  82523. lm.m[12] += vec.x;
  82524. lm.m[13] += vec.y;
  82525. lm.m[14] += vec.z;
  82526. }
  82527. else {
  82528. var wm = null;
  82529. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  82530. if (mesh) {
  82531. wm = mesh.getWorldMatrix();
  82532. }
  82533. this._skeleton.computeAbsoluteTransforms();
  82534. var tmat = Bone._tmpMats[0];
  82535. var tvec = Bone._tmpVecs[0];
  82536. if (this._parent) {
  82537. if (mesh && wm) {
  82538. tmat.copyFrom(this._parent.getAbsoluteTransform());
  82539. tmat.multiplyToRef(wm, tmat);
  82540. }
  82541. else {
  82542. tmat.copyFrom(this._parent.getAbsoluteTransform());
  82543. }
  82544. }
  82545. tmat.m[12] = 0;
  82546. tmat.m[13] = 0;
  82547. tmat.m[14] = 0;
  82548. tmat.invert();
  82549. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  82550. lm.m[12] += tvec.x;
  82551. lm.m[13] += tvec.y;
  82552. lm.m[14] += tvec.z;
  82553. }
  82554. this._markAsDirtyAndDecompose();
  82555. };
  82556. /**
  82557. * Set the postion of the bone in local or world space
  82558. * @param position The position to set the bone
  82559. * @param space The space that the position is in
  82560. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82561. */
  82562. Bone.prototype.setPosition = function (position, space, mesh) {
  82563. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82564. var lm = this.getLocalMatrix();
  82565. if (space == BABYLON.Space.LOCAL) {
  82566. lm.m[12] = position.x;
  82567. lm.m[13] = position.y;
  82568. lm.m[14] = position.z;
  82569. }
  82570. else {
  82571. var wm = null;
  82572. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  82573. if (mesh) {
  82574. wm = mesh.getWorldMatrix();
  82575. }
  82576. this._skeleton.computeAbsoluteTransforms();
  82577. var tmat = Bone._tmpMats[0];
  82578. var vec = Bone._tmpVecs[0];
  82579. if (this._parent) {
  82580. if (mesh && wm) {
  82581. tmat.copyFrom(this._parent.getAbsoluteTransform());
  82582. tmat.multiplyToRef(wm, tmat);
  82583. }
  82584. else {
  82585. tmat.copyFrom(this._parent.getAbsoluteTransform());
  82586. }
  82587. }
  82588. tmat.invert();
  82589. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  82590. lm.m[12] = vec.x;
  82591. lm.m[13] = vec.y;
  82592. lm.m[14] = vec.z;
  82593. }
  82594. this._markAsDirtyAndDecompose();
  82595. };
  82596. /**
  82597. * Set the absolute position of the bone (world space)
  82598. * @param position The position to set the bone
  82599. * @param mesh The mesh that this bone is attached to
  82600. */
  82601. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  82602. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  82603. };
  82604. /**
  82605. * Scale the bone on the x, y and z axes (in local space)
  82606. * @param x The amount to scale the bone on the x axis
  82607. * @param y The amount to scale the bone on the y axis
  82608. * @param z The amount to scale the bone on the z axis
  82609. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  82610. */
  82611. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  82612. if (scaleChildren === void 0) { scaleChildren = false; }
  82613. var locMat = this.getLocalMatrix();
  82614. // Apply new scaling on top of current local matrix
  82615. var scaleMat = Bone._tmpMats[0];
  82616. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  82617. scaleMat.multiplyToRef(locMat, locMat);
  82618. // Invert scaling matrix and apply the inverse to all children
  82619. scaleMat.invert();
  82620. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  82621. var child = _a[_i];
  82622. var cm = child.getLocalMatrix();
  82623. cm.multiplyToRef(scaleMat, cm);
  82624. cm.m[12] *= x;
  82625. cm.m[13] *= y;
  82626. cm.m[14] *= z;
  82627. child._markAsDirtyAndDecompose();
  82628. }
  82629. this._markAsDirtyAndDecompose();
  82630. if (scaleChildren) {
  82631. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  82632. var child = _c[_b];
  82633. child.scale(x, y, z, scaleChildren);
  82634. }
  82635. }
  82636. };
  82637. /**
  82638. * Set the bone scaling in local space
  82639. * @param scale defines the scaling vector
  82640. */
  82641. Bone.prototype.setScale = function (scale) {
  82642. this._decompose();
  82643. this._localScaling.copyFrom(scale);
  82644. this._markAsDirtyAndCompose();
  82645. };
  82646. /**
  82647. * Gets the current scaling in local space
  82648. * @returns the current scaling vector
  82649. */
  82650. Bone.prototype.getScale = function () {
  82651. this._decompose();
  82652. return this._localScaling;
  82653. };
  82654. /**
  82655. * Gets the current scaling in local space and stores it in a target vector
  82656. * @param result defines the target vector
  82657. */
  82658. Bone.prototype.getScaleToRef = function (result) {
  82659. this._decompose();
  82660. result.copyFrom(this._localScaling);
  82661. };
  82662. /**
  82663. * Set the yaw, pitch, and roll of the bone in local or world space
  82664. * @param yaw The rotation of the bone on the y axis
  82665. * @param pitch The rotation of the bone on the x axis
  82666. * @param roll The rotation of the bone on the z axis
  82667. * @param space The space that the axes of rotation are in
  82668. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82669. */
  82670. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  82671. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82672. if (space === BABYLON.Space.LOCAL) {
  82673. var quat = Bone._tmpQuat;
  82674. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  82675. this.setRotationQuaternion(quat, space, mesh);
  82676. return;
  82677. }
  82678. var rotMatInv = Bone._tmpMats[0];
  82679. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  82680. return;
  82681. }
  82682. var rotMat = Bone._tmpMats[1];
  82683. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  82684. rotMatInv.multiplyToRef(rotMat, rotMat);
  82685. this._rotateWithMatrix(rotMat, space, mesh);
  82686. };
  82687. /**
  82688. * Add a rotation to the bone on an axis in local or world space
  82689. * @param axis The axis to rotate the bone on
  82690. * @param amount The amount to rotate the bone
  82691. * @param space The space that the axis is in
  82692. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82693. */
  82694. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  82695. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82696. var rmat = Bone._tmpMats[0];
  82697. rmat.m[12] = 0;
  82698. rmat.m[13] = 0;
  82699. rmat.m[14] = 0;
  82700. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  82701. this._rotateWithMatrix(rmat, space, mesh);
  82702. };
  82703. /**
  82704. * Set the rotation of the bone to a particular axis angle in local or world space
  82705. * @param axis The axis to rotate the bone on
  82706. * @param angle The angle that the bone should be rotated to
  82707. * @param space The space that the axis is in
  82708. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82709. */
  82710. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  82711. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82712. if (space === BABYLON.Space.LOCAL) {
  82713. var quat = Bone._tmpQuat;
  82714. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  82715. this.setRotationQuaternion(quat, space, mesh);
  82716. return;
  82717. }
  82718. var rotMatInv = Bone._tmpMats[0];
  82719. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  82720. return;
  82721. }
  82722. var rotMat = Bone._tmpMats[1];
  82723. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  82724. rotMatInv.multiplyToRef(rotMat, rotMat);
  82725. this._rotateWithMatrix(rotMat, space, mesh);
  82726. };
  82727. /**
  82728. * Set the euler rotation of the bone in local of world space
  82729. * @param rotation The euler rotation that the bone should be set to
  82730. * @param space The space that the rotation is in
  82731. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82732. */
  82733. Bone.prototype.setRotation = function (rotation, space, mesh) {
  82734. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82735. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  82736. };
  82737. /**
  82738. * Set the quaternion rotation of the bone in local of world space
  82739. * @param quat The quaternion rotation that the bone should be set to
  82740. * @param space The space that the rotation is in
  82741. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82742. */
  82743. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  82744. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82745. if (space === BABYLON.Space.LOCAL) {
  82746. this._decompose();
  82747. this._localRotation.copyFrom(quat);
  82748. this._markAsDirtyAndCompose();
  82749. return;
  82750. }
  82751. var rotMatInv = Bone._tmpMats[0];
  82752. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  82753. return;
  82754. }
  82755. var rotMat = Bone._tmpMats[1];
  82756. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  82757. rotMatInv.multiplyToRef(rotMat, rotMat);
  82758. this._rotateWithMatrix(rotMat, space, mesh);
  82759. };
  82760. /**
  82761. * Set the rotation matrix of the bone in local of world space
  82762. * @param rotMat The rotation matrix that the bone should be set to
  82763. * @param space The space that the rotation is in
  82764. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82765. */
  82766. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  82767. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82768. if (space === BABYLON.Space.LOCAL) {
  82769. var quat = Bone._tmpQuat;
  82770. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  82771. this.setRotationQuaternion(quat, space, mesh);
  82772. return;
  82773. }
  82774. var rotMatInv = Bone._tmpMats[0];
  82775. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  82776. return;
  82777. }
  82778. var rotMat2 = Bone._tmpMats[1];
  82779. rotMat2.copyFrom(rotMat);
  82780. rotMatInv.multiplyToRef(rotMat, rotMat2);
  82781. this._rotateWithMatrix(rotMat2, space, mesh);
  82782. };
  82783. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  82784. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82785. var lmat = this.getLocalMatrix();
  82786. var lx = lmat.m[12];
  82787. var ly = lmat.m[13];
  82788. var lz = lmat.m[14];
  82789. var parent = this.getParent();
  82790. var parentScale = Bone._tmpMats[3];
  82791. var parentScaleInv = Bone._tmpMats[4];
  82792. if (parent && space == BABYLON.Space.WORLD) {
  82793. if (mesh) {
  82794. parentScale.copyFrom(mesh.getWorldMatrix());
  82795. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  82796. }
  82797. else {
  82798. parentScale.copyFrom(parent.getAbsoluteTransform());
  82799. }
  82800. parentScaleInv.copyFrom(parentScale);
  82801. parentScaleInv.invert();
  82802. lmat.multiplyToRef(parentScale, lmat);
  82803. lmat.multiplyToRef(rmat, lmat);
  82804. lmat.multiplyToRef(parentScaleInv, lmat);
  82805. }
  82806. else {
  82807. if (space == BABYLON.Space.WORLD && mesh) {
  82808. parentScale.copyFrom(mesh.getWorldMatrix());
  82809. parentScaleInv.copyFrom(parentScale);
  82810. parentScaleInv.invert();
  82811. lmat.multiplyToRef(parentScale, lmat);
  82812. lmat.multiplyToRef(rmat, lmat);
  82813. lmat.multiplyToRef(parentScaleInv, lmat);
  82814. }
  82815. else {
  82816. lmat.multiplyToRef(rmat, lmat);
  82817. }
  82818. }
  82819. lmat.m[12] = lx;
  82820. lmat.m[13] = ly;
  82821. lmat.m[14] = lz;
  82822. this.computeAbsoluteTransforms();
  82823. this._markAsDirtyAndDecompose();
  82824. };
  82825. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  82826. var scaleMatrix = Bone._tmpMats[2];
  82827. rotMatInv.copyFrom(this.getAbsoluteTransform());
  82828. if (mesh) {
  82829. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  82830. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  82831. }
  82832. rotMatInv.invert();
  82833. if (isNaN(rotMatInv.m[0])) {
  82834. // Matrix failed to invert.
  82835. // This can happen if scale is zero for example.
  82836. return false;
  82837. }
  82838. scaleMatrix.m[0] *= this._scalingDeterminant;
  82839. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  82840. return true;
  82841. };
  82842. /**
  82843. * Get the position of the bone in local or world space
  82844. * @param space The space that the returned position is in
  82845. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82846. * @returns The position of the bone
  82847. */
  82848. Bone.prototype.getPosition = function (space, mesh) {
  82849. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82850. if (mesh === void 0) { mesh = null; }
  82851. var pos = BABYLON.Vector3.Zero();
  82852. this.getPositionToRef(space, mesh, pos);
  82853. return pos;
  82854. };
  82855. /**
  82856. * Copy the position of the bone to a vector3 in local or world space
  82857. * @param space The space that the returned position is in
  82858. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82859. * @param result The vector3 to copy the position to
  82860. */
  82861. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  82862. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82863. if (space == BABYLON.Space.LOCAL) {
  82864. var lm = this.getLocalMatrix();
  82865. result.x = lm.m[12];
  82866. result.y = lm.m[13];
  82867. result.z = lm.m[14];
  82868. }
  82869. else {
  82870. var wm = null;
  82871. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  82872. if (mesh) {
  82873. wm = mesh.getWorldMatrix();
  82874. }
  82875. this._skeleton.computeAbsoluteTransforms();
  82876. var tmat = Bone._tmpMats[0];
  82877. if (mesh && wm) {
  82878. tmat.copyFrom(this.getAbsoluteTransform());
  82879. tmat.multiplyToRef(wm, tmat);
  82880. }
  82881. else {
  82882. tmat = this.getAbsoluteTransform();
  82883. }
  82884. result.x = tmat.m[12];
  82885. result.y = tmat.m[13];
  82886. result.z = tmat.m[14];
  82887. }
  82888. };
  82889. /**
  82890. * Get the absolute position of the bone (world space)
  82891. * @param mesh The mesh that this bone is attached to
  82892. * @returns The absolute position of the bone
  82893. */
  82894. Bone.prototype.getAbsolutePosition = function (mesh) {
  82895. if (mesh === void 0) { mesh = null; }
  82896. var pos = BABYLON.Vector3.Zero();
  82897. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  82898. return pos;
  82899. };
  82900. /**
  82901. * Copy the absolute position of the bone (world space) to the result param
  82902. * @param mesh The mesh that this bone is attached to
  82903. * @param result The vector3 to copy the absolute position to
  82904. */
  82905. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  82906. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  82907. };
  82908. /**
  82909. * Compute the absolute transforms of this bone and its children
  82910. */
  82911. Bone.prototype.computeAbsoluteTransforms = function () {
  82912. this._compose();
  82913. if (this._parent) {
  82914. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  82915. }
  82916. else {
  82917. this._absoluteTransform.copyFrom(this._localMatrix);
  82918. var poseMatrix = this._skeleton.getPoseMatrix();
  82919. if (poseMatrix) {
  82920. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  82921. }
  82922. }
  82923. var children = this.children;
  82924. var len = children.length;
  82925. for (var i = 0; i < len; i++) {
  82926. children[i].computeAbsoluteTransforms();
  82927. }
  82928. };
  82929. /**
  82930. * Get the world direction from an axis that is in the local space of the bone
  82931. * @param localAxis The local direction that is used to compute the world direction
  82932. * @param mesh The mesh that this bone is attached to
  82933. * @returns The world direction
  82934. */
  82935. Bone.prototype.getDirection = function (localAxis, mesh) {
  82936. if (mesh === void 0) { mesh = null; }
  82937. var result = BABYLON.Vector3.Zero();
  82938. this.getDirectionToRef(localAxis, mesh, result);
  82939. return result;
  82940. };
  82941. /**
  82942. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  82943. * @param localAxis The local direction that is used to compute the world direction
  82944. * @param mesh The mesh that this bone is attached to
  82945. * @param result The vector3 that the world direction will be copied to
  82946. */
  82947. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  82948. if (mesh === void 0) { mesh = null; }
  82949. var wm = null;
  82950. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  82951. if (mesh) {
  82952. wm = mesh.getWorldMatrix();
  82953. }
  82954. this._skeleton.computeAbsoluteTransforms();
  82955. var mat = Bone._tmpMats[0];
  82956. mat.copyFrom(this.getAbsoluteTransform());
  82957. if (mesh && wm) {
  82958. mat.multiplyToRef(wm, mat);
  82959. }
  82960. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  82961. result.normalize();
  82962. };
  82963. /**
  82964. * Get the euler rotation of the bone in local or world space
  82965. * @param space The space that the rotation should be in
  82966. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82967. * @returns The euler rotation
  82968. */
  82969. Bone.prototype.getRotation = function (space, mesh) {
  82970. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82971. if (mesh === void 0) { mesh = null; }
  82972. var result = BABYLON.Vector3.Zero();
  82973. this.getRotationToRef(space, mesh, result);
  82974. return result;
  82975. };
  82976. /**
  82977. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  82978. * @param space The space that the rotation should be in
  82979. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82980. * @param result The vector3 that the rotation should be copied to
  82981. */
  82982. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  82983. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82984. if (mesh === void 0) { mesh = null; }
  82985. var quat = Bone._tmpQuat;
  82986. this.getRotationQuaternionToRef(space, mesh, quat);
  82987. quat.toEulerAnglesToRef(result);
  82988. };
  82989. /**
  82990. * Get the quaternion rotation of the bone in either local or world space
  82991. * @param space The space that the rotation should be in
  82992. * @param mesh The mesh that this bone is attached to. This is only used in world space
  82993. * @returns The quaternion rotation
  82994. */
  82995. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  82996. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  82997. if (mesh === void 0) { mesh = null; }
  82998. var result = BABYLON.Quaternion.Identity();
  82999. this.getRotationQuaternionToRef(space, mesh, result);
  83000. return result;
  83001. };
  83002. /**
  83003. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  83004. * @param space The space that the rotation should be in
  83005. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83006. * @param result The quaternion that the rotation should be copied to
  83007. */
  83008. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  83009. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83010. if (mesh === void 0) { mesh = null; }
  83011. if (space == BABYLON.Space.LOCAL) {
  83012. this._decompose();
  83013. result.copyFrom(this._localRotation);
  83014. }
  83015. else {
  83016. var mat = Bone._tmpMats[0];
  83017. var amat = this.getAbsoluteTransform();
  83018. if (mesh) {
  83019. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  83020. }
  83021. else {
  83022. mat.copyFrom(amat);
  83023. }
  83024. mat.m[0] *= this._scalingDeterminant;
  83025. mat.m[1] *= this._scalingDeterminant;
  83026. mat.m[2] *= this._scalingDeterminant;
  83027. mat.decompose(undefined, result, undefined);
  83028. }
  83029. };
  83030. /**
  83031. * Get the rotation matrix of the bone in local or world space
  83032. * @param space The space that the rotation should be in
  83033. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83034. * @returns The rotation matrix
  83035. */
  83036. Bone.prototype.getRotationMatrix = function (space, mesh) {
  83037. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83038. var result = BABYLON.Matrix.Identity();
  83039. this.getRotationMatrixToRef(space, mesh, result);
  83040. return result;
  83041. };
  83042. /**
  83043. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  83044. * @param space The space that the rotation should be in
  83045. * @param mesh The mesh that this bone is attached to. This is only used in world space
  83046. * @param result The quaternion that the rotation should be copied to
  83047. */
  83048. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  83049. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  83050. if (space == BABYLON.Space.LOCAL) {
  83051. this.getLocalMatrix().getRotationMatrixToRef(result);
  83052. }
  83053. else {
  83054. var mat = Bone._tmpMats[0];
  83055. var amat = this.getAbsoluteTransform();
  83056. if (mesh) {
  83057. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  83058. }
  83059. else {
  83060. mat.copyFrom(amat);
  83061. }
  83062. mat.m[0] *= this._scalingDeterminant;
  83063. mat.m[1] *= this._scalingDeterminant;
  83064. mat.m[2] *= this._scalingDeterminant;
  83065. mat.getRotationMatrixToRef(result);
  83066. }
  83067. };
  83068. /**
  83069. * Get the world position of a point that is in the local space of the bone
  83070. * @param position The local position
  83071. * @param mesh The mesh that this bone is attached to
  83072. * @returns The world position
  83073. */
  83074. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  83075. if (mesh === void 0) { mesh = null; }
  83076. var result = BABYLON.Vector3.Zero();
  83077. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  83078. return result;
  83079. };
  83080. /**
  83081. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  83082. * @param position The local position
  83083. * @param mesh The mesh that this bone is attached to
  83084. * @param result The vector3 that the world position should be copied to
  83085. */
  83086. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  83087. if (mesh === void 0) { mesh = null; }
  83088. var wm = null;
  83089. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  83090. if (mesh) {
  83091. wm = mesh.getWorldMatrix();
  83092. }
  83093. this._skeleton.computeAbsoluteTransforms();
  83094. var tmat = Bone._tmpMats[0];
  83095. if (mesh && wm) {
  83096. tmat.copyFrom(this.getAbsoluteTransform());
  83097. tmat.multiplyToRef(wm, tmat);
  83098. }
  83099. else {
  83100. tmat = this.getAbsoluteTransform();
  83101. }
  83102. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  83103. };
  83104. /**
  83105. * Get the local position of a point that is in world space
  83106. * @param position The world position
  83107. * @param mesh The mesh that this bone is attached to
  83108. * @returns The local position
  83109. */
  83110. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  83111. if (mesh === void 0) { mesh = null; }
  83112. var result = BABYLON.Vector3.Zero();
  83113. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  83114. return result;
  83115. };
  83116. /**
  83117. * Get the local position of a point that is in world space and copy it to the result param
  83118. * @param position The world position
  83119. * @param mesh The mesh that this bone is attached to
  83120. * @param result The vector3 that the local position should be copied to
  83121. */
  83122. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  83123. if (mesh === void 0) { mesh = null; }
  83124. var wm = null;
  83125. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  83126. if (mesh) {
  83127. wm = mesh.getWorldMatrix();
  83128. }
  83129. this._skeleton.computeAbsoluteTransforms();
  83130. var tmat = Bone._tmpMats[0];
  83131. tmat.copyFrom(this.getAbsoluteTransform());
  83132. if (mesh && wm) {
  83133. tmat.multiplyToRef(wm, tmat);
  83134. }
  83135. tmat.invert();
  83136. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  83137. };
  83138. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83139. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  83140. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  83141. return Bone;
  83142. }(BABYLON.Node));
  83143. BABYLON.Bone = Bone;
  83144. })(BABYLON || (BABYLON = {}));
  83145. //# sourceMappingURL=babylon.bone.js.map
  83146. var BABYLON;
  83147. (function (BABYLON) {
  83148. /**
  83149. * Class used to apply inverse kinematics to bones
  83150. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  83151. */
  83152. var BoneIKController = /** @class */ (function () {
  83153. /**
  83154. * Creates a new BoneIKController
  83155. * @param mesh defines the mesh to control
  83156. * @param bone defines the bone to control
  83157. * @param options defines options to set up the controller
  83158. */
  83159. function BoneIKController(mesh, bone, options) {
  83160. /**
  83161. * Gets or sets the target position
  83162. */
  83163. this.targetPosition = BABYLON.Vector3.Zero();
  83164. /**
  83165. * Gets or sets the pole target position
  83166. */
  83167. this.poleTargetPosition = BABYLON.Vector3.Zero();
  83168. /**
  83169. * Gets or sets the pole target local offset
  83170. */
  83171. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  83172. /**
  83173. * Gets or sets the pole angle
  83174. */
  83175. this.poleAngle = 0;
  83176. /**
  83177. * 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)
  83178. */
  83179. this.slerpAmount = 1;
  83180. this._bone1Quat = BABYLON.Quaternion.Identity();
  83181. this._bone1Mat = BABYLON.Matrix.Identity();
  83182. this._bone2Ang = Math.PI;
  83183. this._maxAngle = Math.PI;
  83184. this._rightHandedSystem = false;
  83185. this._bendAxis = BABYLON.Vector3.Right();
  83186. this._slerping = false;
  83187. this._adjustRoll = 0;
  83188. this._bone2 = bone;
  83189. this._bone1 = bone.getParent();
  83190. if (!this._bone1) {
  83191. return;
  83192. }
  83193. this.mesh = mesh;
  83194. var bonePos = bone.getPosition();
  83195. if (bone.getAbsoluteTransform().determinant() > 0) {
  83196. this._rightHandedSystem = true;
  83197. this._bendAxis.x = 0;
  83198. this._bendAxis.y = 0;
  83199. this._bendAxis.z = -1;
  83200. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  83201. this._adjustRoll = Math.PI * .5;
  83202. this._bendAxis.z = 1;
  83203. }
  83204. }
  83205. if (this._bone1.length) {
  83206. var boneScale1 = this._bone1.getScale();
  83207. var boneScale2 = this._bone2.getScale();
  83208. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  83209. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  83210. }
  83211. else if (this._bone1.children[0]) {
  83212. mesh.computeWorldMatrix(true);
  83213. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  83214. var pos2 = this._bone2.getAbsolutePosition(mesh);
  83215. var pos3 = this._bone1.getAbsolutePosition(mesh);
  83216. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  83217. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  83218. }
  83219. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  83220. this.maxAngle = Math.PI;
  83221. if (options) {
  83222. if (options.targetMesh) {
  83223. this.targetMesh = options.targetMesh;
  83224. this.targetMesh.computeWorldMatrix(true);
  83225. }
  83226. if (options.poleTargetMesh) {
  83227. this.poleTargetMesh = options.poleTargetMesh;
  83228. this.poleTargetMesh.computeWorldMatrix(true);
  83229. }
  83230. else if (options.poleTargetBone) {
  83231. this.poleTargetBone = options.poleTargetBone;
  83232. }
  83233. else if (this._bone1.getParent()) {
  83234. this.poleTargetBone = this._bone1.getParent();
  83235. }
  83236. if (options.poleTargetLocalOffset) {
  83237. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  83238. }
  83239. if (options.poleAngle) {
  83240. this.poleAngle = options.poleAngle;
  83241. }
  83242. if (options.bendAxis) {
  83243. this._bendAxis.copyFrom(options.bendAxis);
  83244. }
  83245. if (options.maxAngle) {
  83246. this.maxAngle = options.maxAngle;
  83247. }
  83248. if (options.slerpAmount) {
  83249. this.slerpAmount = options.slerpAmount;
  83250. }
  83251. }
  83252. }
  83253. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  83254. /**
  83255. * Gets or sets maximum allowed angle
  83256. */
  83257. get: function () {
  83258. return this._maxAngle;
  83259. },
  83260. set: function (value) {
  83261. this._setMaxAngle(value);
  83262. },
  83263. enumerable: true,
  83264. configurable: true
  83265. });
  83266. BoneIKController.prototype._setMaxAngle = function (ang) {
  83267. if (ang < 0) {
  83268. ang = 0;
  83269. }
  83270. if (ang > Math.PI || ang == undefined) {
  83271. ang = Math.PI;
  83272. }
  83273. this._maxAngle = ang;
  83274. var a = this._bone1Length;
  83275. var b = this._bone2Length;
  83276. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  83277. };
  83278. /**
  83279. * Force the controller to update the bones
  83280. */
  83281. BoneIKController.prototype.update = function () {
  83282. var bone1 = this._bone1;
  83283. if (!bone1) {
  83284. return;
  83285. }
  83286. var target = this.targetPosition;
  83287. var poleTarget = this.poleTargetPosition;
  83288. var mat1 = BoneIKController._tmpMats[0];
  83289. var mat2 = BoneIKController._tmpMats[1];
  83290. if (this.targetMesh) {
  83291. target.copyFrom(this.targetMesh.getAbsolutePosition());
  83292. }
  83293. if (this.poleTargetBone) {
  83294. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  83295. }
  83296. else if (this.poleTargetMesh) {
  83297. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  83298. }
  83299. var bonePos = BoneIKController._tmpVecs[0];
  83300. var zaxis = BoneIKController._tmpVecs[1];
  83301. var xaxis = BoneIKController._tmpVecs[2];
  83302. var yaxis = BoneIKController._tmpVecs[3];
  83303. var upAxis = BoneIKController._tmpVecs[4];
  83304. var _tmpQuat = BoneIKController._tmpQuat;
  83305. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  83306. poleTarget.subtractToRef(bonePos, upAxis);
  83307. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  83308. upAxis.y = 1;
  83309. }
  83310. else {
  83311. upAxis.normalize();
  83312. }
  83313. target.subtractToRef(bonePos, yaxis);
  83314. yaxis.normalize();
  83315. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  83316. zaxis.normalize();
  83317. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  83318. xaxis.normalize();
  83319. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  83320. var a = this._bone1Length;
  83321. var b = this._bone2Length;
  83322. var c = BABYLON.Vector3.Distance(bonePos, target);
  83323. if (this._maxReach > 0) {
  83324. c = Math.min(this._maxReach, c);
  83325. }
  83326. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  83327. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  83328. if (acosa > 1) {
  83329. acosa = 1;
  83330. }
  83331. if (acosb > 1) {
  83332. acosb = 1;
  83333. }
  83334. if (acosa < -1) {
  83335. acosa = -1;
  83336. }
  83337. if (acosb < -1) {
  83338. acosb = -1;
  83339. }
  83340. var angA = Math.acos(acosa);
  83341. var angB = Math.acos(acosb);
  83342. var angC = -angA - angB;
  83343. if (this._rightHandedSystem) {
  83344. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  83345. mat2.multiplyToRef(mat1, mat1);
  83346. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  83347. mat2.multiplyToRef(mat1, mat1);
  83348. }
  83349. else {
  83350. var _tmpVec = BoneIKController._tmpVecs[5];
  83351. _tmpVec.copyFrom(this._bendAxis);
  83352. _tmpVec.x *= -1;
  83353. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  83354. mat2.multiplyToRef(mat1, mat1);
  83355. }
  83356. if (this.poleAngle) {
  83357. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  83358. mat1.multiplyToRef(mat2, mat1);
  83359. }
  83360. if (this._bone1) {
  83361. if (this.slerpAmount < 1) {
  83362. if (!this._slerping) {
  83363. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  83364. }
  83365. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  83366. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  83367. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  83368. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  83369. this._slerping = true;
  83370. }
  83371. else {
  83372. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  83373. this._bone1Mat.copyFrom(mat1);
  83374. this._slerping = false;
  83375. }
  83376. }
  83377. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  83378. this._bone2Ang = angC;
  83379. };
  83380. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  83381. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  83382. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  83383. return BoneIKController;
  83384. }());
  83385. BABYLON.BoneIKController = BoneIKController;
  83386. })(BABYLON || (BABYLON = {}));
  83387. //# sourceMappingURL=babylon.boneIKController.js.map
  83388. var BABYLON;
  83389. (function (BABYLON) {
  83390. /**
  83391. * Class used to make a bone look toward a point in space
  83392. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  83393. */
  83394. var BoneLookController = /** @class */ (function () {
  83395. /**
  83396. * Create a BoneLookController
  83397. * @param mesh the mesh that the bone belongs to
  83398. * @param bone the bone that will be looking to the target
  83399. * @param target the target Vector3 to look at
  83400. * @param settings optional settings:
  83401. * * maxYaw: the maximum angle the bone will yaw to
  83402. * * minYaw: the minimum angle the bone will yaw to
  83403. * * maxPitch: the maximum angle the bone will pitch to
  83404. * * minPitch: the minimum angle the bone will yaw to
  83405. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  83406. * * upAxis: the up axis of the coordinate system
  83407. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  83408. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  83409. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  83410. * * adjustYaw: used to make an adjustment to the yaw of the bone
  83411. * * adjustPitch: used to make an adjustment to the pitch of the bone
  83412. * * adjustRoll: used to make an adjustment to the roll of the bone
  83413. **/
  83414. function BoneLookController(mesh, bone, target, options) {
  83415. /**
  83416. * The up axis of the coordinate system that is used when the bone is rotated
  83417. */
  83418. this.upAxis = BABYLON.Vector3.Up();
  83419. /**
  83420. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  83421. */
  83422. this.upAxisSpace = BABYLON.Space.LOCAL;
  83423. /**
  83424. * Used to make an adjustment to the yaw of the bone
  83425. */
  83426. this.adjustYaw = 0;
  83427. /**
  83428. * Used to make an adjustment to the pitch of the bone
  83429. */
  83430. this.adjustPitch = 0;
  83431. /**
  83432. * Used to make an adjustment to the roll of the bone
  83433. */
  83434. this.adjustRoll = 0;
  83435. /**
  83436. * 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)
  83437. */
  83438. this.slerpAmount = 1;
  83439. this._boneQuat = BABYLON.Quaternion.Identity();
  83440. this._slerping = false;
  83441. this._firstFrameSkipped = false;
  83442. this._fowardAxis = BABYLON.Vector3.Forward();
  83443. this.mesh = mesh;
  83444. this.bone = bone;
  83445. this.target = target;
  83446. if (options) {
  83447. if (options.adjustYaw) {
  83448. this.adjustYaw = options.adjustYaw;
  83449. }
  83450. if (options.adjustPitch) {
  83451. this.adjustPitch = options.adjustPitch;
  83452. }
  83453. if (options.adjustRoll) {
  83454. this.adjustRoll = options.adjustRoll;
  83455. }
  83456. if (options.maxYaw != null) {
  83457. this.maxYaw = options.maxYaw;
  83458. }
  83459. else {
  83460. this.maxYaw = Math.PI;
  83461. }
  83462. if (options.minYaw != null) {
  83463. this.minYaw = options.minYaw;
  83464. }
  83465. else {
  83466. this.minYaw = -Math.PI;
  83467. }
  83468. if (options.maxPitch != null) {
  83469. this.maxPitch = options.maxPitch;
  83470. }
  83471. else {
  83472. this.maxPitch = Math.PI;
  83473. }
  83474. if (options.minPitch != null) {
  83475. this.minPitch = options.minPitch;
  83476. }
  83477. else {
  83478. this.minPitch = -Math.PI;
  83479. }
  83480. if (options.slerpAmount != null) {
  83481. this.slerpAmount = options.slerpAmount;
  83482. }
  83483. if (options.upAxis != null) {
  83484. this.upAxis = options.upAxis;
  83485. }
  83486. if (options.upAxisSpace != null) {
  83487. this.upAxisSpace = options.upAxisSpace;
  83488. }
  83489. if (options.yawAxis != null || options.pitchAxis != null) {
  83490. var newYawAxis = BABYLON.Axis.Y;
  83491. var newPitchAxis = BABYLON.Axis.X;
  83492. if (options.yawAxis != null) {
  83493. newYawAxis = options.yawAxis.clone();
  83494. newYawAxis.normalize();
  83495. }
  83496. if (options.pitchAxis != null) {
  83497. newPitchAxis = options.pitchAxis.clone();
  83498. newPitchAxis.normalize();
  83499. }
  83500. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  83501. this._transformYawPitch = BABYLON.Matrix.Identity();
  83502. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  83503. this._transformYawPitchInv = this._transformYawPitch.clone();
  83504. this._transformYawPitch.invert();
  83505. }
  83506. }
  83507. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  83508. this.upAxisSpace = BABYLON.Space.LOCAL;
  83509. }
  83510. }
  83511. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  83512. /**
  83513. * Gets or sets the minimum yaw angle that the bone can look to
  83514. */
  83515. get: function () {
  83516. return this._minYaw;
  83517. },
  83518. set: function (value) {
  83519. this._minYaw = value;
  83520. this._minYawSin = Math.sin(value);
  83521. this._minYawCos = Math.cos(value);
  83522. if (this._maxYaw != null) {
  83523. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  83524. this._yawRange = this._maxYaw - this._minYaw;
  83525. }
  83526. },
  83527. enumerable: true,
  83528. configurable: true
  83529. });
  83530. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  83531. /**
  83532. * Gets or sets the maximum yaw angle that the bone can look to
  83533. */
  83534. get: function () {
  83535. return this._maxYaw;
  83536. },
  83537. set: function (value) {
  83538. this._maxYaw = value;
  83539. this._maxYawSin = Math.sin(value);
  83540. this._maxYawCos = Math.cos(value);
  83541. if (this._minYaw != null) {
  83542. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  83543. this._yawRange = this._maxYaw - this._minYaw;
  83544. }
  83545. },
  83546. enumerable: true,
  83547. configurable: true
  83548. });
  83549. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  83550. /**
  83551. * Gets or sets the minimum pitch angle that the bone can look to
  83552. */
  83553. get: function () {
  83554. return this._minPitch;
  83555. },
  83556. set: function (value) {
  83557. this._minPitch = value;
  83558. this._minPitchTan = Math.tan(value);
  83559. },
  83560. enumerable: true,
  83561. configurable: true
  83562. });
  83563. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  83564. /**
  83565. * Gets or sets the maximum pitch angle that the bone can look to
  83566. */
  83567. get: function () {
  83568. return this._maxPitch;
  83569. },
  83570. set: function (value) {
  83571. this._maxPitch = value;
  83572. this._maxPitchTan = Math.tan(value);
  83573. },
  83574. enumerable: true,
  83575. configurable: true
  83576. });
  83577. /**
  83578. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  83579. */
  83580. BoneLookController.prototype.update = function () {
  83581. //skip the first frame when slerping so that the mesh rotation is correct
  83582. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  83583. this._firstFrameSkipped = true;
  83584. return;
  83585. }
  83586. var bone = this.bone;
  83587. var bonePos = BoneLookController._tmpVecs[0];
  83588. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  83589. var target = this.target;
  83590. var _tmpMat1 = BoneLookController._tmpMats[0];
  83591. var _tmpMat2 = BoneLookController._tmpMats[1];
  83592. var mesh = this.mesh;
  83593. var parentBone = bone.getParent();
  83594. var upAxis = BoneLookController._tmpVecs[1];
  83595. upAxis.copyFrom(this.upAxis);
  83596. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  83597. if (this._transformYawPitch) {
  83598. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  83599. }
  83600. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  83601. }
  83602. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  83603. mesh.getDirectionToRef(upAxis, upAxis);
  83604. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  83605. upAxis.normalize();
  83606. }
  83607. }
  83608. var checkYaw = false;
  83609. var checkPitch = false;
  83610. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  83611. checkYaw = true;
  83612. }
  83613. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  83614. checkPitch = true;
  83615. }
  83616. if (checkYaw || checkPitch) {
  83617. var spaceMat = BoneLookController._tmpMats[2];
  83618. var spaceMatInv = BoneLookController._tmpMats[3];
  83619. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  83620. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  83621. }
  83622. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  83623. spaceMat.copyFrom(mesh.getWorldMatrix());
  83624. }
  83625. else {
  83626. var forwardAxis = BoneLookController._tmpVecs[2];
  83627. forwardAxis.copyFrom(this._fowardAxis);
  83628. if (this._transformYawPitch) {
  83629. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  83630. }
  83631. if (parentBone) {
  83632. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  83633. }
  83634. else {
  83635. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  83636. }
  83637. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  83638. rightAxis.normalize();
  83639. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  83640. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  83641. }
  83642. spaceMat.invertToRef(spaceMatInv);
  83643. var xzlen = null;
  83644. if (checkPitch) {
  83645. var localTarget = BoneLookController._tmpVecs[3];
  83646. target.subtractToRef(bonePos, localTarget);
  83647. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  83648. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  83649. var pitch = Math.atan2(localTarget.y, xzlen);
  83650. var newPitch = pitch;
  83651. if (pitch > this._maxPitch) {
  83652. localTarget.y = this._maxPitchTan * xzlen;
  83653. newPitch = this._maxPitch;
  83654. }
  83655. else if (pitch < this._minPitch) {
  83656. localTarget.y = this._minPitchTan * xzlen;
  83657. newPitch = this._minPitch;
  83658. }
  83659. if (pitch != newPitch) {
  83660. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  83661. localTarget.addInPlace(bonePos);
  83662. target = localTarget;
  83663. }
  83664. }
  83665. if (checkYaw) {
  83666. var localTarget = BoneLookController._tmpVecs[4];
  83667. target.subtractToRef(bonePos, localTarget);
  83668. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  83669. var yaw = Math.atan2(localTarget.x, localTarget.z);
  83670. var newYaw = yaw;
  83671. if (yaw > this._maxYaw || yaw < this._minYaw) {
  83672. if (xzlen == null) {
  83673. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  83674. }
  83675. if (this._yawRange > Math.PI) {
  83676. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  83677. localTarget.z = this._maxYawCos * xzlen;
  83678. localTarget.x = this._maxYawSin * xzlen;
  83679. newYaw = this._maxYaw;
  83680. }
  83681. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  83682. localTarget.z = this._minYawCos * xzlen;
  83683. localTarget.x = this._minYawSin * xzlen;
  83684. newYaw = this._minYaw;
  83685. }
  83686. }
  83687. else {
  83688. if (yaw > this._maxYaw) {
  83689. localTarget.z = this._maxYawCos * xzlen;
  83690. localTarget.x = this._maxYawSin * xzlen;
  83691. newYaw = this._maxYaw;
  83692. }
  83693. else if (yaw < this._minYaw) {
  83694. localTarget.z = this._minYawCos * xzlen;
  83695. localTarget.x = this._minYawSin * xzlen;
  83696. newYaw = this._minYaw;
  83697. }
  83698. }
  83699. }
  83700. if (this._slerping && this._yawRange > Math.PI) {
  83701. //are we going to be crossing into the min/max region?
  83702. var boneFwd = BoneLookController._tmpVecs[8];
  83703. boneFwd.copyFrom(BABYLON.Axis.Z);
  83704. if (this._transformYawPitch) {
  83705. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  83706. }
  83707. var boneRotMat = BoneLookController._tmpMats[4];
  83708. this._boneQuat.toRotationMatrix(boneRotMat);
  83709. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  83710. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  83711. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  83712. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  83713. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  83714. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  83715. if (angBtwTar > angBtwMidYaw) {
  83716. if (xzlen == null) {
  83717. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  83718. }
  83719. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  83720. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  83721. if (angBtwMin < angBtwMax) {
  83722. newYaw = boneYaw + Math.PI * .75;
  83723. localTarget.z = Math.cos(newYaw) * xzlen;
  83724. localTarget.x = Math.sin(newYaw) * xzlen;
  83725. }
  83726. else {
  83727. newYaw = boneYaw - Math.PI * .75;
  83728. localTarget.z = Math.cos(newYaw) * xzlen;
  83729. localTarget.x = Math.sin(newYaw) * xzlen;
  83730. }
  83731. }
  83732. }
  83733. if (yaw != newYaw) {
  83734. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  83735. localTarget.addInPlace(bonePos);
  83736. target = localTarget;
  83737. }
  83738. }
  83739. }
  83740. var zaxis = BoneLookController._tmpVecs[5];
  83741. var xaxis = BoneLookController._tmpVecs[6];
  83742. var yaxis = BoneLookController._tmpVecs[7];
  83743. var _tmpQuat = BoneLookController._tmpQuat;
  83744. target.subtractToRef(bonePos, zaxis);
  83745. zaxis.normalize();
  83746. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  83747. xaxis.normalize();
  83748. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  83749. yaxis.normalize();
  83750. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  83751. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  83752. return;
  83753. }
  83754. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  83755. return;
  83756. }
  83757. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  83758. return;
  83759. }
  83760. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  83761. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  83762. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  83763. }
  83764. if (this.slerpAmount < 1) {
  83765. if (!this._slerping) {
  83766. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  83767. }
  83768. if (this._transformYawPitch) {
  83769. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  83770. }
  83771. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  83772. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  83773. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  83774. this._slerping = true;
  83775. }
  83776. else {
  83777. if (this._transformYawPitch) {
  83778. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  83779. }
  83780. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  83781. this._slerping = false;
  83782. }
  83783. };
  83784. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  83785. var angDiff = ang2 - ang1;
  83786. angDiff %= Math.PI * 2;
  83787. if (angDiff > Math.PI) {
  83788. angDiff -= Math.PI * 2;
  83789. }
  83790. else if (angDiff < -Math.PI) {
  83791. angDiff += Math.PI * 2;
  83792. }
  83793. return angDiff;
  83794. };
  83795. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  83796. ang1 %= (2 * Math.PI);
  83797. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  83798. ang2 %= (2 * Math.PI);
  83799. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  83800. var ab = 0;
  83801. if (ang1 < ang2) {
  83802. ab = ang2 - ang1;
  83803. }
  83804. else {
  83805. ab = ang1 - ang2;
  83806. }
  83807. if (ab > Math.PI) {
  83808. ab = Math.PI * 2 - ab;
  83809. }
  83810. return ab;
  83811. };
  83812. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  83813. ang %= (2 * Math.PI);
  83814. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  83815. ang1 %= (2 * Math.PI);
  83816. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  83817. ang2 %= (2 * Math.PI);
  83818. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  83819. if (ang1 < ang2) {
  83820. if (ang > ang1 && ang < ang2) {
  83821. return true;
  83822. }
  83823. }
  83824. else {
  83825. if (ang > ang2 && ang < ang1) {
  83826. return true;
  83827. }
  83828. }
  83829. return false;
  83830. };
  83831. 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()];
  83832. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  83833. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  83834. return BoneLookController;
  83835. }());
  83836. BABYLON.BoneLookController = BoneLookController;
  83837. })(BABYLON || (BABYLON = {}));
  83838. //# sourceMappingURL=babylon.boneLookController.js.map
  83839. var BABYLON;
  83840. (function (BABYLON) {
  83841. /**
  83842. * Class used to handle skinning animations
  83843. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  83844. */
  83845. var Skeleton = /** @class */ (function () {
  83846. /**
  83847. * Creates a new skeleton
  83848. * @param name defines the skeleton name
  83849. * @param id defines the skeleton Id
  83850. * @param scene defines the hosting scene
  83851. */
  83852. function Skeleton(
  83853. /** defines the skeleton name */
  83854. name,
  83855. /** defines the skeleton Id */
  83856. id, scene) {
  83857. this.name = name;
  83858. this.id = id;
  83859. /**
  83860. * Gets the list of child bones
  83861. */
  83862. this.bones = new Array();
  83863. /**
  83864. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  83865. */
  83866. this.needInitialSkinMatrix = false;
  83867. this._isDirty = true;
  83868. this._meshesWithPoseMatrix = new Array();
  83869. this._identity = BABYLON.Matrix.Identity();
  83870. this._ranges = {};
  83871. this._lastAbsoluteTransformsUpdateId = -1;
  83872. /**
  83873. * Specifies if the skeleton should be serialized
  83874. */
  83875. this.doNotSerialize = false;
  83876. this._animationPropertiesOverride = null;
  83877. // Events
  83878. /**
  83879. * An observable triggered before computing the skeleton's matrices
  83880. */
  83881. this.onBeforeComputeObservable = new BABYLON.Observable();
  83882. this.bones = [];
  83883. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  83884. scene.skeletons.push(this);
  83885. //make sure it will recalculate the matrix next time prepare is called.
  83886. this._isDirty = true;
  83887. }
  83888. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  83889. /**
  83890. * Gets or sets the animation properties override
  83891. */
  83892. get: function () {
  83893. if (!this._animationPropertiesOverride) {
  83894. return this._scene.animationPropertiesOverride;
  83895. }
  83896. return this._animationPropertiesOverride;
  83897. },
  83898. set: function (value) {
  83899. this._animationPropertiesOverride = value;
  83900. },
  83901. enumerable: true,
  83902. configurable: true
  83903. });
  83904. // Members
  83905. /**
  83906. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  83907. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  83908. * @returns a Float32Array containing matrices data
  83909. */
  83910. Skeleton.prototype.getTransformMatrices = function (mesh) {
  83911. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  83912. return mesh._bonesTransformMatrices;
  83913. }
  83914. if (!this._transformMatrices) {
  83915. this.prepare();
  83916. }
  83917. return this._transformMatrices;
  83918. };
  83919. /**
  83920. * Gets the current hosting scene
  83921. * @returns a scene object
  83922. */
  83923. Skeleton.prototype.getScene = function () {
  83924. return this._scene;
  83925. };
  83926. // Methods
  83927. /**
  83928. * Gets a string representing the current skeleton data
  83929. * @param fullDetails defines a boolean indicating if we want a verbose version
  83930. * @returns a string representing the current skeleton data
  83931. */
  83932. Skeleton.prototype.toString = function (fullDetails) {
  83933. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  83934. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  83935. if (fullDetails) {
  83936. ret += ", Ranges: {";
  83937. var first = true;
  83938. for (var name_1 in this._ranges) {
  83939. if (first) {
  83940. ret += ", ";
  83941. first = false;
  83942. }
  83943. ret += name_1;
  83944. }
  83945. ret += "}";
  83946. }
  83947. return ret;
  83948. };
  83949. /**
  83950. * Get bone's index searching by name
  83951. * @param name defines bone's name to search for
  83952. * @return the indice of the bone. Returns -1 if not found
  83953. */
  83954. Skeleton.prototype.getBoneIndexByName = function (name) {
  83955. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  83956. if (this.bones[boneIndex].name === name) {
  83957. return boneIndex;
  83958. }
  83959. }
  83960. return -1;
  83961. };
  83962. /**
  83963. * Creater a new animation range
  83964. * @param name defines the name of the range
  83965. * @param from defines the start key
  83966. * @param to defines the end key
  83967. */
  83968. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  83969. // check name not already in use
  83970. if (!this._ranges[name]) {
  83971. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  83972. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  83973. if (this.bones[i].animations[0]) {
  83974. this.bones[i].animations[0].createRange(name, from, to);
  83975. }
  83976. }
  83977. }
  83978. };
  83979. /**
  83980. * Delete a specific animation range
  83981. * @param name defines the name of the range
  83982. * @param deleteFrames defines if frames must be removed as well
  83983. */
  83984. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  83985. if (deleteFrames === void 0) { deleteFrames = true; }
  83986. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  83987. if (this.bones[i].animations[0]) {
  83988. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  83989. }
  83990. }
  83991. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  83992. };
  83993. /**
  83994. * Gets a specific animation range
  83995. * @param name defines the name of the range to look for
  83996. * @returns the requested animation range or null if not found
  83997. */
  83998. Skeleton.prototype.getAnimationRange = function (name) {
  83999. return this._ranges[name];
  84000. };
  84001. /**
  84002. * Gets the list of all animation ranges defined on this skeleton
  84003. * @returns an array
  84004. */
  84005. Skeleton.prototype.getAnimationRanges = function () {
  84006. var animationRanges = [];
  84007. var name;
  84008. var i = 0;
  84009. for (name in this._ranges) {
  84010. animationRanges[i] = this._ranges[name];
  84011. i++;
  84012. }
  84013. return animationRanges;
  84014. };
  84015. /**
  84016. * Copy animation range from a source skeleton.
  84017. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  84018. * @param source defines the source skeleton
  84019. * @param name defines the name of the range to copy
  84020. * @param rescaleAsRequired defines if rescaling must be applied if required
  84021. * @returns true if operation was successful
  84022. */
  84023. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  84024. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  84025. if (this._ranges[name] || !source.getAnimationRange(name)) {
  84026. return false;
  84027. }
  84028. var ret = true;
  84029. var frameOffset = this._getHighestAnimationFrame() + 1;
  84030. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  84031. var boneDict = {};
  84032. var sourceBones = source.bones;
  84033. var nBones;
  84034. var i;
  84035. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  84036. boneDict[sourceBones[i].name] = sourceBones[i];
  84037. }
  84038. if (this.bones.length !== sourceBones.length) {
  84039. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  84040. ret = false;
  84041. }
  84042. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  84043. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  84044. var boneName = this.bones[i].name;
  84045. var sourceBone = boneDict[boneName];
  84046. if (sourceBone) {
  84047. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  84048. }
  84049. else {
  84050. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  84051. ret = false;
  84052. }
  84053. }
  84054. // do not call createAnimationRange(), since it also is done to bones, which was already done
  84055. var range = source.getAnimationRange(name);
  84056. if (range) {
  84057. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  84058. }
  84059. return ret;
  84060. };
  84061. /**
  84062. * Forces the skeleton to go to rest pose
  84063. */
  84064. Skeleton.prototype.returnToRest = function () {
  84065. for (var index = 0; index < this.bones.length; index++) {
  84066. this.bones[index].returnToRest();
  84067. }
  84068. };
  84069. Skeleton.prototype._getHighestAnimationFrame = function () {
  84070. var ret = 0;
  84071. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  84072. if (this.bones[i].animations[0]) {
  84073. var highest = this.bones[i].animations[0].getHighestFrame();
  84074. if (ret < highest) {
  84075. ret = highest;
  84076. }
  84077. }
  84078. }
  84079. return ret;
  84080. };
  84081. /**
  84082. * Begin a specific animation range
  84083. * @param name defines the name of the range to start
  84084. * @param loop defines if looping must be turned on (false by default)
  84085. * @param speedRatio defines the speed ratio to apply (1 by default)
  84086. * @param onAnimationEnd defines a callback which will be called when animation will end
  84087. * @returns a new animatable
  84088. */
  84089. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  84090. var range = this.getAnimationRange(name);
  84091. if (!range) {
  84092. return null;
  84093. }
  84094. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  84095. };
  84096. /** @hidden */
  84097. Skeleton.prototype._markAsDirty = function () {
  84098. this._isDirty = true;
  84099. };
  84100. /** @hidden */
  84101. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  84102. this._meshesWithPoseMatrix.push(mesh);
  84103. };
  84104. /** @hidden */
  84105. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  84106. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  84107. if (index > -1) {
  84108. this._meshesWithPoseMatrix.splice(index, 1);
  84109. }
  84110. };
  84111. /** @hidden */
  84112. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  84113. this.onBeforeComputeObservable.notifyObservers(this);
  84114. for (var index = 0; index < this.bones.length; index++) {
  84115. var bone = this.bones[index];
  84116. var parentBone = bone.getParent();
  84117. if (parentBone) {
  84118. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  84119. }
  84120. else {
  84121. if (initialSkinMatrix) {
  84122. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  84123. }
  84124. else {
  84125. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  84126. }
  84127. }
  84128. if (bone._index !== -1) {
  84129. var mappedIndex = bone._index === null ? index : bone._index;
  84130. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  84131. }
  84132. }
  84133. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  84134. };
  84135. /**
  84136. * Build all resources required to render a skeleton
  84137. */
  84138. Skeleton.prototype.prepare = function () {
  84139. if (!this._isDirty) {
  84140. return;
  84141. }
  84142. if (this.needInitialSkinMatrix) {
  84143. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  84144. var mesh = this._meshesWithPoseMatrix[index];
  84145. var poseMatrix = mesh.getPoseMatrix();
  84146. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  84147. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  84148. }
  84149. if (this._synchronizedWithMesh !== mesh) {
  84150. this._synchronizedWithMesh = mesh;
  84151. // Prepare bones
  84152. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  84153. var bone = this.bones[boneIndex];
  84154. if (!bone.getParent()) {
  84155. var matrix = bone.getBaseMatrix();
  84156. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  84157. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  84158. }
  84159. }
  84160. }
  84161. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  84162. }
  84163. }
  84164. else {
  84165. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  84166. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  84167. }
  84168. this._computeTransformMatrices(this._transformMatrices, null);
  84169. }
  84170. this._isDirty = false;
  84171. this._scene._activeBones.addCount(this.bones.length, false);
  84172. };
  84173. /**
  84174. * Gets the list of animatables currently running for this skeleton
  84175. * @returns an array of animatables
  84176. */
  84177. Skeleton.prototype.getAnimatables = function () {
  84178. if (!this._animatables || this._animatables.length !== this.bones.length) {
  84179. this._animatables = [];
  84180. for (var index = 0; index < this.bones.length; index++) {
  84181. this._animatables.push(this.bones[index]);
  84182. }
  84183. }
  84184. return this._animatables;
  84185. };
  84186. /**
  84187. * Clone the current skeleton
  84188. * @param name defines the name of the new skeleton
  84189. * @param id defines the id of the enw skeleton
  84190. * @returns the new skeleton
  84191. */
  84192. Skeleton.prototype.clone = function (name, id) {
  84193. var result = new Skeleton(name, id || name, this._scene);
  84194. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  84195. for (var index = 0; index < this.bones.length; index++) {
  84196. var source = this.bones[index];
  84197. var parentBone = null;
  84198. var parent_1 = source.getParent();
  84199. if (parent_1) {
  84200. var parentIndex = this.bones.indexOf(parent_1);
  84201. parentBone = result.bones[parentIndex];
  84202. }
  84203. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  84204. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  84205. }
  84206. if (this._ranges) {
  84207. result._ranges = {};
  84208. for (var rangeName in this._ranges) {
  84209. var range = this._ranges[rangeName];
  84210. if (range) {
  84211. result._ranges[rangeName] = range.clone();
  84212. }
  84213. }
  84214. }
  84215. this._isDirty = true;
  84216. return result;
  84217. };
  84218. /**
  84219. * Enable animation blending for this skeleton
  84220. * @param blendingSpeed defines the blending speed to apply
  84221. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  84222. */
  84223. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  84224. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  84225. this.bones.forEach(function (bone) {
  84226. bone.animations.forEach(function (animation) {
  84227. animation.enableBlending = true;
  84228. animation.blendingSpeed = blendingSpeed;
  84229. });
  84230. });
  84231. };
  84232. /**
  84233. * Releases all resources associated with the current skeleton
  84234. */
  84235. Skeleton.prototype.dispose = function () {
  84236. this._meshesWithPoseMatrix = [];
  84237. // Animations
  84238. this.getScene().stopAnimation(this);
  84239. // Remove from scene
  84240. this.getScene().removeSkeleton(this);
  84241. };
  84242. /**
  84243. * Serialize the skeleton in a JSON object
  84244. * @returns a JSON object
  84245. */
  84246. Skeleton.prototype.serialize = function () {
  84247. var serializationObject = {};
  84248. serializationObject.name = this.name;
  84249. serializationObject.id = this.id;
  84250. if (this.dimensionsAtRest) {
  84251. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  84252. }
  84253. serializationObject.bones = [];
  84254. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  84255. for (var index = 0; index < this.bones.length; index++) {
  84256. var bone = this.bones[index];
  84257. var parent_2 = bone.getParent();
  84258. var serializedBone = {
  84259. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  84260. name: bone.name,
  84261. matrix: bone.getBaseMatrix().toArray(),
  84262. rest: bone.getRestPose().toArray()
  84263. };
  84264. serializationObject.bones.push(serializedBone);
  84265. if (bone.length) {
  84266. serializedBone.length = bone.length;
  84267. }
  84268. if (bone.metadata) {
  84269. serializedBone.metadata = bone.metadata;
  84270. }
  84271. if (bone.animations && bone.animations.length > 0) {
  84272. serializedBone.animation = bone.animations[0].serialize();
  84273. }
  84274. serializationObject.ranges = [];
  84275. for (var name in this._ranges) {
  84276. var source = this._ranges[name];
  84277. if (!source) {
  84278. continue;
  84279. }
  84280. var range = {};
  84281. range.name = name;
  84282. range.from = source.from;
  84283. range.to = source.to;
  84284. serializationObject.ranges.push(range);
  84285. }
  84286. }
  84287. return serializationObject;
  84288. };
  84289. /**
  84290. * Creates a new skeleton from serialized data
  84291. * @param parsedSkeleton defines the serialized data
  84292. * @param scene defines the hosting scene
  84293. * @returns a new skeleton
  84294. */
  84295. Skeleton.Parse = function (parsedSkeleton, scene) {
  84296. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  84297. if (parsedSkeleton.dimensionsAtRest) {
  84298. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  84299. }
  84300. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  84301. var index;
  84302. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  84303. var parsedBone = parsedSkeleton.bones[index];
  84304. var parentBone = null;
  84305. if (parsedBone.parentBoneIndex > -1) {
  84306. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  84307. }
  84308. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  84309. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  84310. if (parsedBone.length) {
  84311. bone.length = parsedBone.length;
  84312. }
  84313. if (parsedBone.metadata) {
  84314. bone.metadata = parsedBone.metadata;
  84315. }
  84316. if (parsedBone.animation) {
  84317. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  84318. }
  84319. }
  84320. // placed after bones, so createAnimationRange can cascade down
  84321. if (parsedSkeleton.ranges) {
  84322. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  84323. var data = parsedSkeleton.ranges[index];
  84324. skeleton.createAnimationRange(data.name, data.from, data.to);
  84325. }
  84326. }
  84327. return skeleton;
  84328. };
  84329. /**
  84330. * Compute all node absolute transforms
  84331. * @param forceUpdate defines if computation must be done even if cache is up to date
  84332. */
  84333. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  84334. if (forceUpdate === void 0) { forceUpdate = false; }
  84335. var renderId = this._scene.getRenderId();
  84336. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  84337. this.bones[0].computeAbsoluteTransforms();
  84338. this._lastAbsoluteTransformsUpdateId = renderId;
  84339. }
  84340. };
  84341. /**
  84342. * Gets the root pose matrix
  84343. * @returns a matrix
  84344. */
  84345. Skeleton.prototype.getPoseMatrix = function () {
  84346. var poseMatrix = null;
  84347. if (this._meshesWithPoseMatrix.length > 0) {
  84348. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  84349. }
  84350. return poseMatrix;
  84351. };
  84352. /**
  84353. * Sorts bones per internal index
  84354. */
  84355. Skeleton.prototype.sortBones = function () {
  84356. var bones = new Array();
  84357. var visited = new Array(this.bones.length);
  84358. for (var index = 0; index < this.bones.length; index++) {
  84359. this._sortBones(index, bones, visited);
  84360. }
  84361. this.bones = bones;
  84362. };
  84363. Skeleton.prototype._sortBones = function (index, bones, visited) {
  84364. if (visited[index]) {
  84365. return;
  84366. }
  84367. visited[index] = true;
  84368. var bone = this.bones[index];
  84369. if (bone._index === undefined) {
  84370. bone._index = index;
  84371. }
  84372. var parentBone = bone.getParent();
  84373. if (parentBone) {
  84374. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  84375. }
  84376. bones.push(bone);
  84377. };
  84378. return Skeleton;
  84379. }());
  84380. BABYLON.Skeleton = Skeleton;
  84381. })(BABYLON || (BABYLON = {}));
  84382. //# sourceMappingURL=babylon.skeleton.js.map
  84383. var BABYLON;
  84384. (function (BABYLON) {
  84385. ;
  84386. /**
  84387. * This groups tools to convert HDR texture to native colors array.
  84388. */
  84389. var HDRTools = /** @class */ (function () {
  84390. function HDRTools() {
  84391. }
  84392. HDRTools.Ldexp = function (mantissa, exponent) {
  84393. if (exponent > 1023) {
  84394. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  84395. }
  84396. if (exponent < -1074) {
  84397. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  84398. }
  84399. return mantissa * Math.pow(2, exponent);
  84400. };
  84401. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  84402. if (exponent > 0) { /*nonzero pixel*/
  84403. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  84404. float32array[index + 0] = red * exponent;
  84405. float32array[index + 1] = green * exponent;
  84406. float32array[index + 2] = blue * exponent;
  84407. }
  84408. else {
  84409. float32array[index + 0] = 0;
  84410. float32array[index + 1] = 0;
  84411. float32array[index + 2] = 0;
  84412. }
  84413. };
  84414. HDRTools.readStringLine = function (uint8array, startIndex) {
  84415. var line = "";
  84416. var character = "";
  84417. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  84418. character = String.fromCharCode(uint8array[i]);
  84419. if (character == "\n") {
  84420. break;
  84421. }
  84422. line += character;
  84423. }
  84424. return line;
  84425. };
  84426. /**
  84427. * Reads header information from an RGBE texture stored in a native array.
  84428. * More information on this format are available here:
  84429. * https://en.wikipedia.org/wiki/RGBE_image_format
  84430. *
  84431. * @param uint8array The binary file stored in native array.
  84432. * @return The header information.
  84433. */
  84434. HDRTools.RGBE_ReadHeader = function (uint8array) {
  84435. var height = 0;
  84436. var width = 0;
  84437. var line = this.readStringLine(uint8array, 0);
  84438. if (line[0] != '#' || line[1] != '?') {
  84439. throw "Bad HDR Format.";
  84440. }
  84441. var endOfHeader = false;
  84442. var findFormat = false;
  84443. var lineIndex = 0;
  84444. do {
  84445. lineIndex += (line.length + 1);
  84446. line = this.readStringLine(uint8array, lineIndex);
  84447. if (line == "FORMAT=32-bit_rle_rgbe") {
  84448. findFormat = true;
  84449. }
  84450. else if (line.length == 0) {
  84451. endOfHeader = true;
  84452. }
  84453. } while (!endOfHeader);
  84454. if (!findFormat) {
  84455. throw "HDR Bad header format, unsupported FORMAT";
  84456. }
  84457. lineIndex += (line.length + 1);
  84458. line = this.readStringLine(uint8array, lineIndex);
  84459. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  84460. var match = sizeRegexp.exec(line);
  84461. // TODO. Support +Y and -X if needed.
  84462. if (!match || match.length < 3) {
  84463. throw "HDR Bad header format, no size";
  84464. }
  84465. width = parseInt(match[2]);
  84466. height = parseInt(match[1]);
  84467. if (width < 8 || width > 0x7fff) {
  84468. throw "HDR Bad header format, unsupported size";
  84469. }
  84470. lineIndex += (line.length + 1);
  84471. return {
  84472. height: height,
  84473. width: width,
  84474. dataPosition: lineIndex
  84475. };
  84476. };
  84477. /**
  84478. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  84479. * This RGBE texture needs to store the information as a panorama.
  84480. *
  84481. * More information on this format are available here:
  84482. * https://en.wikipedia.org/wiki/RGBE_image_format
  84483. *
  84484. * @param buffer The binary file stored in an array buffer.
  84485. * @param size The expected size of the extracted cubemap.
  84486. * @return The Cube Map information.
  84487. */
  84488. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  84489. var uint8array = new Uint8Array(buffer);
  84490. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  84491. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  84492. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  84493. return cubeMapData;
  84494. };
  84495. /**
  84496. * Returns the pixels data extracted from an RGBE texture.
  84497. * This pixels will be stored left to right up to down in the R G B order in one array.
  84498. *
  84499. * More information on this format are available here:
  84500. * https://en.wikipedia.org/wiki/RGBE_image_format
  84501. *
  84502. * @param uint8array The binary file stored in an array buffer.
  84503. * @param hdrInfo The header information of the file.
  84504. * @return The pixels data in RGB right to left up to down order.
  84505. */
  84506. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  84507. // Keep for multi format supports.
  84508. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  84509. };
  84510. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  84511. var num_scanlines = hdrInfo.height;
  84512. var scanline_width = hdrInfo.width;
  84513. var a, b, c, d, count;
  84514. var dataIndex = hdrInfo.dataPosition;
  84515. var index = 0, endIndex = 0, i = 0;
  84516. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  84517. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  84518. // 3 channels of 4 bytes per pixel in float.
  84519. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  84520. var resultArray = new Float32Array(resultBuffer);
  84521. // read in each successive scanline
  84522. while (num_scanlines > 0) {
  84523. a = uint8array[dataIndex++];
  84524. b = uint8array[dataIndex++];
  84525. c = uint8array[dataIndex++];
  84526. d = uint8array[dataIndex++];
  84527. if (a != 2 || b != 2 || (c & 0x80)) {
  84528. // this file is not run length encoded
  84529. throw "HDR Bad header format, not RLE";
  84530. }
  84531. if (((c << 8) | d) != scanline_width) {
  84532. throw "HDR Bad header format, wrong scan line width";
  84533. }
  84534. index = 0;
  84535. // read each of the four channels for the scanline into the buffer
  84536. for (i = 0; i < 4; i++) {
  84537. endIndex = (i + 1) * scanline_width;
  84538. while (index < endIndex) {
  84539. a = uint8array[dataIndex++];
  84540. b = uint8array[dataIndex++];
  84541. if (a > 128) {
  84542. // a run of the same value
  84543. count = a - 128;
  84544. if ((count == 0) || (count > endIndex - index)) {
  84545. throw "HDR Bad Format, bad scanline data (run)";
  84546. }
  84547. while (count-- > 0) {
  84548. scanLineArray[index++] = b;
  84549. }
  84550. }
  84551. else {
  84552. // a non-run
  84553. count = a;
  84554. if ((count == 0) || (count > endIndex - index)) {
  84555. throw "HDR Bad Format, bad scanline data (non-run)";
  84556. }
  84557. scanLineArray[index++] = b;
  84558. if (--count > 0) {
  84559. for (var j = 0; j < count; j++) {
  84560. scanLineArray[index++] = uint8array[dataIndex++];
  84561. }
  84562. }
  84563. }
  84564. }
  84565. }
  84566. // now convert data from buffer into floats
  84567. for (i = 0; i < scanline_width; i++) {
  84568. a = scanLineArray[i];
  84569. b = scanLineArray[i + scanline_width];
  84570. c = scanLineArray[i + 2 * scanline_width];
  84571. d = scanLineArray[i + 3 * scanline_width];
  84572. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  84573. }
  84574. num_scanlines--;
  84575. }
  84576. return resultArray;
  84577. };
  84578. return HDRTools;
  84579. }());
  84580. BABYLON.HDRTools = HDRTools;
  84581. })(BABYLON || (BABYLON = {}));
  84582. //# sourceMappingURL=babylon.hdr.js.map
  84583. var BABYLON;
  84584. (function (BABYLON) {
  84585. /**
  84586. * This represents a texture coming from an HDR input.
  84587. *
  84588. * The only supported format is currently panorama picture stored in RGBE format.
  84589. * Example of such files can be found on HDRLib: http://hdrlib.com/
  84590. */
  84591. var HDRCubeTexture = /** @class */ (function (_super) {
  84592. __extends(HDRCubeTexture, _super);
  84593. /**
  84594. * Instantiates an HDRTexture from the following parameters.
  84595. *
  84596. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  84597. * @param scene The scene the texture will be used in
  84598. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  84599. * @param noMipmap Forces to not generate the mipmap if true
  84600. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  84601. * @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)
  84602. * @param reserved Reserved flag for internal use.
  84603. */
  84604. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  84605. if (noMipmap === void 0) { noMipmap = false; }
  84606. if (generateHarmonics === void 0) { generateHarmonics = true; }
  84607. if (gammaSpace === void 0) { gammaSpace = false; }
  84608. if (reserved === void 0) { reserved = false; }
  84609. if (onLoad === void 0) { onLoad = null; }
  84610. if (onError === void 0) { onError = null; }
  84611. var _this = _super.call(this, scene) || this;
  84612. _this._generateHarmonics = true;
  84613. _this._onLoad = null;
  84614. _this._onError = null;
  84615. /**
  84616. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  84617. */
  84618. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  84619. _this._isBlocking = true;
  84620. _this._rotationY = 0;
  84621. /**
  84622. * Gets or sets the center of the bounding box associated with the cube texture
  84623. * It must define where the camera used to render the texture was set
  84624. */
  84625. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  84626. if (!url) {
  84627. return _this;
  84628. }
  84629. _this.name = url;
  84630. _this.url = url;
  84631. _this.hasAlpha = false;
  84632. _this.isCube = true;
  84633. _this._textureMatrix = BABYLON.Matrix.Identity();
  84634. _this._onLoad = onLoad;
  84635. _this._onError = onError;
  84636. _this.gammaSpace = gammaSpace;
  84637. _this._noMipmap = noMipmap;
  84638. _this._size = size;
  84639. _this._texture = _this._getFromCache(url, _this._noMipmap);
  84640. if (!_this._texture) {
  84641. if (!scene.useDelayedTextureLoading) {
  84642. _this.loadTexture();
  84643. }
  84644. else {
  84645. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  84646. }
  84647. }
  84648. return _this;
  84649. }
  84650. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  84651. /**
  84652. * Gets wether or not the texture is blocking during loading.
  84653. */
  84654. get: function () {
  84655. return this._isBlocking;
  84656. },
  84657. /**
  84658. * Sets wether or not the texture is blocking during loading.
  84659. */
  84660. set: function (value) {
  84661. this._isBlocking = value;
  84662. },
  84663. enumerable: true,
  84664. configurable: true
  84665. });
  84666. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  84667. /**
  84668. * Gets texture matrix rotation angle around Y axis radians.
  84669. */
  84670. get: function () {
  84671. return this._rotationY;
  84672. },
  84673. /**
  84674. * Sets texture matrix rotation angle around Y axis in radians.
  84675. */
  84676. set: function (value) {
  84677. this._rotationY = value;
  84678. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  84679. },
  84680. enumerable: true,
  84681. configurable: true
  84682. });
  84683. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  84684. get: function () {
  84685. return this._boundingBoxSize;
  84686. },
  84687. /**
  84688. * Gets or sets the size of the bounding box associated with the cube texture
  84689. * When defined, the cubemap will switch to local mode
  84690. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  84691. * @example https://www.babylonjs-playground.com/#RNASML
  84692. */
  84693. set: function (value) {
  84694. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  84695. return;
  84696. }
  84697. this._boundingBoxSize = value;
  84698. var scene = this.getScene();
  84699. if (scene) {
  84700. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  84701. }
  84702. },
  84703. enumerable: true,
  84704. configurable: true
  84705. });
  84706. /**
  84707. * Occurs when the file is raw .hdr file.
  84708. */
  84709. HDRCubeTexture.prototype.loadTexture = function () {
  84710. var _this = this;
  84711. var callback = function (buffer) {
  84712. _this.lodGenerationOffset = 0.0;
  84713. _this.lodGenerationScale = 0.8;
  84714. var scene = _this.getScene();
  84715. if (!scene) {
  84716. return null;
  84717. }
  84718. // Extract the raw linear data.
  84719. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  84720. // Generate harmonics if needed.
  84721. if (_this._generateHarmonics) {
  84722. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  84723. _this.sphericalPolynomial = sphericalPolynomial;
  84724. }
  84725. var results = [];
  84726. var byteArray = null;
  84727. // Push each faces.
  84728. for (var j = 0; j < 6; j++) {
  84729. // Create uintarray fallback.
  84730. if (!scene.getEngine().getCaps().textureFloat) {
  84731. // 3 channels of 1 bytes per pixel in bytes.
  84732. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  84733. byteArray = new Uint8Array(byteBuffer);
  84734. }
  84735. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  84736. // If special cases.
  84737. if (_this.gammaSpace || byteArray) {
  84738. for (var i = 0; i < _this._size * _this._size; i++) {
  84739. // Put in gamma space if requested.
  84740. if (_this.gammaSpace) {
  84741. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  84742. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  84743. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  84744. }
  84745. // Convert to int texture for fallback.
  84746. if (byteArray) {
  84747. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  84748. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  84749. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  84750. // May use luminance instead if the result is not accurate.
  84751. var max = Math.max(Math.max(r, g), b);
  84752. if (max > 255) {
  84753. var scale = 255 / max;
  84754. r *= scale;
  84755. g *= scale;
  84756. b *= scale;
  84757. }
  84758. byteArray[(i * 3) + 0] = r;
  84759. byteArray[(i * 3) + 1] = g;
  84760. byteArray[(i * 3) + 2] = b;
  84761. }
  84762. }
  84763. }
  84764. if (byteArray) {
  84765. results.push(byteArray);
  84766. }
  84767. else {
  84768. results.push(dataFace);
  84769. }
  84770. }
  84771. return results;
  84772. };
  84773. var scene = this.getScene();
  84774. if (scene) {
  84775. 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);
  84776. }
  84777. };
  84778. HDRCubeTexture.prototype.clone = function () {
  84779. var scene = this.getScene();
  84780. if (!scene) {
  84781. return this;
  84782. }
  84783. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  84784. // Base texture
  84785. newTexture.level = this.level;
  84786. newTexture.wrapU = this.wrapU;
  84787. newTexture.wrapV = this.wrapV;
  84788. newTexture.coordinatesIndex = this.coordinatesIndex;
  84789. newTexture.coordinatesMode = this.coordinatesMode;
  84790. return newTexture;
  84791. };
  84792. // Methods
  84793. HDRCubeTexture.prototype.delayLoad = function () {
  84794. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  84795. return;
  84796. }
  84797. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  84798. this._texture = this._getFromCache(this.url, this._noMipmap);
  84799. if (!this._texture) {
  84800. this.loadTexture();
  84801. }
  84802. };
  84803. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  84804. return this._textureMatrix;
  84805. };
  84806. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  84807. this._textureMatrix = value;
  84808. };
  84809. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  84810. var texture = null;
  84811. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  84812. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  84813. texture.name = parsedTexture.name;
  84814. texture.hasAlpha = parsedTexture.hasAlpha;
  84815. texture.level = parsedTexture.level;
  84816. texture.coordinatesMode = parsedTexture.coordinatesMode;
  84817. texture.isBlocking = parsedTexture.isBlocking;
  84818. }
  84819. if (texture) {
  84820. if (parsedTexture.boundingBoxPosition) {
  84821. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  84822. }
  84823. if (parsedTexture.boundingBoxSize) {
  84824. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  84825. }
  84826. if (parsedTexture.rotationY) {
  84827. texture.rotationY = parsedTexture.rotationY;
  84828. }
  84829. }
  84830. return texture;
  84831. };
  84832. HDRCubeTexture.prototype.serialize = function () {
  84833. if (!this.name) {
  84834. return null;
  84835. }
  84836. var serializationObject = {};
  84837. serializationObject.name = this.name;
  84838. serializationObject.hasAlpha = this.hasAlpha;
  84839. serializationObject.isCube = true;
  84840. serializationObject.level = this.level;
  84841. serializationObject.size = this._size;
  84842. serializationObject.coordinatesMode = this.coordinatesMode;
  84843. serializationObject.useInGammaSpace = this.gammaSpace;
  84844. serializationObject.generateHarmonics = this._generateHarmonics;
  84845. serializationObject.customType = "BABYLON.HDRCubeTexture";
  84846. serializationObject.noMipmap = this._noMipmap;
  84847. serializationObject.isBlocking = this._isBlocking;
  84848. serializationObject.rotationY = this._rotationY;
  84849. return serializationObject;
  84850. };
  84851. HDRCubeTexture._facesMapping = [
  84852. "right",
  84853. "left",
  84854. "up",
  84855. "down",
  84856. "front",
  84857. "back"
  84858. ];
  84859. return HDRCubeTexture;
  84860. }(BABYLON.BaseTexture));
  84861. BABYLON.HDRCubeTexture = HDRCubeTexture;
  84862. })(BABYLON || (BABYLON = {}));
  84863. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  84864. var BABYLON;
  84865. (function (BABYLON) {
  84866. /**
  84867. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  84868. */
  84869. var PanoramaToCubeMapTools = /** @class */ (function () {
  84870. function PanoramaToCubeMapTools() {
  84871. }
  84872. /**
  84873. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  84874. *
  84875. * @param float32Array The source data.
  84876. * @param inputWidth The width of the input panorama.
  84877. * @param inputhHeight The height of the input panorama.
  84878. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  84879. * @return The cubemap data
  84880. */
  84881. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  84882. if (!float32Array) {
  84883. throw "ConvertPanoramaToCubemap: input cannot be null";
  84884. }
  84885. if (float32Array.length != inputWidth * inputHeight * 3) {
  84886. throw "ConvertPanoramaToCubemap: input size is wrong";
  84887. }
  84888. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  84889. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  84890. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  84891. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  84892. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  84893. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  84894. return {
  84895. front: textureFront,
  84896. back: textureBack,
  84897. left: textureLeft,
  84898. right: textureRight,
  84899. up: textureUp,
  84900. down: textureDown,
  84901. size: size,
  84902. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  84903. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  84904. gammaSpace: false,
  84905. };
  84906. };
  84907. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  84908. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  84909. var textureArray = new Float32Array(buffer);
  84910. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  84911. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  84912. var dy = 1 / texSize;
  84913. var fy = 0;
  84914. for (var y = 0; y < texSize; y++) {
  84915. var xv1 = faceData[0];
  84916. var xv2 = faceData[2];
  84917. for (var x = 0; x < texSize; x++) {
  84918. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  84919. v.normalize();
  84920. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  84921. // 3 channels per pixels
  84922. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  84923. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  84924. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  84925. xv1 = xv1.add(rotDX1);
  84926. xv2 = xv2.add(rotDX2);
  84927. }
  84928. fy += dy;
  84929. }
  84930. return textureArray;
  84931. };
  84932. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  84933. var theta = Math.atan2(vDir.z, vDir.x);
  84934. var phi = Math.acos(vDir.y);
  84935. while (theta < -Math.PI)
  84936. theta += 2 * Math.PI;
  84937. while (theta > Math.PI)
  84938. theta -= 2 * Math.PI;
  84939. var dx = theta / Math.PI;
  84940. var dy = phi / Math.PI;
  84941. // recenter.
  84942. dx = dx * 0.5 + 0.5;
  84943. var px = Math.round(dx * inputWidth);
  84944. if (px < 0)
  84945. px = 0;
  84946. else if (px >= inputWidth)
  84947. px = inputWidth - 1;
  84948. var py = Math.round(dy * inputHeight);
  84949. if (py < 0)
  84950. py = 0;
  84951. else if (py >= inputHeight)
  84952. py = inputHeight - 1;
  84953. var inputY = (inputHeight - py - 1);
  84954. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  84955. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  84956. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  84957. return {
  84958. r: r,
  84959. g: g,
  84960. b: b
  84961. };
  84962. };
  84963. PanoramaToCubeMapTools.FACE_FRONT = [
  84964. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  84965. new BABYLON.Vector3(1.0, -1.0, -1.0),
  84966. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  84967. new BABYLON.Vector3(1.0, 1.0, -1.0)
  84968. ];
  84969. PanoramaToCubeMapTools.FACE_BACK = [
  84970. new BABYLON.Vector3(1.0, -1.0, 1.0),
  84971. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  84972. new BABYLON.Vector3(1.0, 1.0, 1.0),
  84973. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  84974. ];
  84975. PanoramaToCubeMapTools.FACE_RIGHT = [
  84976. new BABYLON.Vector3(1.0, -1.0, -1.0),
  84977. new BABYLON.Vector3(1.0, -1.0, 1.0),
  84978. new BABYLON.Vector3(1.0, 1.0, -1.0),
  84979. new BABYLON.Vector3(1.0, 1.0, 1.0)
  84980. ];
  84981. PanoramaToCubeMapTools.FACE_LEFT = [
  84982. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  84983. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  84984. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  84985. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  84986. ];
  84987. PanoramaToCubeMapTools.FACE_DOWN = [
  84988. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  84989. new BABYLON.Vector3(1.0, 1.0, -1.0),
  84990. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  84991. new BABYLON.Vector3(1.0, 1.0, 1.0)
  84992. ];
  84993. PanoramaToCubeMapTools.FACE_UP = [
  84994. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  84995. new BABYLON.Vector3(1.0, -1.0, 1.0),
  84996. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  84997. new BABYLON.Vector3(1.0, -1.0, -1.0)
  84998. ];
  84999. return PanoramaToCubeMapTools;
  85000. }());
  85001. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  85002. })(BABYLON || (BABYLON = {}));
  85003. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  85004. var BABYLON;
  85005. (function (BABYLON) {
  85006. var IndexedVector2 = /** @class */ (function (_super) {
  85007. __extends(IndexedVector2, _super);
  85008. function IndexedVector2(original, index) {
  85009. var _this = _super.call(this, original.x, original.y) || this;
  85010. _this.index = index;
  85011. return _this;
  85012. }
  85013. return IndexedVector2;
  85014. }(BABYLON.Vector2));
  85015. var PolygonPoints = /** @class */ (function () {
  85016. function PolygonPoints() {
  85017. this.elements = new Array();
  85018. }
  85019. PolygonPoints.prototype.add = function (originalPoints) {
  85020. var _this = this;
  85021. var result = new Array();
  85022. originalPoints.forEach(function (point) {
  85023. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  85024. var newPoint = new IndexedVector2(point, _this.elements.length);
  85025. result.push(newPoint);
  85026. _this.elements.push(newPoint);
  85027. }
  85028. });
  85029. return result;
  85030. };
  85031. PolygonPoints.prototype.computeBounds = function () {
  85032. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  85033. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  85034. this.elements.forEach(function (point) {
  85035. // x
  85036. if (point.x < lmin.x) {
  85037. lmin.x = point.x;
  85038. }
  85039. else if (point.x > lmax.x) {
  85040. lmax.x = point.x;
  85041. }
  85042. // y
  85043. if (point.y < lmin.y) {
  85044. lmin.y = point.y;
  85045. }
  85046. else if (point.y > lmax.y) {
  85047. lmax.y = point.y;
  85048. }
  85049. });
  85050. return {
  85051. min: lmin,
  85052. max: lmax,
  85053. width: lmax.x - lmin.x,
  85054. height: lmax.y - lmin.y
  85055. };
  85056. };
  85057. return PolygonPoints;
  85058. }());
  85059. var Polygon = /** @class */ (function () {
  85060. function Polygon() {
  85061. }
  85062. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  85063. return [
  85064. new BABYLON.Vector2(xmin, ymin),
  85065. new BABYLON.Vector2(xmax, ymin),
  85066. new BABYLON.Vector2(xmax, ymax),
  85067. new BABYLON.Vector2(xmin, ymax)
  85068. ];
  85069. };
  85070. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  85071. if (cx === void 0) { cx = 0; }
  85072. if (cy === void 0) { cy = 0; }
  85073. if (numberOfSides === void 0) { numberOfSides = 32; }
  85074. var result = new Array();
  85075. var angle = 0;
  85076. var increment = (Math.PI * 2) / numberOfSides;
  85077. for (var i = 0; i < numberOfSides; i++) {
  85078. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  85079. angle -= increment;
  85080. }
  85081. return result;
  85082. };
  85083. Polygon.Parse = function (input) {
  85084. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  85085. var i, result = [];
  85086. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  85087. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  85088. }
  85089. return result;
  85090. };
  85091. Polygon.StartingAt = function (x, y) {
  85092. return BABYLON.Path2.StartingAt(x, y);
  85093. };
  85094. return Polygon;
  85095. }());
  85096. BABYLON.Polygon = Polygon;
  85097. var PolygonMeshBuilder = /** @class */ (function () {
  85098. function PolygonMeshBuilder(name, contours, scene) {
  85099. this._points = new PolygonPoints();
  85100. this._outlinepoints = new PolygonPoints();
  85101. this._holes = new Array();
  85102. this._epoints = new Array();
  85103. this._eholes = new Array();
  85104. this._name = name;
  85105. this._scene = scene;
  85106. var points;
  85107. if (contours instanceof BABYLON.Path2) {
  85108. points = contours.getPoints();
  85109. }
  85110. else {
  85111. points = contours;
  85112. }
  85113. this._addToepoint(points);
  85114. this._points.add(points);
  85115. this._outlinepoints.add(points);
  85116. if (typeof earcut === 'undefined') {
  85117. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  85118. }
  85119. }
  85120. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  85121. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  85122. var p = points_1[_i];
  85123. this._epoints.push(p.x, p.y);
  85124. }
  85125. };
  85126. PolygonMeshBuilder.prototype.addHole = function (hole) {
  85127. this._points.add(hole);
  85128. var holepoints = new PolygonPoints();
  85129. holepoints.add(hole);
  85130. this._holes.push(holepoints);
  85131. this._eholes.push(this._epoints.length / 2);
  85132. this._addToepoint(hole);
  85133. return this;
  85134. };
  85135. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  85136. var _this = this;
  85137. if (updatable === void 0) { updatable = false; }
  85138. if (depth === void 0) { depth = 0; }
  85139. var result = new BABYLON.Mesh(this._name, this._scene);
  85140. var normals = new Array();
  85141. var positions = new Array();
  85142. var uvs = new Array();
  85143. var bounds = this._points.computeBounds();
  85144. this._points.elements.forEach(function (p) {
  85145. normals.push(0, 1.0, 0);
  85146. positions.push(p.x, 0, p.y);
  85147. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  85148. });
  85149. var indices = new Array();
  85150. var res = earcut(this._epoints, this._eholes, 2);
  85151. for (var i = 0; i < res.length; i++) {
  85152. indices.push(res[i]);
  85153. }
  85154. if (depth > 0) {
  85155. var positionscount = (positions.length / 3); //get the current pointcount
  85156. this._points.elements.forEach(function (p) {
  85157. normals.push(0, -1.0, 0);
  85158. positions.push(p.x, -depth, p.y);
  85159. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  85160. });
  85161. var totalCount = indices.length;
  85162. for (var i = 0; i < totalCount; i += 3) {
  85163. var i0 = indices[i + 0];
  85164. var i1 = indices[i + 1];
  85165. var i2 = indices[i + 2];
  85166. indices.push(i2 + positionscount);
  85167. indices.push(i1 + positionscount);
  85168. indices.push(i0 + positionscount);
  85169. }
  85170. //Add the sides
  85171. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  85172. this._holes.forEach(function (hole) {
  85173. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  85174. });
  85175. }
  85176. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  85177. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  85178. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  85179. result.setIndices(indices);
  85180. return result;
  85181. };
  85182. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  85183. var StartIndex = positions.length / 3;
  85184. var ulength = 0;
  85185. for (var i = 0; i < points.elements.length; i++) {
  85186. var p = points.elements[i];
  85187. var p1;
  85188. if ((i + 1) > points.elements.length - 1) {
  85189. p1 = points.elements[0];
  85190. }
  85191. else {
  85192. p1 = points.elements[i + 1];
  85193. }
  85194. positions.push(p.x, 0, p.y);
  85195. positions.push(p.x, -depth, p.y);
  85196. positions.push(p1.x, 0, p1.y);
  85197. positions.push(p1.x, -depth, p1.y);
  85198. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  85199. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  85200. var v3 = v2.subtract(v1);
  85201. var v4 = new BABYLON.Vector3(0, 1, 0);
  85202. var vn = BABYLON.Vector3.Cross(v3, v4);
  85203. vn = vn.normalize();
  85204. uvs.push(ulength / bounds.width, 0);
  85205. uvs.push(ulength / bounds.width, 1);
  85206. ulength += v3.length();
  85207. uvs.push((ulength / bounds.width), 0);
  85208. uvs.push((ulength / bounds.width), 1);
  85209. if (!flip) {
  85210. normals.push(-vn.x, -vn.y, -vn.z);
  85211. normals.push(-vn.x, -vn.y, -vn.z);
  85212. normals.push(-vn.x, -vn.y, -vn.z);
  85213. normals.push(-vn.x, -vn.y, -vn.z);
  85214. indices.push(StartIndex);
  85215. indices.push(StartIndex + 1);
  85216. indices.push(StartIndex + 2);
  85217. indices.push(StartIndex + 1);
  85218. indices.push(StartIndex + 3);
  85219. indices.push(StartIndex + 2);
  85220. }
  85221. else {
  85222. normals.push(vn.x, vn.y, vn.z);
  85223. normals.push(vn.x, vn.y, vn.z);
  85224. normals.push(vn.x, vn.y, vn.z);
  85225. normals.push(vn.x, vn.y, vn.z);
  85226. indices.push(StartIndex);
  85227. indices.push(StartIndex + 2);
  85228. indices.push(StartIndex + 1);
  85229. indices.push(StartIndex + 1);
  85230. indices.push(StartIndex + 2);
  85231. indices.push(StartIndex + 3);
  85232. }
  85233. StartIndex += 4;
  85234. }
  85235. ;
  85236. };
  85237. return PolygonMeshBuilder;
  85238. }());
  85239. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  85240. })(BABYLON || (BABYLON = {}));
  85241. //# sourceMappingURL=babylon.polygonMesh.js.map
  85242. var BABYLON;
  85243. (function (BABYLON) {
  85244. // Unique ID when we import meshes from Babylon to CSG
  85245. var currentCSGMeshId = 0;
  85246. // # class Vertex
  85247. // Represents a vertex of a polygon. Use your own vertex class instead of this
  85248. // one to provide additional features like texture coordinates and vertex
  85249. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  85250. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  85251. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  85252. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  85253. // is not used anywhere else.
  85254. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  85255. var Vertex = /** @class */ (function () {
  85256. function Vertex(pos, normal, uv) {
  85257. this.pos = pos;
  85258. this.normal = normal;
  85259. this.uv = uv;
  85260. }
  85261. Vertex.prototype.clone = function () {
  85262. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  85263. };
  85264. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  85265. // orientation of a polygon is flipped.
  85266. Vertex.prototype.flip = function () {
  85267. this.normal = this.normal.scale(-1);
  85268. };
  85269. // Create a new vertex between this vertex and `other` by linearly
  85270. // interpolating all properties using a parameter of `t`. Subclasses should
  85271. // override this to interpolate additional properties.
  85272. Vertex.prototype.interpolate = function (other, t) {
  85273. 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));
  85274. };
  85275. return Vertex;
  85276. }());
  85277. // # class Plane
  85278. // Represents a plane in 3D space.
  85279. var Plane = /** @class */ (function () {
  85280. function Plane(normal, w) {
  85281. this.normal = normal;
  85282. this.w = w;
  85283. }
  85284. Plane.FromPoints = function (a, b, c) {
  85285. var v0 = c.subtract(a);
  85286. var v1 = b.subtract(a);
  85287. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  85288. return null;
  85289. }
  85290. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  85291. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  85292. };
  85293. Plane.prototype.clone = function () {
  85294. return new Plane(this.normal.clone(), this.w);
  85295. };
  85296. Plane.prototype.flip = function () {
  85297. this.normal.scaleInPlace(-1);
  85298. this.w = -this.w;
  85299. };
  85300. // Split `polygon` by this plane if needed, then put the polygon or polygon
  85301. // fragments in the appropriate lists. Coplanar polygons go into either
  85302. // `coplanarFront` or `coplanarBack` depending on their orientation with
  85303. // respect to this plane. Polygons in front or in back of this plane go into
  85304. // either `front` or `back`.
  85305. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  85306. var COPLANAR = 0;
  85307. var FRONT = 1;
  85308. var BACK = 2;
  85309. var SPANNING = 3;
  85310. // Classify each point as well as the entire polygon into one of the above
  85311. // four classes.
  85312. var polygonType = 0;
  85313. var types = [];
  85314. var i;
  85315. var t;
  85316. for (i = 0; i < polygon.vertices.length; i++) {
  85317. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  85318. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  85319. polygonType |= type;
  85320. types.push(type);
  85321. }
  85322. // Put the polygon in the correct list, splitting it when necessary.
  85323. switch (polygonType) {
  85324. case COPLANAR:
  85325. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  85326. break;
  85327. case FRONT:
  85328. front.push(polygon);
  85329. break;
  85330. case BACK:
  85331. back.push(polygon);
  85332. break;
  85333. case SPANNING:
  85334. var f = [], b = [];
  85335. for (i = 0; i < polygon.vertices.length; i++) {
  85336. var j = (i + 1) % polygon.vertices.length;
  85337. var ti = types[i], tj = types[j];
  85338. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  85339. if (ti !== BACK)
  85340. f.push(vi);
  85341. if (ti !== FRONT)
  85342. b.push(ti !== BACK ? vi.clone() : vi);
  85343. if ((ti | tj) === SPANNING) {
  85344. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  85345. var v = vi.interpolate(vj, t);
  85346. f.push(v);
  85347. b.push(v.clone());
  85348. }
  85349. }
  85350. var poly;
  85351. if (f.length >= 3) {
  85352. poly = new Polygon(f, polygon.shared);
  85353. if (poly.plane)
  85354. front.push(poly);
  85355. }
  85356. if (b.length >= 3) {
  85357. poly = new Polygon(b, polygon.shared);
  85358. if (poly.plane)
  85359. back.push(poly);
  85360. }
  85361. break;
  85362. }
  85363. };
  85364. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  85365. // point is on the plane.
  85366. Plane.EPSILON = 1e-5;
  85367. return Plane;
  85368. }());
  85369. // # class Polygon
  85370. // Represents a convex polygon. The vertices used to initialize a polygon must
  85371. // be coplanar and form a convex loop.
  85372. //
  85373. // Each convex polygon has a `shared` property, which is shared between all
  85374. // polygons that are clones of each other or were split from the same polygon.
  85375. // This can be used to define per-polygon properties (such as surface color).
  85376. var Polygon = /** @class */ (function () {
  85377. function Polygon(vertices, shared) {
  85378. this.vertices = vertices;
  85379. this.shared = shared;
  85380. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  85381. }
  85382. Polygon.prototype.clone = function () {
  85383. var vertices = this.vertices.map(function (v) { return v.clone(); });
  85384. return new Polygon(vertices, this.shared);
  85385. };
  85386. Polygon.prototype.flip = function () {
  85387. this.vertices.reverse().map(function (v) { v.flip(); });
  85388. this.plane.flip();
  85389. };
  85390. return Polygon;
  85391. }());
  85392. // # class Node
  85393. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  85394. // by picking a polygon to split along. That polygon (and all other coplanar
  85395. // polygons) are added directly to that node and the other polygons are added to
  85396. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  85397. // no distinction between internal and leaf nodes.
  85398. var Node = /** @class */ (function () {
  85399. function Node(polygons) {
  85400. this.plane = null;
  85401. this.front = null;
  85402. this.back = null;
  85403. this.polygons = new Array();
  85404. if (polygons) {
  85405. this.build(polygons);
  85406. }
  85407. }
  85408. Node.prototype.clone = function () {
  85409. var node = new Node();
  85410. node.plane = this.plane && this.plane.clone();
  85411. node.front = this.front && this.front.clone();
  85412. node.back = this.back && this.back.clone();
  85413. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  85414. return node;
  85415. };
  85416. // Convert solid space to empty space and empty space to solid space.
  85417. Node.prototype.invert = function () {
  85418. for (var i = 0; i < this.polygons.length; i++) {
  85419. this.polygons[i].flip();
  85420. }
  85421. if (this.plane) {
  85422. this.plane.flip();
  85423. }
  85424. if (this.front) {
  85425. this.front.invert();
  85426. }
  85427. if (this.back) {
  85428. this.back.invert();
  85429. }
  85430. var temp = this.front;
  85431. this.front = this.back;
  85432. this.back = temp;
  85433. };
  85434. // Recursively remove all polygons in `polygons` that are inside this BSP
  85435. // tree.
  85436. Node.prototype.clipPolygons = function (polygons) {
  85437. if (!this.plane)
  85438. return polygons.slice();
  85439. var front = new Array(), back = new Array();
  85440. for (var i = 0; i < polygons.length; i++) {
  85441. this.plane.splitPolygon(polygons[i], front, back, front, back);
  85442. }
  85443. if (this.front) {
  85444. front = this.front.clipPolygons(front);
  85445. }
  85446. if (this.back) {
  85447. back = this.back.clipPolygons(back);
  85448. }
  85449. else {
  85450. back = [];
  85451. }
  85452. return front.concat(back);
  85453. };
  85454. // Remove all polygons in this BSP tree that are inside the other BSP tree
  85455. // `bsp`.
  85456. Node.prototype.clipTo = function (bsp) {
  85457. this.polygons = bsp.clipPolygons(this.polygons);
  85458. if (this.front)
  85459. this.front.clipTo(bsp);
  85460. if (this.back)
  85461. this.back.clipTo(bsp);
  85462. };
  85463. // Return a list of all polygons in this BSP tree.
  85464. Node.prototype.allPolygons = function () {
  85465. var polygons = this.polygons.slice();
  85466. if (this.front)
  85467. polygons = polygons.concat(this.front.allPolygons());
  85468. if (this.back)
  85469. polygons = polygons.concat(this.back.allPolygons());
  85470. return polygons;
  85471. };
  85472. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  85473. // new polygons are filtered down to the bottom of the tree and become new
  85474. // nodes there. Each set of polygons is partitioned using the first polygon
  85475. // (no heuristic is used to pick a good split).
  85476. Node.prototype.build = function (polygons) {
  85477. if (!polygons.length)
  85478. return;
  85479. if (!this.plane)
  85480. this.plane = polygons[0].plane.clone();
  85481. var front = new Array(), back = new Array();
  85482. for (var i = 0; i < polygons.length; i++) {
  85483. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  85484. }
  85485. if (front.length) {
  85486. if (!this.front)
  85487. this.front = new Node();
  85488. this.front.build(front);
  85489. }
  85490. if (back.length) {
  85491. if (!this.back)
  85492. this.back = new Node();
  85493. this.back.build(back);
  85494. }
  85495. };
  85496. return Node;
  85497. }());
  85498. var CSG = /** @class */ (function () {
  85499. function CSG() {
  85500. this.polygons = new Array();
  85501. }
  85502. // Convert BABYLON.Mesh to BABYLON.CSG
  85503. CSG.FromMesh = function (mesh) {
  85504. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  85505. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  85506. if (mesh instanceof BABYLON.Mesh) {
  85507. mesh.computeWorldMatrix(true);
  85508. matrix = mesh.getWorldMatrix();
  85509. meshPosition = mesh.position.clone();
  85510. meshRotation = mesh.rotation.clone();
  85511. if (mesh.rotationQuaternion) {
  85512. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  85513. }
  85514. meshScaling = mesh.scaling.clone();
  85515. }
  85516. else {
  85517. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  85518. }
  85519. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  85520. var subMeshes = mesh.subMeshes;
  85521. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  85522. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  85523. vertices = [];
  85524. for (var j = 0; j < 3; j++) {
  85525. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  85526. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  85527. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  85528. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  85529. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  85530. vertex = new Vertex(position, normal, uv);
  85531. vertices.push(vertex);
  85532. }
  85533. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  85534. // To handle the case of degenerated triangle
  85535. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  85536. if (polygon.plane)
  85537. polygons.push(polygon);
  85538. }
  85539. }
  85540. var csg = CSG.FromPolygons(polygons);
  85541. csg.matrix = matrix;
  85542. csg.position = meshPosition;
  85543. csg.rotation = meshRotation;
  85544. csg.scaling = meshScaling;
  85545. csg.rotationQuaternion = meshRotationQuaternion;
  85546. currentCSGMeshId++;
  85547. return csg;
  85548. };
  85549. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  85550. CSG.FromPolygons = function (polygons) {
  85551. var csg = new CSG();
  85552. csg.polygons = polygons;
  85553. return csg;
  85554. };
  85555. CSG.prototype.clone = function () {
  85556. var csg = new CSG();
  85557. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  85558. csg.copyTransformAttributes(this);
  85559. return csg;
  85560. };
  85561. CSG.prototype.union = function (csg) {
  85562. var a = new Node(this.clone().polygons);
  85563. var b = new Node(csg.clone().polygons);
  85564. a.clipTo(b);
  85565. b.clipTo(a);
  85566. b.invert();
  85567. b.clipTo(a);
  85568. b.invert();
  85569. a.build(b.allPolygons());
  85570. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  85571. };
  85572. CSG.prototype.unionInPlace = function (csg) {
  85573. var a = new Node(this.polygons);
  85574. var b = new Node(csg.polygons);
  85575. a.clipTo(b);
  85576. b.clipTo(a);
  85577. b.invert();
  85578. b.clipTo(a);
  85579. b.invert();
  85580. a.build(b.allPolygons());
  85581. this.polygons = a.allPolygons();
  85582. };
  85583. CSG.prototype.subtract = function (csg) {
  85584. var a = new Node(this.clone().polygons);
  85585. var b = new Node(csg.clone().polygons);
  85586. a.invert();
  85587. a.clipTo(b);
  85588. b.clipTo(a);
  85589. b.invert();
  85590. b.clipTo(a);
  85591. b.invert();
  85592. a.build(b.allPolygons());
  85593. a.invert();
  85594. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  85595. };
  85596. CSG.prototype.subtractInPlace = function (csg) {
  85597. var a = new Node(this.polygons);
  85598. var b = new Node(csg.polygons);
  85599. a.invert();
  85600. a.clipTo(b);
  85601. b.clipTo(a);
  85602. b.invert();
  85603. b.clipTo(a);
  85604. b.invert();
  85605. a.build(b.allPolygons());
  85606. a.invert();
  85607. this.polygons = a.allPolygons();
  85608. };
  85609. CSG.prototype.intersect = function (csg) {
  85610. var a = new Node(this.clone().polygons);
  85611. var b = new Node(csg.clone().polygons);
  85612. a.invert();
  85613. b.clipTo(a);
  85614. b.invert();
  85615. a.clipTo(b);
  85616. b.clipTo(a);
  85617. a.build(b.allPolygons());
  85618. a.invert();
  85619. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  85620. };
  85621. CSG.prototype.intersectInPlace = function (csg) {
  85622. var a = new Node(this.polygons);
  85623. var b = new Node(csg.polygons);
  85624. a.invert();
  85625. b.clipTo(a);
  85626. b.invert();
  85627. a.clipTo(b);
  85628. b.clipTo(a);
  85629. a.build(b.allPolygons());
  85630. a.invert();
  85631. this.polygons = a.allPolygons();
  85632. };
  85633. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  85634. // not modified.
  85635. CSG.prototype.inverse = function () {
  85636. var csg = this.clone();
  85637. csg.inverseInPlace();
  85638. return csg;
  85639. };
  85640. CSG.prototype.inverseInPlace = function () {
  85641. this.polygons.map(function (p) { p.flip(); });
  85642. };
  85643. // This is used to keep meshes transformations so they can be restored
  85644. // when we build back a Babylon Mesh
  85645. // NB : All CSG operations are performed in world coordinates
  85646. CSG.prototype.copyTransformAttributes = function (csg) {
  85647. this.matrix = csg.matrix;
  85648. this.position = csg.position;
  85649. this.rotation = csg.rotation;
  85650. this.scaling = csg.scaling;
  85651. this.rotationQuaternion = csg.rotationQuaternion;
  85652. return this;
  85653. };
  85654. // Build Raw mesh from CSG
  85655. // Coordinates here are in world space
  85656. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  85657. var matrix = this.matrix.clone();
  85658. matrix.invert();
  85659. 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;
  85660. if (keepSubMeshes) {
  85661. // Sort Polygons, since subMeshes are indices range
  85662. polygons.sort(function (a, b) {
  85663. if (a.shared.meshId === b.shared.meshId) {
  85664. return a.shared.subMeshId - b.shared.subMeshId;
  85665. }
  85666. else {
  85667. return a.shared.meshId - b.shared.meshId;
  85668. }
  85669. });
  85670. }
  85671. for (var i = 0, il = polygons.length; i < il; i++) {
  85672. polygon = polygons[i];
  85673. // Building SubMeshes
  85674. if (!subMesh_dict[polygon.shared.meshId]) {
  85675. subMesh_dict[polygon.shared.meshId] = {};
  85676. }
  85677. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  85678. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  85679. indexStart: +Infinity,
  85680. indexEnd: -Infinity,
  85681. materialIndex: polygon.shared.materialIndex
  85682. };
  85683. }
  85684. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  85685. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  85686. polygonIndices[0] = 0;
  85687. polygonIndices[1] = j - 1;
  85688. polygonIndices[2] = j;
  85689. for (var k = 0; k < 3; k++) {
  85690. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  85691. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  85692. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  85693. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  85694. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  85695. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  85696. // Check if 2 points can be merged
  85697. if (!(typeof vertex_idx !== 'undefined' &&
  85698. normals[vertex_idx * 3] === localNormal.x &&
  85699. normals[vertex_idx * 3 + 1] === localNormal.y &&
  85700. normals[vertex_idx * 3 + 2] === localNormal.z &&
  85701. uvs[vertex_idx * 2] === uv.x &&
  85702. uvs[vertex_idx * 2 + 1] === uv.y)) {
  85703. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  85704. uvs.push(uv.x, uv.y);
  85705. normals.push(normal.x, normal.y, normal.z);
  85706. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  85707. }
  85708. indices.push(vertex_idx);
  85709. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  85710. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  85711. currentIndex++;
  85712. }
  85713. }
  85714. }
  85715. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  85716. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  85717. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  85718. mesh.setIndices(indices, null);
  85719. if (keepSubMeshes) {
  85720. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  85721. var materialIndexOffset = 0, materialMaxIndex;
  85722. mesh.subMeshes = new Array();
  85723. for (var m in subMesh_dict) {
  85724. materialMaxIndex = -1;
  85725. for (var sm in subMesh_dict[m]) {
  85726. subMesh_obj = subMesh_dict[m][sm];
  85727. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  85728. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  85729. }
  85730. materialIndexOffset += ++materialMaxIndex;
  85731. }
  85732. }
  85733. return mesh;
  85734. };
  85735. // Build Mesh from CSG taking material and transforms into account
  85736. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  85737. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  85738. mesh.material = material;
  85739. mesh.position.copyFrom(this.position);
  85740. mesh.rotation.copyFrom(this.rotation);
  85741. if (this.rotationQuaternion) {
  85742. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  85743. }
  85744. mesh.scaling.copyFrom(this.scaling);
  85745. mesh.computeWorldMatrix(true);
  85746. return mesh;
  85747. };
  85748. return CSG;
  85749. }());
  85750. BABYLON.CSG = CSG;
  85751. })(BABYLON || (BABYLON = {}));
  85752. //# sourceMappingURL=babylon.csg.js.map
  85753. var BABYLON;
  85754. (function (BABYLON) {
  85755. var LensFlare = /** @class */ (function () {
  85756. function LensFlare(size, position, color, imgUrl, system) {
  85757. this.size = size;
  85758. this.position = position;
  85759. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  85760. this.color = color || new BABYLON.Color3(1, 1, 1);
  85761. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  85762. this._system = system;
  85763. system.lensFlares.push(this);
  85764. }
  85765. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  85766. return new LensFlare(size, position, color, imgUrl, system);
  85767. };
  85768. LensFlare.prototype.dispose = function () {
  85769. if (this.texture) {
  85770. this.texture.dispose();
  85771. }
  85772. // Remove from scene
  85773. var index = this._system.lensFlares.indexOf(this);
  85774. this._system.lensFlares.splice(index, 1);
  85775. };
  85776. ;
  85777. return LensFlare;
  85778. }());
  85779. BABYLON.LensFlare = LensFlare;
  85780. })(BABYLON || (BABYLON = {}));
  85781. //# sourceMappingURL=babylon.lensFlare.js.map
  85782. var BABYLON;
  85783. (function (BABYLON) {
  85784. // Adds the parser to the scene parsers.
  85785. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  85786. // Lens flares
  85787. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  85788. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  85789. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  85790. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  85791. container.lensFlareSystems.push(lf);
  85792. }
  85793. }
  85794. });
  85795. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  85796. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  85797. if (this.lensFlareSystems[index].name === name) {
  85798. return this.lensFlareSystems[index];
  85799. }
  85800. }
  85801. return null;
  85802. };
  85803. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  85804. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  85805. if (this.lensFlareSystems[index].id === id) {
  85806. return this.lensFlareSystems[index];
  85807. }
  85808. }
  85809. return null;
  85810. };
  85811. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  85812. var index = this.lensFlareSystems.indexOf(toRemove);
  85813. if (index !== -1) {
  85814. this.lensFlareSystems.splice(index, 1);
  85815. }
  85816. return index;
  85817. };
  85818. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  85819. this.lensFlareSystems.push(newLensFlareSystem);
  85820. };
  85821. /**
  85822. * Defines the lens flare scene component responsible to manage any lens flares
  85823. * in a given scene.
  85824. */
  85825. var LensFlareSystemSceneComponent = /** @class */ (function () {
  85826. /**
  85827. * Creates a new instance of the component for the given scene
  85828. * @param scene Defines the scene to register the component in
  85829. */
  85830. function LensFlareSystemSceneComponent(scene) {
  85831. /**
  85832. * The component name helpfull to identify the component in the list of scene components.
  85833. */
  85834. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  85835. this.scene = scene;
  85836. scene.lensFlareSystems = new Array();
  85837. }
  85838. /**
  85839. * Registers the component in a given scene
  85840. */
  85841. LensFlareSystemSceneComponent.prototype.register = function () {
  85842. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  85843. };
  85844. /**
  85845. * Rebuilds the elements related to this component in case of
  85846. * context lost for instance.
  85847. */
  85848. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  85849. // Nothing to do for lens flare
  85850. };
  85851. /**
  85852. * Adds all the element from the container to the scene
  85853. * @param container the container holding the elements
  85854. */
  85855. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  85856. var _this = this;
  85857. if (!container.lensFlareSystems) {
  85858. return;
  85859. }
  85860. container.lensFlareSystems.forEach(function (o) {
  85861. _this.scene.addLensFlareSystem(o);
  85862. });
  85863. };
  85864. /**
  85865. * Removes all the elements in the container from the scene
  85866. * @param container contains the elements to remove
  85867. */
  85868. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  85869. var _this = this;
  85870. if (!container.lensFlareSystems) {
  85871. return;
  85872. }
  85873. container.lensFlareSystems.forEach(function (o) {
  85874. _this.scene.removeLensFlareSystem(o);
  85875. });
  85876. };
  85877. /**
  85878. * Serializes the component data to the specified json object
  85879. * @param serializationObject The object to serialize to
  85880. */
  85881. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  85882. // Lens flares
  85883. serializationObject.lensFlareSystems = [];
  85884. var lensFlareSystems = this.scene.lensFlareSystems;
  85885. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  85886. var lensFlareSystem = lensFlareSystems_1[_i];
  85887. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  85888. }
  85889. };
  85890. /**
  85891. * Disposes the component and the associated ressources.
  85892. */
  85893. LensFlareSystemSceneComponent.prototype.dispose = function () {
  85894. var lensFlareSystems = this.scene.lensFlareSystems;
  85895. while (lensFlareSystems.length) {
  85896. lensFlareSystems[0].dispose();
  85897. }
  85898. };
  85899. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  85900. // Lens flares
  85901. if (this.scene.lensFlaresEnabled) {
  85902. var lensFlareSystems = this.scene.lensFlareSystems;
  85903. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  85904. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  85905. var lensFlareSystem = lensFlareSystems_2[_i];
  85906. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  85907. lensFlareSystem.render();
  85908. }
  85909. }
  85910. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  85911. }
  85912. };
  85913. return LensFlareSystemSceneComponent;
  85914. }());
  85915. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  85916. })(BABYLON || (BABYLON = {}));
  85917. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  85918. var BABYLON;
  85919. (function (BABYLON) {
  85920. var LensFlareSystem = /** @class */ (function () {
  85921. function LensFlareSystem(name, emitter, scene) {
  85922. this.name = name;
  85923. this.lensFlares = new Array();
  85924. this.borderLimit = 300;
  85925. this.viewportBorder = 0;
  85926. this.layerMask = 0x0FFFFFFF;
  85927. this._vertexBuffers = {};
  85928. this._isEnabled = true;
  85929. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85930. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  85931. if (!component) {
  85932. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  85933. scene._addComponent(component);
  85934. }
  85935. this._emitter = emitter;
  85936. this.id = name;
  85937. scene.lensFlareSystems.push(this);
  85938. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  85939. var engine = scene.getEngine();
  85940. // VBO
  85941. var vertices = [];
  85942. vertices.push(1, 1);
  85943. vertices.push(-1, 1);
  85944. vertices.push(-1, -1);
  85945. vertices.push(1, -1);
  85946. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  85947. // Indices
  85948. var indices = [];
  85949. indices.push(0);
  85950. indices.push(1);
  85951. indices.push(2);
  85952. indices.push(0);
  85953. indices.push(2);
  85954. indices.push(3);
  85955. this._indexBuffer = engine.createIndexBuffer(indices);
  85956. // Effects
  85957. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  85958. }
  85959. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  85960. get: function () {
  85961. return this._isEnabled;
  85962. },
  85963. set: function (value) {
  85964. this._isEnabled = value;
  85965. },
  85966. enumerable: true,
  85967. configurable: true
  85968. });
  85969. LensFlareSystem.prototype.getScene = function () {
  85970. return this._scene;
  85971. };
  85972. LensFlareSystem.prototype.getEmitter = function () {
  85973. return this._emitter;
  85974. };
  85975. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  85976. this._emitter = newEmitter;
  85977. };
  85978. LensFlareSystem.prototype.getEmitterPosition = function () {
  85979. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  85980. };
  85981. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  85982. var position = this.getEmitterPosition();
  85983. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  85984. this._positionX = position.x;
  85985. this._positionY = position.y;
  85986. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  85987. if (this.viewportBorder > 0) {
  85988. globalViewport.x -= this.viewportBorder;
  85989. globalViewport.y -= this.viewportBorder;
  85990. globalViewport.width += this.viewportBorder * 2;
  85991. globalViewport.height += this.viewportBorder * 2;
  85992. position.x += this.viewportBorder;
  85993. position.y += this.viewportBorder;
  85994. this._positionX += this.viewportBorder;
  85995. this._positionY += this.viewportBorder;
  85996. }
  85997. if (position.z > 0) {
  85998. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  85999. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  86000. return true;
  86001. }
  86002. return true;
  86003. }
  86004. return false;
  86005. };
  86006. /** @hidden */
  86007. LensFlareSystem.prototype._isVisible = function () {
  86008. if (!this._isEnabled || !this._scene.activeCamera) {
  86009. return false;
  86010. }
  86011. var emitterPosition = this.getEmitterPosition();
  86012. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  86013. var distance = direction.length();
  86014. direction.normalize();
  86015. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  86016. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  86017. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  86018. };
  86019. LensFlareSystem.prototype.render = function () {
  86020. if (!this._effect.isReady() || !this._scene.activeCamera)
  86021. return false;
  86022. var engine = this._scene.getEngine();
  86023. var viewport = this._scene.activeCamera.viewport;
  86024. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  86025. // Position
  86026. if (!this.computeEffectivePosition(globalViewport)) {
  86027. return false;
  86028. }
  86029. // Visibility
  86030. if (!this._isVisible()) {
  86031. return false;
  86032. }
  86033. // Intensity
  86034. var awayX;
  86035. var awayY;
  86036. if (this._positionX < this.borderLimit + globalViewport.x) {
  86037. awayX = this.borderLimit + globalViewport.x - this._positionX;
  86038. }
  86039. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  86040. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  86041. }
  86042. else {
  86043. awayX = 0;
  86044. }
  86045. if (this._positionY < this.borderLimit + globalViewport.y) {
  86046. awayY = this.borderLimit + globalViewport.y - this._positionY;
  86047. }
  86048. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  86049. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  86050. }
  86051. else {
  86052. awayY = 0;
  86053. }
  86054. var away = (awayX > awayY) ? awayX : awayY;
  86055. away -= this.viewportBorder;
  86056. if (away > this.borderLimit) {
  86057. away = this.borderLimit;
  86058. }
  86059. var intensity = 1.0 - (away / this.borderLimit);
  86060. if (intensity < 0) {
  86061. return false;
  86062. }
  86063. if (intensity > 1.0) {
  86064. intensity = 1.0;
  86065. }
  86066. if (this.viewportBorder > 0) {
  86067. globalViewport.x += this.viewportBorder;
  86068. globalViewport.y += this.viewportBorder;
  86069. globalViewport.width -= this.viewportBorder * 2;
  86070. globalViewport.height -= this.viewportBorder * 2;
  86071. this._positionX -= this.viewportBorder;
  86072. this._positionY -= this.viewportBorder;
  86073. }
  86074. // Position
  86075. var centerX = globalViewport.x + globalViewport.width / 2;
  86076. var centerY = globalViewport.y + globalViewport.height / 2;
  86077. var distX = centerX - this._positionX;
  86078. var distY = centerY - this._positionY;
  86079. // Effects
  86080. engine.enableEffect(this._effect);
  86081. engine.setState(false);
  86082. engine.setDepthBuffer(false);
  86083. // VBOs
  86084. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  86085. // Flares
  86086. for (var index = 0; index < this.lensFlares.length; index++) {
  86087. var flare = this.lensFlares[index];
  86088. engine.setAlphaMode(flare.alphaMode);
  86089. var x = centerX - (distX * flare.position);
  86090. var y = centerY - (distY * flare.position);
  86091. var cw = flare.size;
  86092. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  86093. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  86094. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  86095. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  86096. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  86097. // Texture
  86098. this._effect.setTexture("textureSampler", flare.texture);
  86099. // Color
  86100. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  86101. // Draw order
  86102. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86103. }
  86104. engine.setDepthBuffer(true);
  86105. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  86106. return true;
  86107. };
  86108. LensFlareSystem.prototype.dispose = function () {
  86109. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86110. if (vertexBuffer) {
  86111. vertexBuffer.dispose();
  86112. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86113. }
  86114. if (this._indexBuffer) {
  86115. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86116. this._indexBuffer = null;
  86117. }
  86118. while (this.lensFlares.length) {
  86119. this.lensFlares[0].dispose();
  86120. }
  86121. // Remove from scene
  86122. var index = this._scene.lensFlareSystems.indexOf(this);
  86123. this._scene.lensFlareSystems.splice(index, 1);
  86124. };
  86125. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  86126. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  86127. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  86128. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  86129. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  86130. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  86131. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  86132. var parsedFlare = parsedLensFlareSystem.flares[index];
  86133. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  86134. }
  86135. return lensFlareSystem;
  86136. };
  86137. LensFlareSystem.prototype.serialize = function () {
  86138. var serializationObject = {};
  86139. serializationObject.id = this.id;
  86140. serializationObject.name = this.name;
  86141. serializationObject.emitterId = this.getEmitter().id;
  86142. serializationObject.borderLimit = this.borderLimit;
  86143. serializationObject.flares = [];
  86144. for (var index = 0; index < this.lensFlares.length; index++) {
  86145. var flare = this.lensFlares[index];
  86146. serializationObject.flares.push({
  86147. size: flare.size,
  86148. position: flare.position,
  86149. color: flare.color.asArray(),
  86150. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  86151. });
  86152. }
  86153. return serializationObject;
  86154. };
  86155. return LensFlareSystem;
  86156. }());
  86157. BABYLON.LensFlareSystem = LensFlareSystem;
  86158. })(BABYLON || (BABYLON = {}));
  86159. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  86160. var BABYLON;
  86161. (function (BABYLON) {
  86162. /**
  86163. * This is a holder class for the physics joint created by the physics plugin.
  86164. * It holds a set of functions to control the underlying joint.
  86165. */
  86166. var PhysicsJoint = /** @class */ (function () {
  86167. function PhysicsJoint(type, jointData) {
  86168. this.type = type;
  86169. this.jointData = jointData;
  86170. jointData.nativeParams = jointData.nativeParams || {};
  86171. }
  86172. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  86173. get: function () {
  86174. return this._physicsJoint;
  86175. },
  86176. set: function (newJoint) {
  86177. if (this._physicsJoint) {
  86178. //remove from the wolrd
  86179. }
  86180. this._physicsJoint = newJoint;
  86181. },
  86182. enumerable: true,
  86183. configurable: true
  86184. });
  86185. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  86186. set: function (physicsPlugin) {
  86187. this._physicsPlugin = physicsPlugin;
  86188. },
  86189. enumerable: true,
  86190. configurable: true
  86191. });
  86192. /**
  86193. * Execute a function that is physics-plugin specific.
  86194. * @param {Function} func the function that will be executed.
  86195. * It accepts two parameters: the physics world and the physics joint.
  86196. */
  86197. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  86198. func(this._physicsPlugin.world, this._physicsJoint);
  86199. };
  86200. //TODO check if the native joints are the same
  86201. //Joint Types
  86202. PhysicsJoint.DistanceJoint = 0;
  86203. PhysicsJoint.HingeJoint = 1;
  86204. PhysicsJoint.BallAndSocketJoint = 2;
  86205. PhysicsJoint.WheelJoint = 3;
  86206. PhysicsJoint.SliderJoint = 4;
  86207. //OIMO
  86208. PhysicsJoint.PrismaticJoint = 5;
  86209. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  86210. PhysicsJoint.UniversalJoint = 6;
  86211. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  86212. //Cannon
  86213. //Similar to a Ball-Joint. Different in params
  86214. PhysicsJoint.PointToPointJoint = 8;
  86215. //Cannon only at the moment
  86216. PhysicsJoint.SpringJoint = 9;
  86217. PhysicsJoint.LockJoint = 10;
  86218. return PhysicsJoint;
  86219. }());
  86220. BABYLON.PhysicsJoint = PhysicsJoint;
  86221. /**
  86222. * A class representing a physics distance joint.
  86223. */
  86224. var DistanceJoint = /** @class */ (function (_super) {
  86225. __extends(DistanceJoint, _super);
  86226. function DistanceJoint(jointData) {
  86227. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  86228. }
  86229. /**
  86230. * Update the predefined distance.
  86231. */
  86232. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  86233. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  86234. };
  86235. return DistanceJoint;
  86236. }(PhysicsJoint));
  86237. BABYLON.DistanceJoint = DistanceJoint;
  86238. var MotorEnabledJoint = /** @class */ (function (_super) {
  86239. __extends(MotorEnabledJoint, _super);
  86240. function MotorEnabledJoint(type, jointData) {
  86241. return _super.call(this, type, jointData) || this;
  86242. }
  86243. /**
  86244. * Set the motor values.
  86245. * Attention, this function is plugin specific. Engines won't react 100% the same.
  86246. * @param {number} force the force to apply
  86247. * @param {number} maxForce max force for this motor.
  86248. */
  86249. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  86250. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  86251. };
  86252. /**
  86253. * Set the motor's limits.
  86254. * Attention, this function is plugin specific. Engines won't react 100% the same.
  86255. */
  86256. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  86257. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  86258. };
  86259. return MotorEnabledJoint;
  86260. }(PhysicsJoint));
  86261. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  86262. /**
  86263. * This class represents a single hinge physics joint
  86264. */
  86265. var HingeJoint = /** @class */ (function (_super) {
  86266. __extends(HingeJoint, _super);
  86267. function HingeJoint(jointData) {
  86268. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  86269. }
  86270. /**
  86271. * Set the motor values.
  86272. * Attention, this function is plugin specific. Engines won't react 100% the same.
  86273. * @param {number} force the force to apply
  86274. * @param {number} maxForce max force for this motor.
  86275. */
  86276. HingeJoint.prototype.setMotor = function (force, maxForce) {
  86277. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  86278. };
  86279. /**
  86280. * Set the motor's limits.
  86281. * Attention, this function is plugin specific. Engines won't react 100% the same.
  86282. */
  86283. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  86284. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  86285. };
  86286. return HingeJoint;
  86287. }(MotorEnabledJoint));
  86288. BABYLON.HingeJoint = HingeJoint;
  86289. /**
  86290. * This class represents a dual hinge physics joint (same as wheel joint)
  86291. */
  86292. var Hinge2Joint = /** @class */ (function (_super) {
  86293. __extends(Hinge2Joint, _super);
  86294. function Hinge2Joint(jointData) {
  86295. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  86296. }
  86297. /**
  86298. * Set the motor values.
  86299. * Attention, this function is plugin specific. Engines won't react 100% the same.
  86300. * @param {number} force the force to apply
  86301. * @param {number} maxForce max force for this motor.
  86302. * @param {motorIndex} the motor's index, 0 or 1.
  86303. */
  86304. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  86305. if (motorIndex === void 0) { motorIndex = 0; }
  86306. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  86307. };
  86308. /**
  86309. * Set the motor limits.
  86310. * Attention, this function is plugin specific. Engines won't react 100% the same.
  86311. * @param {number} upperLimit the upper limit
  86312. * @param {number} lowerLimit lower limit
  86313. * @param {motorIndex} the motor's index, 0 or 1.
  86314. */
  86315. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  86316. if (motorIndex === void 0) { motorIndex = 0; }
  86317. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  86318. };
  86319. return Hinge2Joint;
  86320. }(MotorEnabledJoint));
  86321. BABYLON.Hinge2Joint = Hinge2Joint;
  86322. })(BABYLON || (BABYLON = {}));
  86323. //# sourceMappingURL=babylon.physicsJoint.js.map
  86324. var BABYLON;
  86325. (function (BABYLON) {
  86326. var PhysicsImpostor = /** @class */ (function () {
  86327. function PhysicsImpostor(object, type, _options, _scene) {
  86328. if (_options === void 0) { _options = { mass: 0 }; }
  86329. var _this = this;
  86330. this.object = object;
  86331. this.type = type;
  86332. this._options = _options;
  86333. this._scene = _scene;
  86334. this._bodyUpdateRequired = false;
  86335. this._onBeforePhysicsStepCallbacks = new Array();
  86336. this._onAfterPhysicsStepCallbacks = new Array();
  86337. this._onPhysicsCollideCallbacks = [];
  86338. this._deltaPosition = BABYLON.Vector3.Zero();
  86339. this._isDisposed = false;
  86340. //temp variables for parent rotation calculations
  86341. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  86342. this._tmpQuat = new BABYLON.Quaternion();
  86343. this._tmpQuat2 = new BABYLON.Quaternion();
  86344. /**
  86345. * this function is executed by the physics engine.
  86346. */
  86347. this.beforeStep = function () {
  86348. if (!_this._physicsEngine) {
  86349. return;
  86350. }
  86351. _this.object.translate(_this._deltaPosition, -1);
  86352. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  86353. _this.object.computeWorldMatrix(false);
  86354. if (_this.object.parent && _this.object.rotationQuaternion) {
  86355. _this.getParentsRotation();
  86356. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  86357. }
  86358. else {
  86359. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  86360. }
  86361. if (!_this._options.disableBidirectionalTransformation) {
  86362. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  86363. }
  86364. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  86365. func(_this);
  86366. });
  86367. };
  86368. /**
  86369. * this function is executed by the physics engine.
  86370. */
  86371. this.afterStep = function () {
  86372. if (!_this._physicsEngine) {
  86373. return;
  86374. }
  86375. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  86376. func(_this);
  86377. });
  86378. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  86379. // object has now its world rotation. needs to be converted to local.
  86380. if (_this.object.parent && _this.object.rotationQuaternion) {
  86381. _this.getParentsRotation();
  86382. _this._tmpQuat.conjugateInPlace();
  86383. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  86384. }
  86385. // take the position set and make it the absolute position of this object.
  86386. _this.object.setAbsolutePosition(_this.object.position);
  86387. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  86388. _this.object.translate(_this._deltaPosition, 1);
  86389. };
  86390. /**
  86391. * Legacy collision detection event support
  86392. */
  86393. this.onCollideEvent = null;
  86394. //event and body object due to cannon's event-based architecture.
  86395. this.onCollide = function (e) {
  86396. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  86397. return;
  86398. }
  86399. if (!_this._physicsEngine) {
  86400. return;
  86401. }
  86402. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  86403. if (otherImpostor) {
  86404. // Legacy collision detection event support
  86405. if (_this.onCollideEvent) {
  86406. _this.onCollideEvent(_this, otherImpostor);
  86407. }
  86408. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  86409. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  86410. }).forEach(function (obj) {
  86411. obj.callback(_this, otherImpostor);
  86412. });
  86413. }
  86414. };
  86415. //sanity check!
  86416. if (!this.object) {
  86417. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  86418. return;
  86419. }
  86420. //legacy support for old syntax.
  86421. if (!this._scene && object.getScene) {
  86422. this._scene = object.getScene();
  86423. }
  86424. if (!this._scene) {
  86425. return;
  86426. }
  86427. this._physicsEngine = this._scene.getPhysicsEngine();
  86428. if (!this._physicsEngine) {
  86429. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  86430. }
  86431. else {
  86432. //set the object's quaternion, if not set
  86433. if (!this.object.rotationQuaternion) {
  86434. if (this.object.rotation) {
  86435. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  86436. }
  86437. else {
  86438. this.object.rotationQuaternion = new BABYLON.Quaternion();
  86439. }
  86440. }
  86441. //default options params
  86442. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  86443. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  86444. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  86445. this._joints = [];
  86446. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  86447. if (!this.object.parent || this._options.ignoreParent) {
  86448. this._init();
  86449. }
  86450. else if (this.object.parent.physicsImpostor) {
  86451. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  86452. }
  86453. }
  86454. }
  86455. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  86456. get: function () {
  86457. return this._isDisposed;
  86458. },
  86459. enumerable: true,
  86460. configurable: true
  86461. });
  86462. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  86463. get: function () {
  86464. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  86465. },
  86466. set: function (value) {
  86467. this.setMass(value);
  86468. },
  86469. enumerable: true,
  86470. configurable: true
  86471. });
  86472. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  86473. get: function () {
  86474. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  86475. },
  86476. set: function (value) {
  86477. if (!this._physicsEngine) {
  86478. return;
  86479. }
  86480. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  86481. },
  86482. enumerable: true,
  86483. configurable: true
  86484. });
  86485. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  86486. get: function () {
  86487. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  86488. },
  86489. set: function (value) {
  86490. if (!this._physicsEngine) {
  86491. return;
  86492. }
  86493. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  86494. },
  86495. enumerable: true,
  86496. configurable: true
  86497. });
  86498. /**
  86499. * This function will completly initialize this impostor.
  86500. * It will create a new body - but only if this mesh has no parent.
  86501. * If it has, this impostor will not be used other than to define the impostor
  86502. * of the child mesh.
  86503. * @hidden
  86504. */
  86505. PhysicsImpostor.prototype._init = function () {
  86506. if (!this._physicsEngine) {
  86507. return;
  86508. }
  86509. this._physicsEngine.removeImpostor(this);
  86510. this.physicsBody = null;
  86511. this._parent = this._parent || this._getPhysicsParent();
  86512. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  86513. this._physicsEngine.addImpostor(this);
  86514. }
  86515. };
  86516. PhysicsImpostor.prototype._getPhysicsParent = function () {
  86517. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  86518. var parentMesh = this.object.parent;
  86519. return parentMesh.physicsImpostor;
  86520. }
  86521. return null;
  86522. };
  86523. /**
  86524. * Should a new body be generated.
  86525. */
  86526. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  86527. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  86528. };
  86529. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  86530. this.forceUpdate();
  86531. };
  86532. /**
  86533. * Force a regeneration of this or the parent's impostor's body.
  86534. * Use under cautious - This will remove all joints already implemented.
  86535. */
  86536. PhysicsImpostor.prototype.forceUpdate = function () {
  86537. this._init();
  86538. if (this.parent && !this._options.ignoreParent) {
  86539. this.parent.forceUpdate();
  86540. }
  86541. };
  86542. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  86543. /*public get mesh(): AbstractMesh {
  86544. return this._mesh;
  86545. }*/
  86546. /**
  86547. * Gets the body that holds this impostor. Either its own, or its parent.
  86548. */
  86549. get: function () {
  86550. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  86551. },
  86552. /**
  86553. * Set the physics body. Used mainly by the physics engine/plugin
  86554. */
  86555. set: function (physicsBody) {
  86556. if (this._physicsBody && this._physicsEngine) {
  86557. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  86558. }
  86559. this._physicsBody = physicsBody;
  86560. this.resetUpdateFlags();
  86561. },
  86562. enumerable: true,
  86563. configurable: true
  86564. });
  86565. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  86566. get: function () {
  86567. return !this._options.ignoreParent && this._parent ? this._parent : null;
  86568. },
  86569. set: function (value) {
  86570. this._parent = value;
  86571. },
  86572. enumerable: true,
  86573. configurable: true
  86574. });
  86575. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  86576. this._bodyUpdateRequired = false;
  86577. };
  86578. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  86579. if (this.object.getBoundingInfo) {
  86580. var q = this.object.rotationQuaternion;
  86581. //reset rotation
  86582. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  86583. //calculate the world matrix with no rotation
  86584. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  86585. var boundingInfo = this.object.getBoundingInfo();
  86586. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  86587. //bring back the rotation
  86588. this.object.rotationQuaternion = q;
  86589. //calculate the world matrix with the new rotation
  86590. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  86591. return size;
  86592. }
  86593. else {
  86594. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  86595. }
  86596. };
  86597. PhysicsImpostor.prototype.getObjectCenter = function () {
  86598. if (this.object.getBoundingInfo) {
  86599. var boundingInfo = this.object.getBoundingInfo();
  86600. return boundingInfo.boundingBox.centerWorld;
  86601. }
  86602. else {
  86603. return this.object.position;
  86604. }
  86605. };
  86606. /**
  86607. * Get a specific parametes from the options parameter.
  86608. */
  86609. PhysicsImpostor.prototype.getParam = function (paramName) {
  86610. return this._options[paramName];
  86611. };
  86612. /**
  86613. * Sets a specific parameter in the options given to the physics plugin
  86614. */
  86615. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  86616. this._options[paramName] = value;
  86617. this._bodyUpdateRequired = true;
  86618. };
  86619. /**
  86620. * Specifically change the body's mass option. Won't recreate the physics body object
  86621. */
  86622. PhysicsImpostor.prototype.setMass = function (mass) {
  86623. if (this.getParam("mass") !== mass) {
  86624. this.setParam("mass", mass);
  86625. }
  86626. if (this._physicsEngine) {
  86627. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  86628. }
  86629. };
  86630. PhysicsImpostor.prototype.getLinearVelocity = function () {
  86631. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  86632. };
  86633. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  86634. if (this._physicsEngine) {
  86635. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  86636. }
  86637. };
  86638. PhysicsImpostor.prototype.getAngularVelocity = function () {
  86639. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  86640. };
  86641. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  86642. if (this._physicsEngine) {
  86643. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  86644. }
  86645. };
  86646. /**
  86647. * Execute a function with the physics plugin native code.
  86648. * Provide a function the will have two variables - the world object and the physics body object.
  86649. */
  86650. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  86651. if (this._physicsEngine) {
  86652. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  86653. }
  86654. };
  86655. /**
  86656. * Register a function that will be executed before the physics world is stepping forward.
  86657. */
  86658. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  86659. this._onBeforePhysicsStepCallbacks.push(func);
  86660. };
  86661. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  86662. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  86663. if (index > -1) {
  86664. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  86665. }
  86666. else {
  86667. BABYLON.Tools.Warn("Function to remove was not found");
  86668. }
  86669. };
  86670. /**
  86671. * Register a function that will be executed after the physics step
  86672. */
  86673. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  86674. this._onAfterPhysicsStepCallbacks.push(func);
  86675. };
  86676. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  86677. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  86678. if (index > -1) {
  86679. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  86680. }
  86681. else {
  86682. BABYLON.Tools.Warn("Function to remove was not found");
  86683. }
  86684. };
  86685. /**
  86686. * register a function that will be executed when this impostor collides against a different body.
  86687. */
  86688. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  86689. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  86690. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  86691. };
  86692. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  86693. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  86694. var index = -1;
  86695. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  86696. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  86697. // chcek the arrays match
  86698. var sameList = cbDef.otherImpostors.every(function (impostor) {
  86699. return collidedAgainstList.indexOf(impostor) > -1;
  86700. });
  86701. if (sameList) {
  86702. index = idx;
  86703. }
  86704. return sameList;
  86705. }
  86706. return false;
  86707. });
  86708. if (found) {
  86709. this._onPhysicsCollideCallbacks.splice(index, 1);
  86710. }
  86711. else {
  86712. BABYLON.Tools.Warn("Function to remove was not found");
  86713. }
  86714. };
  86715. PhysicsImpostor.prototype.getParentsRotation = function () {
  86716. var parent = this.object.parent;
  86717. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  86718. while (parent) {
  86719. if (parent.rotationQuaternion) {
  86720. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  86721. }
  86722. else {
  86723. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  86724. }
  86725. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  86726. parent = parent.parent;
  86727. }
  86728. return this._tmpQuat;
  86729. };
  86730. /**
  86731. * Apply a force
  86732. */
  86733. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  86734. if (this._physicsEngine) {
  86735. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  86736. }
  86737. return this;
  86738. };
  86739. /**
  86740. * Apply an impulse
  86741. */
  86742. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  86743. if (this._physicsEngine) {
  86744. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  86745. }
  86746. return this;
  86747. };
  86748. /**
  86749. * A help function to create a joint.
  86750. */
  86751. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  86752. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  86753. this.addJoint(otherImpostor, joint);
  86754. return this;
  86755. };
  86756. /**
  86757. * Add a joint to this impostor with a different impostor.
  86758. */
  86759. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  86760. this._joints.push({
  86761. otherImpostor: otherImpostor,
  86762. joint: joint
  86763. });
  86764. if (this._physicsEngine) {
  86765. this._physicsEngine.addJoint(this, otherImpostor, joint);
  86766. }
  86767. return this;
  86768. };
  86769. /**
  86770. * Will keep this body still, in a sleep mode.
  86771. */
  86772. PhysicsImpostor.prototype.sleep = function () {
  86773. if (this._physicsEngine) {
  86774. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  86775. }
  86776. return this;
  86777. };
  86778. /**
  86779. * Wake the body up.
  86780. */
  86781. PhysicsImpostor.prototype.wakeUp = function () {
  86782. if (this._physicsEngine) {
  86783. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  86784. }
  86785. return this;
  86786. };
  86787. PhysicsImpostor.prototype.clone = function (newObject) {
  86788. if (!newObject)
  86789. return null;
  86790. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  86791. };
  86792. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  86793. var _this = this;
  86794. //no dispose if no physics engine is available.
  86795. if (!this._physicsEngine) {
  86796. return;
  86797. }
  86798. this._joints.forEach(function (j) {
  86799. if (_this._physicsEngine) {
  86800. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  86801. }
  86802. });
  86803. //dispose the physics body
  86804. this._physicsEngine.removeImpostor(this);
  86805. if (this.parent) {
  86806. this.parent.forceUpdate();
  86807. }
  86808. else {
  86809. /*this._object.getChildMeshes().forEach(function(mesh) {
  86810. if (mesh.physicsImpostor) {
  86811. if (disposeChildren) {
  86812. mesh.physicsImpostor.dispose();
  86813. mesh.physicsImpostor = null;
  86814. }
  86815. }
  86816. })*/
  86817. }
  86818. this._isDisposed = true;
  86819. };
  86820. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  86821. this._deltaPosition.copyFrom(position);
  86822. };
  86823. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  86824. if (!this._deltaRotation) {
  86825. this._deltaRotation = new BABYLON.Quaternion();
  86826. }
  86827. this._deltaRotation.copyFrom(rotation);
  86828. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  86829. };
  86830. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  86831. if (this._physicsEngine) {
  86832. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  86833. }
  86834. return this;
  86835. };
  86836. PhysicsImpostor.prototype.getRadius = function () {
  86837. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  86838. };
  86839. /**
  86840. * Sync a bone with this impostor
  86841. * @param bone The bone to sync to the impostor.
  86842. * @param boneMesh The mesh that the bone is influencing.
  86843. * @param jointPivot The pivot of the joint / bone in local space.
  86844. * @param distToJoint Optional distance from the impostor to the joint.
  86845. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  86846. */
  86847. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  86848. var tempVec = PhysicsImpostor._tmpVecs[0];
  86849. var mesh = this.object;
  86850. if (mesh.rotationQuaternion) {
  86851. if (adjustRotation) {
  86852. var tempQuat = PhysicsImpostor._tmpQuat;
  86853. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  86854. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  86855. }
  86856. else {
  86857. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  86858. }
  86859. }
  86860. tempVec.x = 0;
  86861. tempVec.y = 0;
  86862. tempVec.z = 0;
  86863. if (jointPivot) {
  86864. tempVec.x = jointPivot.x;
  86865. tempVec.y = jointPivot.y;
  86866. tempVec.z = jointPivot.z;
  86867. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  86868. if (distToJoint === undefined || distToJoint === null) {
  86869. distToJoint = jointPivot.length();
  86870. }
  86871. tempVec.x *= distToJoint;
  86872. tempVec.y *= distToJoint;
  86873. tempVec.z *= distToJoint;
  86874. }
  86875. if (bone.getParent()) {
  86876. tempVec.addInPlace(mesh.getAbsolutePosition());
  86877. bone.setAbsolutePosition(tempVec, boneMesh);
  86878. }
  86879. else {
  86880. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  86881. boneMesh.position.x -= tempVec.x;
  86882. boneMesh.position.y -= tempVec.y;
  86883. boneMesh.position.z -= tempVec.z;
  86884. }
  86885. };
  86886. /**
  86887. * Sync impostor to a bone
  86888. * @param bone The bone that the impostor will be synced to.
  86889. * @param boneMesh The mesh that the bone is influencing.
  86890. * @param jointPivot The pivot of the joint / bone in local space.
  86891. * @param distToJoint Optional distance from the impostor to the joint.
  86892. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  86893. * @param boneAxis Optional vector3 axis the bone is aligned with
  86894. */
  86895. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  86896. var mesh = this.object;
  86897. if (mesh.rotationQuaternion) {
  86898. if (adjustRotation) {
  86899. var tempQuat = PhysicsImpostor._tmpQuat;
  86900. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  86901. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  86902. }
  86903. else {
  86904. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  86905. }
  86906. }
  86907. var pos = PhysicsImpostor._tmpVecs[0];
  86908. var boneDir = PhysicsImpostor._tmpVecs[1];
  86909. if (!boneAxis) {
  86910. boneAxis = PhysicsImpostor._tmpVecs[2];
  86911. boneAxis.x = 0;
  86912. boneAxis.y = 1;
  86913. boneAxis.z = 0;
  86914. }
  86915. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  86916. bone.getAbsolutePositionToRef(boneMesh, pos);
  86917. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  86918. distToJoint = jointPivot.length();
  86919. }
  86920. if (distToJoint !== undefined && distToJoint !== null) {
  86921. pos.x += boneDir.x * distToJoint;
  86922. pos.y += boneDir.y * distToJoint;
  86923. pos.z += boneDir.z * distToJoint;
  86924. }
  86925. mesh.setAbsolutePosition(pos);
  86926. };
  86927. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  86928. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  86929. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  86930. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  86931. //Impostor types
  86932. PhysicsImpostor.NoImpostor = 0;
  86933. PhysicsImpostor.SphereImpostor = 1;
  86934. PhysicsImpostor.BoxImpostor = 2;
  86935. PhysicsImpostor.PlaneImpostor = 3;
  86936. PhysicsImpostor.MeshImpostor = 4;
  86937. PhysicsImpostor.CylinderImpostor = 7;
  86938. PhysicsImpostor.ParticleImpostor = 8;
  86939. PhysicsImpostor.HeightmapImpostor = 9;
  86940. return PhysicsImpostor;
  86941. }());
  86942. BABYLON.PhysicsImpostor = PhysicsImpostor;
  86943. })(BABYLON || (BABYLON = {}));
  86944. //# sourceMappingURL=babylon.physicsImpostor.js.map
  86945. var BABYLON;
  86946. (function (BABYLON) {
  86947. var PhysicsEngine = /** @class */ (function () {
  86948. function PhysicsEngine(gravity, _physicsPlugin) {
  86949. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  86950. this._physicsPlugin = _physicsPlugin;
  86951. //new methods and parameters
  86952. this._impostors = [];
  86953. this._joints = [];
  86954. if (!this._physicsPlugin.isSupported()) {
  86955. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  86956. + "Please make sure it is included.");
  86957. }
  86958. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  86959. this.setGravity(gravity);
  86960. this.setTimeStep();
  86961. }
  86962. PhysicsEngine.prototype.setGravity = function (gravity) {
  86963. this.gravity = gravity;
  86964. this._physicsPlugin.setGravity(this.gravity);
  86965. };
  86966. /**
  86967. * Set the time step of the physics engine.
  86968. * default is 1/60.
  86969. * To slow it down, enter 1/600 for example.
  86970. * To speed it up, 1/30
  86971. * @param {number} newTimeStep the new timestep to apply to this world.
  86972. */
  86973. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  86974. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  86975. this._physicsPlugin.setTimeStep(newTimeStep);
  86976. };
  86977. /**
  86978. * Get the time step of the physics engine.
  86979. */
  86980. PhysicsEngine.prototype.getTimeStep = function () {
  86981. return this._physicsPlugin.getTimeStep();
  86982. };
  86983. PhysicsEngine.prototype.dispose = function () {
  86984. this._impostors.forEach(function (impostor) {
  86985. impostor.dispose();
  86986. });
  86987. this._physicsPlugin.dispose();
  86988. };
  86989. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  86990. return this._physicsPlugin.name;
  86991. };
  86992. /**
  86993. * Adding a new impostor for the impostor tracking.
  86994. * This will be done by the impostor itself.
  86995. * @param {PhysicsImpostor} impostor the impostor to add
  86996. */
  86997. PhysicsEngine.prototype.addImpostor = function (impostor) {
  86998. impostor.uniqueId = this._impostors.push(impostor);
  86999. //if no parent, generate the body
  87000. if (!impostor.parent) {
  87001. this._physicsPlugin.generatePhysicsBody(impostor);
  87002. }
  87003. };
  87004. /**
  87005. * Remove an impostor from the engine.
  87006. * This impostor and its mesh will not longer be updated by the physics engine.
  87007. * @param {PhysicsImpostor} impostor the impostor to remove
  87008. */
  87009. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  87010. var index = this._impostors.indexOf(impostor);
  87011. if (index > -1) {
  87012. var removed = this._impostors.splice(index, 1);
  87013. //Is it needed?
  87014. if (removed.length) {
  87015. //this will also remove it from the world.
  87016. removed[0].physicsBody = null;
  87017. }
  87018. }
  87019. };
  87020. /**
  87021. * Add a joint to the physics engine
  87022. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  87023. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  87024. * @param {PhysicsJoint} the joint that will connect both impostors.
  87025. */
  87026. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  87027. var impostorJoint = {
  87028. mainImpostor: mainImpostor,
  87029. connectedImpostor: connectedImpostor,
  87030. joint: joint
  87031. };
  87032. joint.physicsPlugin = this._physicsPlugin;
  87033. this._joints.push(impostorJoint);
  87034. this._physicsPlugin.generateJoint(impostorJoint);
  87035. };
  87036. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  87037. var matchingJoints = this._joints.filter(function (impostorJoint) {
  87038. return (impostorJoint.connectedImpostor === connectedImpostor
  87039. && impostorJoint.joint === joint
  87040. && impostorJoint.mainImpostor === mainImpostor);
  87041. });
  87042. if (matchingJoints.length) {
  87043. this._physicsPlugin.removeJoint(matchingJoints[0]);
  87044. //TODO remove it from the list as well
  87045. }
  87046. };
  87047. /**
  87048. * Called by the scene. no need to call it.
  87049. * @hidden
  87050. */
  87051. PhysicsEngine.prototype._step = function (delta) {
  87052. var _this = this;
  87053. //check if any mesh has no body / requires an update
  87054. this._impostors.forEach(function (impostor) {
  87055. if (impostor.isBodyInitRequired()) {
  87056. _this._physicsPlugin.generatePhysicsBody(impostor);
  87057. }
  87058. });
  87059. if (delta > 0.1) {
  87060. delta = 0.1;
  87061. }
  87062. else if (delta <= 0) {
  87063. delta = 1.0 / 60.0;
  87064. }
  87065. this._physicsPlugin.executeStep(delta, this._impostors);
  87066. };
  87067. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  87068. return this._physicsPlugin;
  87069. };
  87070. PhysicsEngine.prototype.getImpostors = function () {
  87071. return this._impostors;
  87072. };
  87073. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  87074. for (var i = 0; i < this._impostors.length; ++i) {
  87075. if (this._impostors[i].object === object) {
  87076. return this._impostors[i];
  87077. }
  87078. }
  87079. return null;
  87080. };
  87081. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  87082. for (var i = 0; i < this._impostors.length; ++i) {
  87083. if (this._impostors[i].physicsBody === body) {
  87084. return this._impostors[i];
  87085. }
  87086. }
  87087. return null;
  87088. };
  87089. // Statics
  87090. PhysicsEngine.Epsilon = 0.001;
  87091. return PhysicsEngine;
  87092. }());
  87093. BABYLON.PhysicsEngine = PhysicsEngine;
  87094. })(BABYLON || (BABYLON = {}));
  87095. //# sourceMappingURL=babylon.physicsEngine.js.map
  87096. var BABYLON;
  87097. (function (BABYLON) {
  87098. var PhysicsHelper = /** @class */ (function () {
  87099. function PhysicsHelper(scene) {
  87100. this._scene = scene;
  87101. this._physicsEngine = this._scene.getPhysicsEngine();
  87102. if (!this._physicsEngine) {
  87103. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  87104. }
  87105. }
  87106. /**
  87107. * @param {Vector3} origin the origin of the explosion
  87108. * @param {number} radius the explosion radius
  87109. * @param {number} strength the explosion strength
  87110. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  87111. */
  87112. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  87113. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  87114. if (!this._physicsEngine) {
  87115. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  87116. return null;
  87117. }
  87118. var impostors = this._physicsEngine.getImpostors();
  87119. if (impostors.length === 0) {
  87120. return null;
  87121. }
  87122. var event = new PhysicsRadialExplosionEvent(this._scene);
  87123. impostors.forEach(function (impostor) {
  87124. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  87125. if (!impostorForceAndContactPoint) {
  87126. return;
  87127. }
  87128. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  87129. });
  87130. event.dispose(false);
  87131. return event;
  87132. };
  87133. /**
  87134. * @param {Vector3} origin the origin of the explosion
  87135. * @param {number} radius the explosion radius
  87136. * @param {number} strength the explosion strength
  87137. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  87138. */
  87139. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  87140. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  87141. if (!this._physicsEngine) {
  87142. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  87143. return null;
  87144. }
  87145. var impostors = this._physicsEngine.getImpostors();
  87146. if (impostors.length === 0) {
  87147. return null;
  87148. }
  87149. var event = new PhysicsRadialExplosionEvent(this._scene);
  87150. impostors.forEach(function (impostor) {
  87151. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  87152. if (!impostorForceAndContactPoint) {
  87153. return;
  87154. }
  87155. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  87156. });
  87157. event.dispose(false);
  87158. return event;
  87159. };
  87160. /**
  87161. * @param {Vector3} origin the origin of the explosion
  87162. * @param {number} radius the explosion radius
  87163. * @param {number} strength the explosion strength
  87164. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  87165. */
  87166. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  87167. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  87168. if (!this._physicsEngine) {
  87169. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  87170. return null;
  87171. }
  87172. var impostors = this._physicsEngine.getImpostors();
  87173. if (impostors.length === 0) {
  87174. return null;
  87175. }
  87176. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  87177. event.dispose(false);
  87178. return event;
  87179. };
  87180. /**
  87181. * @param {Vector3} origin the origin of the updraft
  87182. * @param {number} radius the radius of the updraft
  87183. * @param {number} strength the strength of the updraft
  87184. * @param {number} height the height of the updraft
  87185. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  87186. */
  87187. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  87188. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  87189. if (!this._physicsEngine) {
  87190. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  87191. return null;
  87192. }
  87193. if (this._physicsEngine.getImpostors().length === 0) {
  87194. return null;
  87195. }
  87196. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  87197. event.dispose(false);
  87198. return event;
  87199. };
  87200. /**
  87201. * @param {Vector3} origin the of the vortex
  87202. * @param {number} radius the radius of the vortex
  87203. * @param {number} strength the strength of the vortex
  87204. * @param {number} height the height of the vortex
  87205. */
  87206. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  87207. if (!this._physicsEngine) {
  87208. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  87209. return null;
  87210. }
  87211. if (this._physicsEngine.getImpostors().length === 0) {
  87212. return null;
  87213. }
  87214. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  87215. event.dispose(false);
  87216. return event;
  87217. };
  87218. return PhysicsHelper;
  87219. }());
  87220. BABYLON.PhysicsHelper = PhysicsHelper;
  87221. /***** Radial explosion *****/
  87222. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  87223. function PhysicsRadialExplosionEvent(scene) {
  87224. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  87225. this._rays = [];
  87226. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  87227. this._scene = scene;
  87228. }
  87229. /**
  87230. * Returns the data related to the radial explosion event (sphere & rays).
  87231. * @returns {PhysicsRadialExplosionEventData}
  87232. */
  87233. PhysicsRadialExplosionEvent.prototype.getData = function () {
  87234. this._dataFetched = true;
  87235. return {
  87236. sphere: this._sphere,
  87237. rays: this._rays,
  87238. };
  87239. };
  87240. /**
  87241. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  87242. * @param impostor
  87243. * @param {Vector3} origin the origin of the explosion
  87244. * @param {number} radius the explosion radius
  87245. * @param {number} strength the explosion strength
  87246. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  87247. * @returns {Nullable<PhysicsForceAndContactPoint>}
  87248. */
  87249. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  87250. if (impostor.mass === 0) {
  87251. return null;
  87252. }
  87253. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  87254. return null;
  87255. }
  87256. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  87257. return null;
  87258. }
  87259. var impostorObjectCenter = impostor.getObjectCenter();
  87260. var direction = impostorObjectCenter.subtract(origin);
  87261. var ray = new BABYLON.Ray(origin, direction, radius);
  87262. this._rays.push(ray);
  87263. var hit = ray.intersectsMesh(impostor.object);
  87264. var contactPoint = hit.pickedPoint;
  87265. if (!contactPoint) {
  87266. return null;
  87267. }
  87268. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  87269. if (distanceFromOrigin > radius) {
  87270. return null;
  87271. }
  87272. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  87273. ? strength
  87274. : strength * (1 - (distanceFromOrigin / radius));
  87275. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  87276. return { force: force, contactPoint: contactPoint };
  87277. };
  87278. /**
  87279. * Disposes the sphere.
  87280. * @param {bolean} force
  87281. */
  87282. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  87283. var _this = this;
  87284. if (force === void 0) { force = true; }
  87285. if (force) {
  87286. this._sphere.dispose();
  87287. }
  87288. else {
  87289. setTimeout(function () {
  87290. if (!_this._dataFetched) {
  87291. _this._sphere.dispose();
  87292. }
  87293. }, 0);
  87294. }
  87295. };
  87296. /*** Helpers ***/
  87297. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  87298. if (!this._sphere) {
  87299. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  87300. this._sphere.isVisible = false;
  87301. }
  87302. };
  87303. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  87304. var impostorObject = impostor.object;
  87305. this._prepareSphere();
  87306. this._sphere.position = origin;
  87307. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  87308. this._sphere._updateBoundingInfo();
  87309. this._sphere.computeWorldMatrix(true);
  87310. return this._sphere.intersectsMesh(impostorObject, true);
  87311. };
  87312. return PhysicsRadialExplosionEvent;
  87313. }());
  87314. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  87315. /***** Gravitational Field *****/
  87316. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  87317. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  87318. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  87319. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  87320. this._physicsHelper = physicsHelper;
  87321. this._scene = scene;
  87322. this._origin = origin;
  87323. this._radius = radius;
  87324. this._strength = strength;
  87325. this._falloff = falloff;
  87326. this._tickCallback = this._tick.bind(this);
  87327. }
  87328. /**
  87329. * Returns the data related to the gravitational field event (sphere).
  87330. * @returns {PhysicsGravitationalFieldEventData}
  87331. */
  87332. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  87333. this._dataFetched = true;
  87334. return {
  87335. sphere: this._sphere,
  87336. };
  87337. };
  87338. /**
  87339. * Enables the gravitational field.
  87340. */
  87341. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  87342. this._tickCallback.call(this);
  87343. this._scene.registerBeforeRender(this._tickCallback);
  87344. };
  87345. /**
  87346. * Disables the gravitational field.
  87347. */
  87348. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  87349. this._scene.unregisterBeforeRender(this._tickCallback);
  87350. };
  87351. /**
  87352. * Disposes the sphere.
  87353. * @param {bolean} force
  87354. */
  87355. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  87356. var _this = this;
  87357. if (force === void 0) { force = true; }
  87358. if (force) {
  87359. this._sphere.dispose();
  87360. }
  87361. else {
  87362. setTimeout(function () {
  87363. if (!_this._dataFetched) {
  87364. _this._sphere.dispose();
  87365. }
  87366. }, 0);
  87367. }
  87368. };
  87369. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  87370. // Since the params won't change, we fetch the event only once
  87371. if (this._sphere) {
  87372. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  87373. }
  87374. else {
  87375. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  87376. if (radialExplosionEvent) {
  87377. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  87378. }
  87379. }
  87380. };
  87381. return PhysicsGravitationalFieldEvent;
  87382. }());
  87383. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  87384. /***** Updraft *****/
  87385. var PhysicsUpdraftEvent = /** @class */ (function () {
  87386. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  87387. this._scene = _scene;
  87388. this._origin = _origin;
  87389. this._radius = _radius;
  87390. this._strength = _strength;
  87391. this._height = _height;
  87392. this._updraftMode = _updraftMode;
  87393. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  87394. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  87395. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  87396. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  87397. this._physicsEngine = this._scene.getPhysicsEngine();
  87398. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  87399. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  87400. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  87401. this._originDirection = this._origin.subtract(this._originTop).normalize();
  87402. }
  87403. this._tickCallback = this._tick.bind(this);
  87404. }
  87405. /**
  87406. * Returns the data related to the updraft event (cylinder).
  87407. * @returns {PhysicsUpdraftEventData}
  87408. */
  87409. PhysicsUpdraftEvent.prototype.getData = function () {
  87410. this._dataFetched = true;
  87411. return {
  87412. cylinder: this._cylinder,
  87413. };
  87414. };
  87415. /**
  87416. * Enables the updraft.
  87417. */
  87418. PhysicsUpdraftEvent.prototype.enable = function () {
  87419. this._tickCallback.call(this);
  87420. this._scene.registerBeforeRender(this._tickCallback);
  87421. };
  87422. /**
  87423. * Disables the cortex.
  87424. */
  87425. PhysicsUpdraftEvent.prototype.disable = function () {
  87426. this._scene.unregisterBeforeRender(this._tickCallback);
  87427. };
  87428. /**
  87429. * Disposes the sphere.
  87430. * @param {bolean} force
  87431. */
  87432. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  87433. var _this = this;
  87434. if (force === void 0) { force = true; }
  87435. if (force) {
  87436. this._cylinder.dispose();
  87437. }
  87438. else {
  87439. setTimeout(function () {
  87440. if (!_this._dataFetched) {
  87441. _this._cylinder.dispose();
  87442. }
  87443. }, 0);
  87444. }
  87445. };
  87446. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  87447. if (impostor.mass === 0) {
  87448. return null;
  87449. }
  87450. if (!this._intersectsWithCylinder(impostor)) {
  87451. return null;
  87452. }
  87453. var impostorObjectCenter = impostor.getObjectCenter();
  87454. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  87455. var direction = this._originDirection;
  87456. }
  87457. else {
  87458. var direction = impostorObjectCenter.subtract(this._originTop);
  87459. }
  87460. var multiplier = this._strength * -1;
  87461. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  87462. return { force: force, contactPoint: impostorObjectCenter };
  87463. };
  87464. PhysicsUpdraftEvent.prototype._tick = function () {
  87465. var _this = this;
  87466. this._physicsEngine.getImpostors().forEach(function (impostor) {
  87467. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  87468. if (!impostorForceAndContactPoint) {
  87469. return;
  87470. }
  87471. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  87472. });
  87473. };
  87474. /*** Helpers ***/
  87475. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  87476. if (!this._cylinder) {
  87477. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  87478. height: this._height,
  87479. diameter: this._radius * 2,
  87480. }, this._scene);
  87481. this._cylinder.isVisible = false;
  87482. }
  87483. };
  87484. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  87485. var impostorObject = impostor.object;
  87486. this._prepareCylinder();
  87487. this._cylinder.position = this._cylinderPosition;
  87488. return this._cylinder.intersectsMesh(impostorObject, true);
  87489. };
  87490. return PhysicsUpdraftEvent;
  87491. }());
  87492. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  87493. /***** Vortex *****/
  87494. var PhysicsVortexEvent = /** @class */ (function () {
  87495. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  87496. this._scene = _scene;
  87497. this._origin = _origin;
  87498. this._radius = _radius;
  87499. this._strength = _strength;
  87500. this._height = _height;
  87501. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  87502. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  87503. this._updraftMultiplier = 0.02;
  87504. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  87505. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  87506. this._physicsEngine = this._scene.getPhysicsEngine();
  87507. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  87508. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  87509. this._tickCallback = this._tick.bind(this);
  87510. }
  87511. /**
  87512. * Returns the data related to the vortex event (cylinder).
  87513. * @returns {PhysicsVortexEventData}
  87514. */
  87515. PhysicsVortexEvent.prototype.getData = function () {
  87516. this._dataFetched = true;
  87517. return {
  87518. cylinder: this._cylinder,
  87519. };
  87520. };
  87521. /**
  87522. * Enables the vortex.
  87523. */
  87524. PhysicsVortexEvent.prototype.enable = function () {
  87525. this._tickCallback.call(this);
  87526. this._scene.registerBeforeRender(this._tickCallback);
  87527. };
  87528. /**
  87529. * Disables the cortex.
  87530. */
  87531. PhysicsVortexEvent.prototype.disable = function () {
  87532. this._scene.unregisterBeforeRender(this._tickCallback);
  87533. };
  87534. /**
  87535. * Disposes the sphere.
  87536. * @param {bolean} force
  87537. */
  87538. PhysicsVortexEvent.prototype.dispose = function (force) {
  87539. var _this = this;
  87540. if (force === void 0) { force = true; }
  87541. if (force) {
  87542. this._cylinder.dispose();
  87543. }
  87544. else {
  87545. setTimeout(function () {
  87546. if (!_this._dataFetched) {
  87547. _this._cylinder.dispose();
  87548. }
  87549. }, 0);
  87550. }
  87551. };
  87552. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  87553. if (impostor.mass === 0) {
  87554. return null;
  87555. }
  87556. if (!this._intersectsWithCylinder(impostor)) {
  87557. return null;
  87558. }
  87559. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  87560. return null;
  87561. }
  87562. var impostorObjectCenter = impostor.getObjectCenter();
  87563. 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)
  87564. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  87565. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  87566. var hit = ray.intersectsMesh(impostor.object);
  87567. var contactPoint = hit.pickedPoint;
  87568. if (!contactPoint) {
  87569. return null;
  87570. }
  87571. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  87572. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  87573. var directionToOrigin = contactPoint.normalize();
  87574. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  87575. directionToOrigin = directionToOrigin.negate();
  87576. }
  87577. // TODO: find a more physically based solution
  87578. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  87579. var forceX = directionToOrigin.x * this._strength / 8;
  87580. var forceY = directionToOrigin.y * this._updraftMultiplier;
  87581. var forceZ = directionToOrigin.z * this._strength / 8;
  87582. }
  87583. else {
  87584. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  87585. var forceY = this._originTop.y * this._updraftMultiplier;
  87586. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  87587. }
  87588. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  87589. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  87590. return { force: force, contactPoint: impostorObjectCenter };
  87591. };
  87592. PhysicsVortexEvent.prototype._tick = function () {
  87593. var _this = this;
  87594. this._physicsEngine.getImpostors().forEach(function (impostor) {
  87595. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  87596. if (!impostorForceAndContactPoint) {
  87597. return;
  87598. }
  87599. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  87600. });
  87601. };
  87602. /*** Helpers ***/
  87603. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  87604. if (!this._cylinder) {
  87605. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  87606. height: this._height,
  87607. diameter: this._radius * 2,
  87608. }, this._scene);
  87609. this._cylinder.isVisible = false;
  87610. }
  87611. };
  87612. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  87613. var impostorObject = impostor.object;
  87614. this._prepareCylinder();
  87615. this._cylinder.position = this._cylinderPosition;
  87616. return this._cylinder.intersectsMesh(impostorObject, true);
  87617. };
  87618. return PhysicsVortexEvent;
  87619. }());
  87620. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  87621. /***** Enums *****/
  87622. /**
  87623. * The strenght of the force in correspondence to the distance of the affected object
  87624. */
  87625. var PhysicsRadialImpulseFalloff;
  87626. (function (PhysicsRadialImpulseFalloff) {
  87627. /** Defines that impulse is constant in strength across it's whole radius */
  87628. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  87629. /** DEfines that impulse gets weaker if it's further from the origin */
  87630. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  87631. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  87632. /**
  87633. * The strenght of the force in correspondence to the distance of the affected object
  87634. */
  87635. var PhysicsUpdraftMode;
  87636. (function (PhysicsUpdraftMode) {
  87637. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  87638. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  87639. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  87640. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  87641. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  87642. })(BABYLON || (BABYLON = {}));
  87643. //# sourceMappingURL=babylon.physicsHelper.js.map
  87644. var BABYLON;
  87645. (function (BABYLON) {
  87646. var CannonJSPlugin = /** @class */ (function () {
  87647. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  87648. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  87649. if (iterations === void 0) { iterations = 10; }
  87650. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  87651. this.name = "CannonJSPlugin";
  87652. this._physicsMaterials = new Array();
  87653. this._fixedTimeStep = 1 / 60;
  87654. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  87655. this.BJSCANNON = CANNON;
  87656. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  87657. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  87658. this._tmpPosition = BABYLON.Vector3.Zero();
  87659. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  87660. this._tmpUnityRotation = new BABYLON.Quaternion();
  87661. if (!this.isSupported()) {
  87662. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  87663. return;
  87664. }
  87665. this._extendNamespace();
  87666. this.world = new this.BJSCANNON.World();
  87667. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  87668. this.world.solver.iterations = iterations;
  87669. }
  87670. CannonJSPlugin.prototype.setGravity = function (gravity) {
  87671. this.world.gravity.copy(gravity);
  87672. };
  87673. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  87674. this._fixedTimeStep = timeStep;
  87675. };
  87676. CannonJSPlugin.prototype.getTimeStep = function () {
  87677. return this._fixedTimeStep;
  87678. };
  87679. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  87680. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  87681. };
  87682. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  87683. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  87684. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  87685. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  87686. };
  87687. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  87688. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  87689. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  87690. impostor.physicsBody.applyForce(impulse, worldPoint);
  87691. };
  87692. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  87693. //parent-child relationship. Does this impostor has a parent impostor?
  87694. if (impostor.parent) {
  87695. if (impostor.physicsBody) {
  87696. this.removePhysicsBody(impostor);
  87697. //TODO is that needed?
  87698. impostor.forceUpdate();
  87699. }
  87700. return;
  87701. }
  87702. //should a new body be created for this impostor?
  87703. if (impostor.isBodyInitRequired()) {
  87704. var shape = this._createShape(impostor);
  87705. //unregister events, if body is being changed
  87706. var oldBody = impostor.physicsBody;
  87707. if (oldBody) {
  87708. this.removePhysicsBody(impostor);
  87709. }
  87710. //create the body and material
  87711. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  87712. var bodyCreationObject = {
  87713. mass: impostor.getParam("mass"),
  87714. material: material
  87715. };
  87716. // A simple extend, in case native options were used.
  87717. var nativeOptions = impostor.getParam("nativeOptions");
  87718. for (var key in nativeOptions) {
  87719. if (nativeOptions.hasOwnProperty(key)) {
  87720. bodyCreationObject[key] = nativeOptions[key];
  87721. }
  87722. }
  87723. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  87724. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  87725. this.world.addEventListener("preStep", impostor.beforeStep);
  87726. this.world.addEventListener("postStep", impostor.afterStep);
  87727. impostor.physicsBody.addShape(shape);
  87728. this.world.add(impostor.physicsBody);
  87729. //try to keep the body moving in the right direction by taking old properties.
  87730. //Should be tested!
  87731. if (oldBody) {
  87732. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  87733. impostor.physicsBody[param].copy(oldBody[param]);
  87734. });
  87735. }
  87736. this._processChildMeshes(impostor);
  87737. }
  87738. //now update the body's transformation
  87739. this._updatePhysicsBodyTransformation(impostor);
  87740. };
  87741. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  87742. var _this = this;
  87743. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  87744. var currentRotation = mainImpostor.object.rotationQuaternion;
  87745. if (meshChildren.length) {
  87746. var processMesh = function (localPosition, mesh) {
  87747. if (!currentRotation || !mesh.rotationQuaternion) {
  87748. return;
  87749. }
  87750. var childImpostor = mesh.getPhysicsImpostor();
  87751. if (childImpostor) {
  87752. var parent = childImpostor.parent;
  87753. if (parent !== mainImpostor) {
  87754. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  87755. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  87756. if (childImpostor.physicsBody) {
  87757. _this.removePhysicsBody(childImpostor);
  87758. childImpostor.physicsBody = null;
  87759. }
  87760. childImpostor.parent = mainImpostor;
  87761. childImpostor.resetUpdateFlags();
  87762. 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));
  87763. //Add the mass of the children.
  87764. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  87765. }
  87766. }
  87767. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  87768. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  87769. };
  87770. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  87771. }
  87772. };
  87773. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  87774. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  87775. this.world.removeEventListener("preStep", impostor.beforeStep);
  87776. this.world.removeEventListener("postStep", impostor.afterStep);
  87777. this.world.remove(impostor.physicsBody);
  87778. };
  87779. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  87780. var mainBody = impostorJoint.mainImpostor.physicsBody;
  87781. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  87782. if (!mainBody || !connectedBody) {
  87783. return;
  87784. }
  87785. var constraint;
  87786. var jointData = impostorJoint.joint.jointData;
  87787. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  87788. var constraintData = {
  87789. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  87790. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  87791. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  87792. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  87793. maxForce: jointData.nativeParams.maxForce,
  87794. collideConnected: !!jointData.collision
  87795. };
  87796. switch (impostorJoint.joint.type) {
  87797. case BABYLON.PhysicsJoint.HingeJoint:
  87798. case BABYLON.PhysicsJoint.Hinge2Joint:
  87799. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  87800. break;
  87801. case BABYLON.PhysicsJoint.DistanceJoint:
  87802. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  87803. break;
  87804. case BABYLON.PhysicsJoint.SpringJoint:
  87805. var springData = jointData;
  87806. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  87807. restLength: springData.length,
  87808. stiffness: springData.stiffness,
  87809. damping: springData.damping,
  87810. localAnchorA: constraintData.pivotA,
  87811. localAnchorB: constraintData.pivotB
  87812. });
  87813. break;
  87814. case BABYLON.PhysicsJoint.LockJoint:
  87815. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  87816. break;
  87817. case BABYLON.PhysicsJoint.PointToPointJoint:
  87818. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  87819. default:
  87820. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  87821. break;
  87822. }
  87823. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  87824. constraint.collideConnected = !!jointData.collision;
  87825. impostorJoint.joint.physicsJoint = constraint;
  87826. //don't add spring as constraint, as it is not one.
  87827. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  87828. this.world.addConstraint(constraint);
  87829. }
  87830. else {
  87831. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  87832. constraint.applyForce();
  87833. });
  87834. }
  87835. };
  87836. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  87837. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  87838. };
  87839. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  87840. var index;
  87841. var mat;
  87842. for (index = 0; index < this._physicsMaterials.length; index++) {
  87843. mat = this._physicsMaterials[index];
  87844. if (mat.friction === friction && mat.restitution === restitution) {
  87845. return mat;
  87846. }
  87847. }
  87848. var currentMat = new this.BJSCANNON.Material(name);
  87849. currentMat.friction = friction;
  87850. currentMat.restitution = restitution;
  87851. this._physicsMaterials.push(currentMat);
  87852. return currentMat;
  87853. };
  87854. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  87855. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  87856. };
  87857. CannonJSPlugin.prototype._createShape = function (impostor) {
  87858. var object = impostor.object;
  87859. var returnValue;
  87860. var extendSize = impostor.getObjectExtendSize();
  87861. switch (impostor.type) {
  87862. case BABYLON.PhysicsImpostor.SphereImpostor:
  87863. var radiusX = extendSize.x;
  87864. var radiusY = extendSize.y;
  87865. var radiusZ = extendSize.z;
  87866. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  87867. break;
  87868. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  87869. case BABYLON.PhysicsImpostor.CylinderImpostor:
  87870. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  87871. break;
  87872. case BABYLON.PhysicsImpostor.BoxImpostor:
  87873. var box = extendSize.scale(0.5);
  87874. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  87875. break;
  87876. case BABYLON.PhysicsImpostor.PlaneImpostor:
  87877. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  87878. returnValue = new this.BJSCANNON.Plane();
  87879. break;
  87880. case BABYLON.PhysicsImpostor.MeshImpostor:
  87881. // should transform the vertex data to world coordinates!!
  87882. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  87883. var rawFaces = object.getIndices ? object.getIndices() : [];
  87884. if (!rawVerts)
  87885. return;
  87886. // get only scale! so the object could transform correctly.
  87887. var oldPosition = object.position.clone();
  87888. var oldRotation = object.rotation && object.rotation.clone();
  87889. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  87890. object.position.copyFromFloats(0, 0, 0);
  87891. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  87892. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  87893. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  87894. var transform = object.computeWorldMatrix(true);
  87895. // convert rawVerts to object space
  87896. var temp = new Array();
  87897. var index;
  87898. for (index = 0; index < rawVerts.length; index += 3) {
  87899. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  87900. }
  87901. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  87902. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  87903. //now set back the transformation!
  87904. object.position.copyFrom(oldPosition);
  87905. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  87906. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  87907. break;
  87908. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  87909. var oldPosition2 = object.position.clone();
  87910. var oldRotation2 = object.rotation && object.rotation.clone();
  87911. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  87912. object.position.copyFromFloats(0, 0, 0);
  87913. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  87914. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  87915. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  87916. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  87917. returnValue = this._createHeightmap(object);
  87918. object.position.copyFrom(oldPosition2);
  87919. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  87920. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  87921. object.computeWorldMatrix(true);
  87922. break;
  87923. case BABYLON.PhysicsImpostor.ParticleImpostor:
  87924. returnValue = new this.BJSCANNON.Particle();
  87925. break;
  87926. }
  87927. return returnValue;
  87928. };
  87929. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  87930. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  87931. var transform = object.computeWorldMatrix(true);
  87932. // convert rawVerts to object space
  87933. var temp = new Array();
  87934. var index;
  87935. for (index = 0; index < pos.length; index += 3) {
  87936. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  87937. }
  87938. pos = temp;
  87939. var matrix = new Array();
  87940. //For now pointDepth will not be used and will be automatically calculated.
  87941. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  87942. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  87943. var boundingInfo = object.getBoundingInfo();
  87944. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  87945. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  87946. var elementSize = dim * 2 / arraySize;
  87947. for (var i = 0; i < pos.length; i = i + 3) {
  87948. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  87949. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  87950. var y = -pos[i + 2] + minY;
  87951. if (!matrix[x]) {
  87952. matrix[x] = [];
  87953. }
  87954. if (!matrix[x][z]) {
  87955. matrix[x][z] = y;
  87956. }
  87957. matrix[x][z] = Math.max(y, matrix[x][z]);
  87958. }
  87959. for (var x = 0; x <= arraySize; ++x) {
  87960. if (!matrix[x]) {
  87961. var loc = 1;
  87962. while (!matrix[(x + loc) % arraySize]) {
  87963. loc++;
  87964. }
  87965. matrix[x] = matrix[(x + loc) % arraySize].slice();
  87966. //console.log("missing x", x);
  87967. }
  87968. for (var z = 0; z <= arraySize; ++z) {
  87969. if (!matrix[x][z]) {
  87970. var loc = 1;
  87971. var newValue;
  87972. while (newValue === undefined) {
  87973. newValue = matrix[x][(z + loc++) % arraySize];
  87974. }
  87975. matrix[x][z] = newValue;
  87976. }
  87977. }
  87978. }
  87979. var shape = new this.BJSCANNON.Heightfield(matrix, {
  87980. elementSize: elementSize
  87981. });
  87982. //For future reference, needed for body transformation
  87983. shape.minY = minY;
  87984. return shape;
  87985. };
  87986. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  87987. var object = impostor.object;
  87988. //make sure it is updated...
  87989. object.computeWorldMatrix && object.computeWorldMatrix(true);
  87990. // The delta between the mesh position and the mesh bounding box center
  87991. var bInfo = object.getBoundingInfo();
  87992. if (!bInfo)
  87993. return;
  87994. var center = impostor.getObjectCenter();
  87995. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  87996. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  87997. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  87998. this._tmpPosition.copyFrom(center);
  87999. var quaternion = object.rotationQuaternion;
  88000. if (!quaternion) {
  88001. return;
  88002. }
  88003. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  88004. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  88005. //-90 DEG in X, precalculated
  88006. quaternion = quaternion.multiply(this._minus90X);
  88007. //Invert! (Precalculated, 90 deg in X)
  88008. //No need to clone. this will never change.
  88009. impostor.setDeltaRotation(this._plus90X);
  88010. }
  88011. //If it is a heightfield, if should be centered.
  88012. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  88013. var mesh = object;
  88014. var boundingInfo = mesh.getBoundingInfo();
  88015. //calculate the correct body position:
  88016. var rotationQuaternion = mesh.rotationQuaternion;
  88017. mesh.rotationQuaternion = this._tmpUnityRotation;
  88018. mesh.computeWorldMatrix(true);
  88019. //get original center with no rotation
  88020. var c = center.clone();
  88021. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  88022. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  88023. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  88024. mesh.setPreTransformMatrix(p);
  88025. mesh.computeWorldMatrix(true);
  88026. //calculate the translation
  88027. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  88028. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  88029. //add it inverted to the delta
  88030. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  88031. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  88032. //rotation is back
  88033. mesh.rotationQuaternion = rotationQuaternion;
  88034. mesh.setPreTransformMatrix(oldPivot);
  88035. mesh.computeWorldMatrix(true);
  88036. }
  88037. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  88038. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  88039. //this._tmpPosition.copyFrom(object.position);
  88040. }
  88041. impostor.setDeltaPosition(this._tmpDeltaPosition);
  88042. //Now update the impostor object
  88043. impostor.physicsBody.position.copy(this._tmpPosition);
  88044. impostor.physicsBody.quaternion.copy(quaternion);
  88045. };
  88046. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  88047. impostor.object.position.copyFrom(impostor.physicsBody.position);
  88048. if (impostor.object.rotationQuaternion) {
  88049. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  88050. }
  88051. };
  88052. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  88053. impostor.physicsBody.position.copy(newPosition);
  88054. impostor.physicsBody.quaternion.copy(newRotation);
  88055. };
  88056. CannonJSPlugin.prototype.isSupported = function () {
  88057. return this.BJSCANNON !== undefined;
  88058. };
  88059. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  88060. impostor.physicsBody.velocity.copy(velocity);
  88061. };
  88062. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  88063. impostor.physicsBody.angularVelocity.copy(velocity);
  88064. };
  88065. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  88066. var v = impostor.physicsBody.velocity;
  88067. if (!v) {
  88068. return null;
  88069. }
  88070. return new BABYLON.Vector3(v.x, v.y, v.z);
  88071. };
  88072. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  88073. var v = impostor.physicsBody.angularVelocity;
  88074. if (!v) {
  88075. return null;
  88076. }
  88077. return new BABYLON.Vector3(v.x, v.y, v.z);
  88078. };
  88079. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  88080. impostor.physicsBody.mass = mass;
  88081. impostor.physicsBody.updateMassProperties();
  88082. };
  88083. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  88084. return impostor.physicsBody.mass;
  88085. };
  88086. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  88087. return impostor.physicsBody.material.friction;
  88088. };
  88089. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  88090. impostor.physicsBody.material.friction = friction;
  88091. };
  88092. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  88093. return impostor.physicsBody.material.restitution;
  88094. };
  88095. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  88096. impostor.physicsBody.material.restitution = restitution;
  88097. };
  88098. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  88099. impostor.physicsBody.sleep();
  88100. };
  88101. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  88102. impostor.physicsBody.wakeUp();
  88103. };
  88104. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  88105. joint.physicsJoint.distance = maxDistance;
  88106. };
  88107. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  88108. // if (!motorIndex) {
  88109. // joint.physicsJoint.enableMotor();
  88110. // }
  88111. // }
  88112. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  88113. // if (!motorIndex) {
  88114. // joint.physicsJoint.disableMotor();
  88115. // }
  88116. // }
  88117. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  88118. if (!motorIndex) {
  88119. joint.physicsJoint.enableMotor();
  88120. joint.physicsJoint.setMotorSpeed(speed);
  88121. if (maxForce) {
  88122. this.setLimit(joint, maxForce);
  88123. }
  88124. }
  88125. };
  88126. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  88127. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  88128. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  88129. };
  88130. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  88131. var body = impostor.physicsBody;
  88132. mesh.position.x = body.position.x;
  88133. mesh.position.y = body.position.y;
  88134. mesh.position.z = body.position.z;
  88135. if (mesh.rotationQuaternion) {
  88136. mesh.rotationQuaternion.x = body.quaternion.x;
  88137. mesh.rotationQuaternion.y = body.quaternion.y;
  88138. mesh.rotationQuaternion.z = body.quaternion.z;
  88139. mesh.rotationQuaternion.w = body.quaternion.w;
  88140. }
  88141. };
  88142. CannonJSPlugin.prototype.getRadius = function (impostor) {
  88143. var shape = impostor.physicsBody.shapes[0];
  88144. return shape.boundingSphereRadius;
  88145. };
  88146. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  88147. var shape = impostor.physicsBody.shapes[0];
  88148. result.x = shape.halfExtents.x * 2;
  88149. result.y = shape.halfExtents.y * 2;
  88150. result.z = shape.halfExtents.z * 2;
  88151. };
  88152. CannonJSPlugin.prototype.dispose = function () {
  88153. };
  88154. CannonJSPlugin.prototype._extendNamespace = function () {
  88155. //this will force cannon to execute at least one step when using interpolation
  88156. var step_tmp1 = new this.BJSCANNON.Vec3();
  88157. var Engine = this.BJSCANNON;
  88158. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  88159. maxSubSteps = maxSubSteps || 10;
  88160. timeSinceLastCalled = timeSinceLastCalled || 0;
  88161. if (timeSinceLastCalled === 0) {
  88162. this.internalStep(dt);
  88163. this.time += dt;
  88164. }
  88165. else {
  88166. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  88167. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  88168. var t0 = performance.now();
  88169. for (var i = 0; i !== internalSteps; i++) {
  88170. this.internalStep(dt);
  88171. if (performance.now() - t0 > dt * 1000) {
  88172. break;
  88173. }
  88174. }
  88175. this.time += timeSinceLastCalled;
  88176. var h = this.time % dt;
  88177. var h_div_dt = h / dt;
  88178. var interpvelo = step_tmp1;
  88179. var bodies = this.bodies;
  88180. for (var j = 0; j !== bodies.length; j++) {
  88181. var b = bodies[j];
  88182. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  88183. b.position.vsub(b.previousPosition, interpvelo);
  88184. interpvelo.scale(h_div_dt, interpvelo);
  88185. b.position.vadd(interpvelo, b.interpolatedPosition);
  88186. }
  88187. else {
  88188. b.interpolatedPosition.copy(b.position);
  88189. b.interpolatedQuaternion.copy(b.quaternion);
  88190. }
  88191. }
  88192. }
  88193. };
  88194. };
  88195. return CannonJSPlugin;
  88196. }());
  88197. BABYLON.CannonJSPlugin = CannonJSPlugin;
  88198. })(BABYLON || (BABYLON = {}));
  88199. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  88200. var BABYLON;
  88201. (function (BABYLON) {
  88202. var OimoJSPlugin = /** @class */ (function () {
  88203. function OimoJSPlugin(iterations) {
  88204. this.name = "OimoJSPlugin";
  88205. this._tmpImpostorsArray = [];
  88206. this._tmpPositionVector = BABYLON.Vector3.Zero();
  88207. this.BJSOIMO = OIMO;
  88208. this.world = new this.BJSOIMO.World({
  88209. iterations: iterations
  88210. });
  88211. this.world.clear();
  88212. }
  88213. OimoJSPlugin.prototype.setGravity = function (gravity) {
  88214. this.world.gravity.copy(gravity);
  88215. };
  88216. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  88217. this.world.timeStep = timeStep;
  88218. };
  88219. OimoJSPlugin.prototype.getTimeStep = function () {
  88220. return this.world.timeStep;
  88221. };
  88222. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  88223. var _this = this;
  88224. impostors.forEach(function (impostor) {
  88225. impostor.beforeStep();
  88226. });
  88227. this.world.step();
  88228. impostors.forEach(function (impostor) {
  88229. impostor.afterStep();
  88230. //update the ordered impostors array
  88231. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  88232. });
  88233. //check for collisions
  88234. var contact = this.world.contacts;
  88235. while (contact !== null) {
  88236. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  88237. contact = contact.next;
  88238. continue;
  88239. }
  88240. //is this body colliding with any other? get the impostor
  88241. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  88242. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  88243. if (!mainImpostor || !collidingImpostor) {
  88244. contact = contact.next;
  88245. continue;
  88246. }
  88247. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  88248. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  88249. contact = contact.next;
  88250. }
  88251. };
  88252. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  88253. var mass = impostor.physicsBody.mass;
  88254. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  88255. };
  88256. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  88257. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  88258. this.applyImpulse(impostor, force, contactPoint);
  88259. };
  88260. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  88261. var _this = this;
  88262. //parent-child relationship. Does this impostor has a parent impostor?
  88263. if (impostor.parent) {
  88264. if (impostor.physicsBody) {
  88265. this.removePhysicsBody(impostor);
  88266. //TODO is that needed?
  88267. impostor.forceUpdate();
  88268. }
  88269. return;
  88270. }
  88271. if (impostor.isBodyInitRequired()) {
  88272. var bodyConfig = {
  88273. name: impostor.uniqueId,
  88274. //Oimo must have mass, also for static objects.
  88275. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  88276. size: [],
  88277. type: [],
  88278. pos: [],
  88279. posShape: [],
  88280. rot: [],
  88281. rotShape: [],
  88282. move: impostor.getParam("mass") !== 0,
  88283. density: impostor.getParam("mass"),
  88284. friction: impostor.getParam("friction"),
  88285. restitution: impostor.getParam("restitution"),
  88286. //Supporting older versions of Oimo
  88287. world: this.world
  88288. };
  88289. var impostors = [impostor];
  88290. var addToArray = function (parent) {
  88291. if (!parent.getChildMeshes)
  88292. return;
  88293. parent.getChildMeshes().forEach(function (m) {
  88294. if (m.physicsImpostor) {
  88295. impostors.push(m.physicsImpostor);
  88296. //m.physicsImpostor._init();
  88297. }
  88298. });
  88299. };
  88300. addToArray(impostor.object);
  88301. var checkWithEpsilon_1 = function (value) {
  88302. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  88303. };
  88304. var globalQuaternion_1 = new BABYLON.Quaternion();
  88305. impostors.forEach(function (i) {
  88306. if (!i.object.rotationQuaternion) {
  88307. return;
  88308. }
  88309. //get the correct bounding box
  88310. var oldQuaternion = i.object.rotationQuaternion;
  88311. globalQuaternion_1 = oldQuaternion.clone();
  88312. var rot = oldQuaternion.toEulerAngles();
  88313. var extendSize = i.getObjectExtendSize();
  88314. var radToDeg = 57.295779513082320876;
  88315. if (i === impostor) {
  88316. var center = impostor.getObjectCenter();
  88317. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  88318. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  88319. //Can also use Array.prototype.push.apply
  88320. bodyConfig.pos.push(center.x);
  88321. bodyConfig.pos.push(center.y);
  88322. bodyConfig.pos.push(center.z);
  88323. bodyConfig.posShape.push(0, 0, 0);
  88324. //tmp solution
  88325. bodyConfig.rot.push(0);
  88326. bodyConfig.rot.push(0);
  88327. bodyConfig.rot.push(0);
  88328. bodyConfig.rotShape.push(0, 0, 0);
  88329. }
  88330. else {
  88331. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  88332. bodyConfig.posShape.push(localPosition.x);
  88333. bodyConfig.posShape.push(localPosition.y);
  88334. bodyConfig.posShape.push(localPosition.z);
  88335. bodyConfig.pos.push(0, 0, 0);
  88336. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  88337. bodyConfig.rot.push(0);
  88338. bodyConfig.rot.push(0);
  88339. bodyConfig.rot.push(0);
  88340. bodyConfig.rotShape.push(rot.x * radToDeg);
  88341. bodyConfig.rotShape.push(rot.y * radToDeg);
  88342. bodyConfig.rotShape.push(rot.z * radToDeg);
  88343. }
  88344. // register mesh
  88345. switch (i.type) {
  88346. case BABYLON.PhysicsImpostor.ParticleImpostor:
  88347. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  88348. case BABYLON.PhysicsImpostor.SphereImpostor:
  88349. var radiusX = extendSize.x;
  88350. var radiusY = extendSize.y;
  88351. var radiusZ = extendSize.z;
  88352. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  88353. bodyConfig.type.push('sphere');
  88354. //due to the way oimo works with compounds, add 3 times
  88355. bodyConfig.size.push(size);
  88356. bodyConfig.size.push(size);
  88357. bodyConfig.size.push(size);
  88358. break;
  88359. case BABYLON.PhysicsImpostor.CylinderImpostor:
  88360. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  88361. var sizeY = checkWithEpsilon_1(extendSize.y);
  88362. bodyConfig.type.push('cylinder');
  88363. bodyConfig.size.push(sizeX);
  88364. bodyConfig.size.push(sizeY);
  88365. //due to the way oimo works with compounds, add one more value.
  88366. bodyConfig.size.push(sizeY);
  88367. break;
  88368. case BABYLON.PhysicsImpostor.PlaneImpostor:
  88369. case BABYLON.PhysicsImpostor.BoxImpostor:
  88370. default:
  88371. var sizeX = checkWithEpsilon_1(extendSize.x);
  88372. var sizeY = checkWithEpsilon_1(extendSize.y);
  88373. var sizeZ = checkWithEpsilon_1(extendSize.z);
  88374. bodyConfig.type.push('box');
  88375. //if (i === impostor) {
  88376. bodyConfig.size.push(sizeX);
  88377. bodyConfig.size.push(sizeY);
  88378. bodyConfig.size.push(sizeZ);
  88379. //} else {
  88380. // bodyConfig.size.push(0,0,0);
  88381. //}
  88382. break;
  88383. }
  88384. //actually not needed, but hey...
  88385. i.object.rotationQuaternion = oldQuaternion;
  88386. });
  88387. impostor.physicsBody = this.world.add(bodyConfig);
  88388. // set the quaternion, ignoring the previously defined (euler) rotation
  88389. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  88390. // update with delta 0, so the body will reveive the new rotation.
  88391. impostor.physicsBody.updatePosition(0);
  88392. }
  88393. else {
  88394. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  88395. }
  88396. impostor.setDeltaPosition(this._tmpPositionVector);
  88397. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  88398. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  88399. };
  88400. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  88401. //impostor.physicsBody.dispose();
  88402. //Same as : (older oimo versions)
  88403. this.world.removeRigidBody(impostor.physicsBody);
  88404. };
  88405. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  88406. var mainBody = impostorJoint.mainImpostor.physicsBody;
  88407. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  88408. if (!mainBody || !connectedBody) {
  88409. return;
  88410. }
  88411. var jointData = impostorJoint.joint.jointData;
  88412. var options = jointData.nativeParams || {};
  88413. var type;
  88414. var nativeJointData = {
  88415. body1: mainBody,
  88416. body2: connectedBody,
  88417. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  88418. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  88419. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  88420. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  88421. min: options.min,
  88422. max: options.max,
  88423. collision: options.collision || jointData.collision,
  88424. spring: options.spring,
  88425. //supporting older version of Oimo
  88426. world: this.world
  88427. };
  88428. switch (impostorJoint.joint.type) {
  88429. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  88430. type = "jointBall";
  88431. break;
  88432. case BABYLON.PhysicsJoint.SpringJoint:
  88433. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  88434. var springData = jointData;
  88435. nativeJointData.min = springData.length || nativeJointData.min;
  88436. //Max should also be set, just make sure it is at least min
  88437. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  88438. case BABYLON.PhysicsJoint.DistanceJoint:
  88439. type = "jointDistance";
  88440. nativeJointData.max = jointData.maxDistance;
  88441. break;
  88442. case BABYLON.PhysicsJoint.PrismaticJoint:
  88443. type = "jointPrisme";
  88444. break;
  88445. case BABYLON.PhysicsJoint.SliderJoint:
  88446. type = "jointSlide";
  88447. break;
  88448. case BABYLON.PhysicsJoint.WheelJoint:
  88449. type = "jointWheel";
  88450. break;
  88451. case BABYLON.PhysicsJoint.HingeJoint:
  88452. default:
  88453. type = "jointHinge";
  88454. break;
  88455. }
  88456. nativeJointData.type = type;
  88457. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  88458. };
  88459. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  88460. //Bug in Oimo prevents us from disposing a joint in the playground
  88461. //joint.joint.physicsJoint.dispose();
  88462. //So we will bruteforce it!
  88463. try {
  88464. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  88465. }
  88466. catch (e) {
  88467. BABYLON.Tools.Warn(e);
  88468. }
  88469. };
  88470. OimoJSPlugin.prototype.isSupported = function () {
  88471. return this.BJSOIMO !== undefined;
  88472. };
  88473. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  88474. if (!impostor.physicsBody.sleeping) {
  88475. //TODO check that
  88476. /*if (impostor.physicsBody.shapes.next) {
  88477. var parentShape = this._getLastShape(impostor.physicsBody);
  88478. impostor.object.position.copyFrom(parentShape.position);
  88479. console.log(parentShape.position);
  88480. } else {*/
  88481. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  88482. //}
  88483. if (impostor.object.rotationQuaternion) {
  88484. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  88485. }
  88486. }
  88487. };
  88488. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  88489. var body = impostor.physicsBody;
  88490. body.position.copy(newPosition);
  88491. body.orientation.copy(newRotation);
  88492. body.syncShapes();
  88493. body.awake();
  88494. };
  88495. /*private _getLastShape(body: any): any {
  88496. var lastShape = body.shapes;
  88497. while (lastShape.next) {
  88498. lastShape = lastShape.next;
  88499. }
  88500. return lastShape;
  88501. }*/
  88502. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  88503. impostor.physicsBody.linearVelocity.copy(velocity);
  88504. };
  88505. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  88506. impostor.physicsBody.angularVelocity.copy(velocity);
  88507. };
  88508. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  88509. var v = impostor.physicsBody.linearVelocity;
  88510. if (!v) {
  88511. return null;
  88512. }
  88513. return new BABYLON.Vector3(v.x, v.y, v.z);
  88514. };
  88515. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  88516. var v = impostor.physicsBody.angularVelocity;
  88517. if (!v) {
  88518. return null;
  88519. }
  88520. return new BABYLON.Vector3(v.x, v.y, v.z);
  88521. };
  88522. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  88523. var staticBody = mass === 0;
  88524. //this will actually set the body's density and not its mass.
  88525. //But this is how oimo treats the mass variable.
  88526. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  88527. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  88528. };
  88529. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  88530. return impostor.physicsBody.shapes.density;
  88531. };
  88532. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  88533. return impostor.physicsBody.shapes.friction;
  88534. };
  88535. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  88536. impostor.physicsBody.shapes.friction = friction;
  88537. };
  88538. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  88539. return impostor.physicsBody.shapes.restitution;
  88540. };
  88541. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  88542. impostor.physicsBody.shapes.restitution = restitution;
  88543. };
  88544. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  88545. impostor.physicsBody.sleep();
  88546. };
  88547. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  88548. impostor.physicsBody.awake();
  88549. };
  88550. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  88551. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  88552. if (minDistance !== void 0) {
  88553. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  88554. }
  88555. };
  88556. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  88557. //TODO separate rotational and transational motors.
  88558. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  88559. if (motor) {
  88560. motor.setMotor(speed, maxForce);
  88561. }
  88562. };
  88563. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  88564. //TODO separate rotational and transational motors.
  88565. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  88566. if (motor) {
  88567. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  88568. }
  88569. };
  88570. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  88571. var body = impostor.physicsBody;
  88572. mesh.position.x = body.position.x;
  88573. mesh.position.y = body.position.y;
  88574. mesh.position.z = body.position.z;
  88575. if (mesh.rotationQuaternion) {
  88576. mesh.rotationQuaternion.x = body.orientation.x;
  88577. mesh.rotationQuaternion.y = body.orientation.y;
  88578. mesh.rotationQuaternion.z = body.orientation.z;
  88579. mesh.rotationQuaternion.w = body.orientation.s;
  88580. }
  88581. };
  88582. OimoJSPlugin.prototype.getRadius = function (impostor) {
  88583. return impostor.physicsBody.shapes.radius;
  88584. };
  88585. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  88586. var shape = impostor.physicsBody.shapes;
  88587. result.x = shape.halfWidth * 2;
  88588. result.y = shape.halfHeight * 2;
  88589. result.z = shape.halfDepth * 2;
  88590. };
  88591. OimoJSPlugin.prototype.dispose = function () {
  88592. this.world.clear();
  88593. };
  88594. return OimoJSPlugin;
  88595. }());
  88596. BABYLON.OimoJSPlugin = OimoJSPlugin;
  88597. })(BABYLON || (BABYLON = {}));
  88598. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  88599. var BABYLON;
  88600. (function (BABYLON) {
  88601. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  88602. // All values and structures referenced from:
  88603. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  88604. var DDS_MAGIC = 0x20534444;
  88605. var
  88606. //DDSD_CAPS = 0x1,
  88607. //DDSD_HEIGHT = 0x2,
  88608. //DDSD_WIDTH = 0x4,
  88609. //DDSD_PITCH = 0x8,
  88610. //DDSD_PIXELFORMAT = 0x1000,
  88611. DDSD_MIPMAPCOUNT = 0x20000;
  88612. //DDSD_LINEARSIZE = 0x80000,
  88613. //DDSD_DEPTH = 0x800000;
  88614. // var DDSCAPS_COMPLEX = 0x8,
  88615. // DDSCAPS_MIPMAP = 0x400000,
  88616. // DDSCAPS_TEXTURE = 0x1000;
  88617. var DDSCAPS2_CUBEMAP = 0x200;
  88618. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  88619. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  88620. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  88621. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  88622. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  88623. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  88624. // DDSCAPS2_VOLUME = 0x200000;
  88625. var
  88626. //DDPF_ALPHAPIXELS = 0x1,
  88627. //DDPF_ALPHA = 0x2,
  88628. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  88629. //DDPF_YUV = 0x200,
  88630. DDPF_LUMINANCE = 0x20000;
  88631. function FourCCToInt32(value) {
  88632. return value.charCodeAt(0) +
  88633. (value.charCodeAt(1) << 8) +
  88634. (value.charCodeAt(2) << 16) +
  88635. (value.charCodeAt(3) << 24);
  88636. }
  88637. function Int32ToFourCC(value) {
  88638. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  88639. }
  88640. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  88641. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  88642. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  88643. var FOURCC_DX10 = FourCCToInt32("DX10");
  88644. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  88645. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  88646. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  88647. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  88648. var headerLengthInt = 31; // The header length in 32 bit ints
  88649. // Offsets into the header array
  88650. var off_magic = 0;
  88651. var off_size = 1;
  88652. var off_flags = 2;
  88653. var off_height = 3;
  88654. var off_width = 4;
  88655. var off_mipmapCount = 7;
  88656. var off_pfFlags = 20;
  88657. var off_pfFourCC = 21;
  88658. var off_RGBbpp = 22;
  88659. var off_RMask = 23;
  88660. var off_GMask = 24;
  88661. var off_BMask = 25;
  88662. var off_AMask = 26;
  88663. // var off_caps1 = 27;
  88664. var off_caps2 = 28;
  88665. // var off_caps3 = 29;
  88666. // var off_caps4 = 30;
  88667. var off_dxgiFormat = 32;
  88668. ;
  88669. var DDSTools = /** @class */ (function () {
  88670. function DDSTools() {
  88671. }
  88672. DDSTools.GetDDSInfo = function (arrayBuffer) {
  88673. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  88674. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  88675. var mipmapCount = 1;
  88676. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  88677. mipmapCount = Math.max(1, header[off_mipmapCount]);
  88678. }
  88679. var fourCC = header[off_pfFourCC];
  88680. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  88681. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  88682. switch (fourCC) {
  88683. case FOURCC_D3DFMT_R16G16B16A16F:
  88684. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  88685. break;
  88686. case FOURCC_D3DFMT_R32G32B32A32F:
  88687. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  88688. break;
  88689. case FOURCC_DX10:
  88690. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  88691. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  88692. break;
  88693. }
  88694. }
  88695. return {
  88696. width: header[off_width],
  88697. height: header[off_height],
  88698. mipmapCount: mipmapCount,
  88699. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  88700. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  88701. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  88702. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  88703. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  88704. dxgiFormat: dxgiFormat,
  88705. textureType: textureType
  88706. };
  88707. };
  88708. DDSTools._ToHalfFloat = function (value) {
  88709. if (!DDSTools._FloatView) {
  88710. DDSTools._FloatView = new Float32Array(1);
  88711. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  88712. }
  88713. DDSTools._FloatView[0] = value;
  88714. var x = DDSTools._Int32View[0];
  88715. var bits = (x >> 16) & 0x8000; /* Get the sign */
  88716. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  88717. var e = (x >> 23) & 0xff; /* Using int is faster here */
  88718. /* If zero, or denormal, or exponent underflows too much for a denormal
  88719. * half, return signed zero. */
  88720. if (e < 103) {
  88721. return bits;
  88722. }
  88723. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  88724. if (e > 142) {
  88725. bits |= 0x7c00;
  88726. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  88727. * not Inf, so make sure we set one mantissa bit too. */
  88728. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  88729. return bits;
  88730. }
  88731. /* If exponent underflows but not too much, return a denormal */
  88732. if (e < 113) {
  88733. m |= 0x0800;
  88734. /* Extra rounding may overflow and set mantissa to 0 and exponent
  88735. * to 1, which is OK. */
  88736. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  88737. return bits;
  88738. }
  88739. bits |= ((e - 112) << 10) | (m >> 1);
  88740. bits += m & 1;
  88741. return bits;
  88742. };
  88743. DDSTools._FromHalfFloat = function (value) {
  88744. var s = (value & 0x8000) >> 15;
  88745. var e = (value & 0x7C00) >> 10;
  88746. var f = value & 0x03FF;
  88747. if (e === 0) {
  88748. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  88749. }
  88750. else if (e == 0x1F) {
  88751. return f ? NaN : ((s ? -1 : 1) * Infinity);
  88752. }
  88753. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  88754. };
  88755. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  88756. var destArray = new Float32Array(dataLength);
  88757. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  88758. var index = 0;
  88759. for (var y = 0; y < height; y++) {
  88760. for (var x = 0; x < width; x++) {
  88761. var srcPos = (x + y * width) * 4;
  88762. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  88763. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  88764. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  88765. if (DDSTools.StoreLODInAlphaChannel) {
  88766. destArray[index + 3] = lod;
  88767. }
  88768. else {
  88769. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  88770. }
  88771. index += 4;
  88772. }
  88773. }
  88774. return destArray;
  88775. };
  88776. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  88777. if (DDSTools.StoreLODInAlphaChannel) {
  88778. var destArray = new Uint16Array(dataLength);
  88779. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  88780. var index = 0;
  88781. for (var y = 0; y < height; y++) {
  88782. for (var x = 0; x < width; x++) {
  88783. var srcPos = (x + y * width) * 4;
  88784. destArray[index] = srcData[srcPos];
  88785. destArray[index + 1] = srcData[srcPos + 1];
  88786. destArray[index + 2] = srcData[srcPos + 2];
  88787. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  88788. index += 4;
  88789. }
  88790. }
  88791. return destArray;
  88792. }
  88793. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  88794. };
  88795. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  88796. if (DDSTools.StoreLODInAlphaChannel) {
  88797. var destArray = new Float32Array(dataLength);
  88798. var srcData = new Float32Array(arrayBuffer, dataOffset);
  88799. var index = 0;
  88800. for (var y = 0; y < height; y++) {
  88801. for (var x = 0; x < width; x++) {
  88802. var srcPos = (x + y * width) * 4;
  88803. destArray[index] = srcData[srcPos];
  88804. destArray[index + 1] = srcData[srcPos + 1];
  88805. destArray[index + 2] = srcData[srcPos + 2];
  88806. destArray[index + 3] = lod;
  88807. index += 4;
  88808. }
  88809. }
  88810. return destArray;
  88811. }
  88812. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  88813. };
  88814. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  88815. var destArray = new Uint8Array(dataLength);
  88816. var srcData = new Float32Array(arrayBuffer, dataOffset);
  88817. var index = 0;
  88818. for (var y = 0; y < height; y++) {
  88819. for (var x = 0; x < width; x++) {
  88820. var srcPos = (x + y * width) * 4;
  88821. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  88822. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  88823. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  88824. if (DDSTools.StoreLODInAlphaChannel) {
  88825. destArray[index + 3] = lod;
  88826. }
  88827. else {
  88828. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  88829. }
  88830. index += 4;
  88831. }
  88832. }
  88833. return destArray;
  88834. };
  88835. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  88836. var destArray = new Uint8Array(dataLength);
  88837. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  88838. var index = 0;
  88839. for (var y = 0; y < height; y++) {
  88840. for (var x = 0; x < width; x++) {
  88841. var srcPos = (x + y * width) * 4;
  88842. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  88843. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  88844. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  88845. if (DDSTools.StoreLODInAlphaChannel) {
  88846. destArray[index + 3] = lod;
  88847. }
  88848. else {
  88849. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  88850. }
  88851. index += 4;
  88852. }
  88853. }
  88854. return destArray;
  88855. };
  88856. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  88857. var byteArray = new Uint8Array(dataLength);
  88858. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  88859. var index = 0;
  88860. for (var y = 0; y < height; y++) {
  88861. for (var x = 0; x < width; x++) {
  88862. var srcPos = (x + y * width) * 4;
  88863. byteArray[index] = srcData[srcPos + rOffset];
  88864. byteArray[index + 1] = srcData[srcPos + gOffset];
  88865. byteArray[index + 2] = srcData[srcPos + bOffset];
  88866. byteArray[index + 3] = srcData[srcPos + aOffset];
  88867. index += 4;
  88868. }
  88869. }
  88870. return byteArray;
  88871. };
  88872. DDSTools._ExtractLongWordOrder = function (value) {
  88873. if (value === 0 || value === 255 || value === -16777216) {
  88874. return 0;
  88875. }
  88876. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  88877. };
  88878. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  88879. var byteArray = new Uint8Array(dataLength);
  88880. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  88881. var index = 0;
  88882. for (var y = 0; y < height; y++) {
  88883. for (var x = 0; x < width; x++) {
  88884. var srcPos = (x + y * width) * 3;
  88885. byteArray[index] = srcData[srcPos + rOffset];
  88886. byteArray[index + 1] = srcData[srcPos + gOffset];
  88887. byteArray[index + 2] = srcData[srcPos + bOffset];
  88888. index += 3;
  88889. }
  88890. }
  88891. return byteArray;
  88892. };
  88893. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  88894. var byteArray = new Uint8Array(dataLength);
  88895. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  88896. var index = 0;
  88897. for (var y = 0; y < height; y++) {
  88898. for (var x = 0; x < width; x++) {
  88899. var srcPos = (x + y * width);
  88900. byteArray[index] = srcData[srcPos];
  88901. index++;
  88902. }
  88903. }
  88904. return byteArray;
  88905. };
  88906. /**
  88907. * Uploads DDS Levels to a Babylon Texture
  88908. * @hidden
  88909. */
  88910. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  88911. if (lodIndex === void 0) { lodIndex = -1; }
  88912. var sphericalPolynomialFaces = null;
  88913. if (info.sphericalPolynomial) {
  88914. sphericalPolynomialFaces = new Array();
  88915. }
  88916. var ext = engine.getCaps().s3tc;
  88917. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  88918. var fourCC, width, height, dataLength = 0, dataOffset;
  88919. var byteArray, mipmapCount, mip;
  88920. var internalCompressedFormat = 0;
  88921. var blockBytes = 1;
  88922. if (header[off_magic] !== DDS_MAGIC) {
  88923. BABYLON.Tools.Error("Invalid magic number in DDS header");
  88924. return;
  88925. }
  88926. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  88927. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  88928. return;
  88929. }
  88930. if (info.isCompressed && !ext) {
  88931. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  88932. return;
  88933. }
  88934. var bpp = header[off_RGBbpp];
  88935. dataOffset = header[off_size] + 4;
  88936. var computeFormats = false;
  88937. if (info.isFourCC) {
  88938. fourCC = header[off_pfFourCC];
  88939. switch (fourCC) {
  88940. case FOURCC_DXT1:
  88941. blockBytes = 8;
  88942. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  88943. break;
  88944. case FOURCC_DXT3:
  88945. blockBytes = 16;
  88946. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  88947. break;
  88948. case FOURCC_DXT5:
  88949. blockBytes = 16;
  88950. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  88951. break;
  88952. case FOURCC_D3DFMT_R16G16B16A16F:
  88953. computeFormats = true;
  88954. break;
  88955. case FOURCC_D3DFMT_R32G32B32A32F:
  88956. computeFormats = true;
  88957. break;
  88958. case FOURCC_DX10:
  88959. // There is an additionnal header so dataOffset need to be changed
  88960. dataOffset += 5 * 4; // 5 uints
  88961. var supported = false;
  88962. switch (info.dxgiFormat) {
  88963. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  88964. computeFormats = true;
  88965. supported = true;
  88966. break;
  88967. case DXGI_FORMAT_B8G8R8X8_UNORM:
  88968. info.isRGB = true;
  88969. info.isFourCC = false;
  88970. bpp = 32;
  88971. supported = true;
  88972. break;
  88973. }
  88974. if (supported) {
  88975. break;
  88976. }
  88977. default:
  88978. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  88979. return;
  88980. }
  88981. }
  88982. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  88983. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  88984. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  88985. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  88986. if (computeFormats) {
  88987. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  88988. }
  88989. mipmapCount = 1;
  88990. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  88991. mipmapCount = Math.max(1, header[off_mipmapCount]);
  88992. }
  88993. for (var face = 0; face < faces; face++) {
  88994. width = header[off_width];
  88995. height = header[off_height];
  88996. for (mip = 0; mip < mipmapCount; ++mip) {
  88997. if (lodIndex === -1 || lodIndex === mip) {
  88998. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  88999. var i = (lodIndex === -1) ? mip : 0;
  89000. if (!info.isCompressed && info.isFourCC) {
  89001. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  89002. dataLength = width * height * 4;
  89003. var floatArray = null;
  89004. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  89005. if (bpp === 128) {
  89006. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  89007. if (sphericalPolynomialFaces && i == 0) {
  89008. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  89009. }
  89010. }
  89011. else if (bpp === 64) {
  89012. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  89013. if (sphericalPolynomialFaces && i == 0) {
  89014. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  89015. }
  89016. }
  89017. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89018. }
  89019. else {
  89020. if (bpp === 128) {
  89021. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  89022. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  89023. if (sphericalPolynomialFaces && i == 0) {
  89024. sphericalPolynomialFaces.push(floatArray);
  89025. }
  89026. }
  89027. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  89028. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  89029. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  89030. if (sphericalPolynomialFaces && i == 0) {
  89031. sphericalPolynomialFaces.push(floatArray);
  89032. }
  89033. }
  89034. else { // 64
  89035. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  89036. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  89037. if (sphericalPolynomialFaces && i == 0) {
  89038. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  89039. }
  89040. }
  89041. }
  89042. if (floatArray) {
  89043. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  89044. }
  89045. }
  89046. else if (info.isRGB) {
  89047. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89048. if (bpp === 24) {
  89049. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  89050. dataLength = width * height * 3;
  89051. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  89052. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  89053. }
  89054. else { // 32
  89055. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  89056. dataLength = width * height * 4;
  89057. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  89058. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  89059. }
  89060. }
  89061. else if (info.isLuminance) {
  89062. var unpackAlignment = engine._getUnpackAlignement();
  89063. var unpaddedRowSize = width;
  89064. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  89065. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  89066. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  89067. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  89068. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89069. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  89070. }
  89071. else {
  89072. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  89073. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  89074. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89075. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  89076. }
  89077. }
  89078. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  89079. width *= 0.5;
  89080. height *= 0.5;
  89081. width = Math.max(1.0, width);
  89082. height = Math.max(1.0, height);
  89083. }
  89084. if (currentFace !== undefined) {
  89085. // Loading a single face
  89086. break;
  89087. }
  89088. }
  89089. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  89090. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  89091. size: header[off_width],
  89092. right: sphericalPolynomialFaces[0],
  89093. left: sphericalPolynomialFaces[1],
  89094. up: sphericalPolynomialFaces[2],
  89095. down: sphericalPolynomialFaces[3],
  89096. front: sphericalPolynomialFaces[4],
  89097. back: sphericalPolynomialFaces[5],
  89098. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  89099. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  89100. gammaSpace: false,
  89101. });
  89102. }
  89103. else {
  89104. info.sphericalPolynomial = undefined;
  89105. }
  89106. };
  89107. DDSTools.StoreLODInAlphaChannel = false;
  89108. return DDSTools;
  89109. }());
  89110. BABYLON.DDSTools = DDSTools;
  89111. })(BABYLON || (BABYLON = {}));
  89112. //# sourceMappingURL=babylon.dds.js.map
  89113. var BABYLON;
  89114. (function (BABYLON) {
  89115. /**
  89116. * Implementation of the DDS Texture Loader.
  89117. */
  89118. var DDSTextureLoader = /** @class */ (function () {
  89119. function DDSTextureLoader() {
  89120. /**
  89121. * Defines wether the loader supports cascade loading the different faces.
  89122. */
  89123. this.supportCascades = true;
  89124. }
  89125. /**
  89126. * This returns if the loader support the current file information.
  89127. * @param extension defines the file extension of the file being loaded
  89128. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89129. * @param fallback defines the fallback internal texture if any
  89130. * @param isBase64 defines whether the texture is encoded as a base64
  89131. * @param isBuffer defines whether the texture data are stored as a buffer
  89132. * @returns true if the loader can load the specified file
  89133. */
  89134. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  89135. return extension.indexOf(".dds") === 0;
  89136. };
  89137. /**
  89138. * Transform the url before loading if required.
  89139. * @param rootUrl the url of the texture
  89140. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89141. * @returns the transformed texture
  89142. */
  89143. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  89144. return rootUrl;
  89145. };
  89146. /**
  89147. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  89148. * @param rootUrl the url of the texture
  89149. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89150. * @returns the fallback texture
  89151. */
  89152. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  89153. return null;
  89154. };
  89155. /**
  89156. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  89157. * @param data contains the texture data
  89158. * @param texture defines the BabylonJS internal texture
  89159. * @param createPolynomials will be true if polynomials have been requested
  89160. * @param onLoad defines the callback to trigger once the texture is ready
  89161. * @param onError defines the callback to trigger in case of error
  89162. */
  89163. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  89164. var engine = texture.getEngine();
  89165. var info;
  89166. var loadMipmap = false;
  89167. if (Array.isArray(imgs)) {
  89168. for (var index = 0; index < imgs.length; index++) {
  89169. var data_1 = imgs[index];
  89170. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  89171. texture.width = info.width;
  89172. texture.height = info.height;
  89173. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  89174. engine._unpackFlipY(info.isCompressed);
  89175. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  89176. if (!info.isFourCC && info.mipmapCount === 1) {
  89177. engine.generateMipMapsForCubemap(texture);
  89178. }
  89179. }
  89180. }
  89181. else {
  89182. var data = imgs;
  89183. info = BABYLON.DDSTools.GetDDSInfo(data);
  89184. texture.width = info.width;
  89185. texture.height = info.height;
  89186. if (createPolynomials) {
  89187. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  89188. }
  89189. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  89190. engine._unpackFlipY(info.isCompressed);
  89191. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  89192. if (!info.isFourCC && info.mipmapCount === 1) {
  89193. engine.generateMipMapsForCubemap(texture);
  89194. }
  89195. }
  89196. engine._setCubeMapTextureParams(loadMipmap);
  89197. texture.isReady = true;
  89198. if (onLoad) {
  89199. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  89200. }
  89201. };
  89202. /**
  89203. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  89204. * @param data contains the texture data
  89205. * @param texture defines the BabylonJS internal texture
  89206. * @param callback defines the method to call once ready to upload
  89207. */
  89208. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  89209. var info = BABYLON.DDSTools.GetDDSInfo(data);
  89210. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  89211. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  89212. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  89213. });
  89214. };
  89215. return DDSTextureLoader;
  89216. }());
  89217. // Register the loader.
  89218. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  89219. })(BABYLON || (BABYLON = {}));
  89220. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  89221. var BABYLON;
  89222. (function (BABYLON) {
  89223. /*
  89224. * Based on jsTGALoader - Javascript loader for TGA file
  89225. * By Vincent Thibault
  89226. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  89227. */
  89228. var TGATools = /** @class */ (function () {
  89229. function TGATools() {
  89230. }
  89231. TGATools.GetTGAHeader = function (data) {
  89232. var offset = 0;
  89233. var header = {
  89234. id_length: data[offset++],
  89235. colormap_type: data[offset++],
  89236. image_type: data[offset++],
  89237. colormap_index: data[offset++] | data[offset++] << 8,
  89238. colormap_length: data[offset++] | data[offset++] << 8,
  89239. colormap_size: data[offset++],
  89240. origin: [
  89241. data[offset++] | data[offset++] << 8,
  89242. data[offset++] | data[offset++] << 8
  89243. ],
  89244. width: data[offset++] | data[offset++] << 8,
  89245. height: data[offset++] | data[offset++] << 8,
  89246. pixel_size: data[offset++],
  89247. flags: data[offset++]
  89248. };
  89249. return header;
  89250. };
  89251. /**
  89252. * Uploads TGA content to a Babylon Texture
  89253. * @hidden
  89254. */
  89255. TGATools.UploadContent = function (texture, data) {
  89256. // Not enough data to contain header ?
  89257. if (data.length < 19) {
  89258. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  89259. return;
  89260. }
  89261. // Read Header
  89262. var offset = 18;
  89263. var header = TGATools.GetTGAHeader(data);
  89264. // Assume it's a valid Targa file.
  89265. if (header.id_length + offset > data.length) {
  89266. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  89267. return;
  89268. }
  89269. // Skip not needed data
  89270. offset += header.id_length;
  89271. var use_rle = false;
  89272. var use_pal = false;
  89273. var use_grey = false;
  89274. // Get some informations.
  89275. switch (header.image_type) {
  89276. case TGATools._TYPE_RLE_INDEXED:
  89277. use_rle = true;
  89278. case TGATools._TYPE_INDEXED:
  89279. use_pal = true;
  89280. break;
  89281. case TGATools._TYPE_RLE_RGB:
  89282. use_rle = true;
  89283. case TGATools._TYPE_RGB:
  89284. // use_rgb = true;
  89285. break;
  89286. case TGATools._TYPE_RLE_GREY:
  89287. use_rle = true;
  89288. case TGATools._TYPE_GREY:
  89289. use_grey = true;
  89290. break;
  89291. }
  89292. var pixel_data;
  89293. // var numAlphaBits = header.flags & 0xf;
  89294. var pixel_size = header.pixel_size >> 3;
  89295. var pixel_total = header.width * header.height * pixel_size;
  89296. // Read palettes
  89297. var palettes;
  89298. if (use_pal) {
  89299. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  89300. }
  89301. // Read LRE
  89302. if (use_rle) {
  89303. pixel_data = new Uint8Array(pixel_total);
  89304. var c, count, i;
  89305. var localOffset = 0;
  89306. var pixels = new Uint8Array(pixel_size);
  89307. while (offset < pixel_total && localOffset < pixel_total) {
  89308. c = data[offset++];
  89309. count = (c & 0x7f) + 1;
  89310. // RLE pixels
  89311. if (c & 0x80) {
  89312. // Bind pixel tmp array
  89313. for (i = 0; i < pixel_size; ++i) {
  89314. pixels[i] = data[offset++];
  89315. }
  89316. // Copy pixel array
  89317. for (i = 0; i < count; ++i) {
  89318. pixel_data.set(pixels, localOffset + i * pixel_size);
  89319. }
  89320. localOffset += pixel_size * count;
  89321. }
  89322. // Raw pixels
  89323. else {
  89324. count *= pixel_size;
  89325. for (i = 0; i < count; ++i) {
  89326. pixel_data[localOffset + i] = data[offset++];
  89327. }
  89328. localOffset += count;
  89329. }
  89330. }
  89331. }
  89332. // RAW Pixels
  89333. else {
  89334. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  89335. }
  89336. // Load to texture
  89337. var x_start, y_start, x_step, y_step, y_end, x_end;
  89338. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  89339. default:
  89340. case TGATools._ORIGIN_UL:
  89341. x_start = 0;
  89342. x_step = 1;
  89343. x_end = header.width;
  89344. y_start = 0;
  89345. y_step = 1;
  89346. y_end = header.height;
  89347. break;
  89348. case TGATools._ORIGIN_BL:
  89349. x_start = 0;
  89350. x_step = 1;
  89351. x_end = header.width;
  89352. y_start = header.height - 1;
  89353. y_step = -1;
  89354. y_end = -1;
  89355. break;
  89356. case TGATools._ORIGIN_UR:
  89357. x_start = header.width - 1;
  89358. x_step = -1;
  89359. x_end = -1;
  89360. y_start = 0;
  89361. y_step = 1;
  89362. y_end = header.height;
  89363. break;
  89364. case TGATools._ORIGIN_BR:
  89365. x_start = header.width - 1;
  89366. x_step = -1;
  89367. x_end = -1;
  89368. y_start = header.height - 1;
  89369. y_step = -1;
  89370. y_end = -1;
  89371. break;
  89372. }
  89373. // Load the specify method
  89374. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  89375. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  89376. var engine = texture.getEngine();
  89377. engine._uploadDataToTextureDirectly(texture, imageData);
  89378. };
  89379. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  89380. var image = pixel_data, colormap = palettes;
  89381. var width = header.width, height = header.height;
  89382. var color, i = 0, x, y;
  89383. var imageData = new Uint8Array(width * height * 4);
  89384. for (y = y_start; y !== y_end; y += y_step) {
  89385. for (x = x_start; x !== x_end; x += x_step, i++) {
  89386. color = image[i];
  89387. imageData[(x + width * y) * 4 + 3] = 255;
  89388. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  89389. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  89390. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  89391. }
  89392. }
  89393. return imageData;
  89394. };
  89395. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  89396. var image = pixel_data;
  89397. var width = header.width, height = header.height;
  89398. var color, i = 0, x, y;
  89399. var imageData = new Uint8Array(width * height * 4);
  89400. for (y = y_start; y !== y_end; y += y_step) {
  89401. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  89402. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  89403. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  89404. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  89405. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  89406. imageData[(x + width * y) * 4 + 0] = r;
  89407. imageData[(x + width * y) * 4 + 1] = g;
  89408. imageData[(x + width * y) * 4 + 2] = b;
  89409. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  89410. }
  89411. }
  89412. return imageData;
  89413. };
  89414. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  89415. var image = pixel_data;
  89416. var width = header.width, height = header.height;
  89417. var i = 0, x, y;
  89418. var imageData = new Uint8Array(width * height * 4);
  89419. for (y = y_start; y !== y_end; y += y_step) {
  89420. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  89421. imageData[(x + width * y) * 4 + 3] = 255;
  89422. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  89423. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  89424. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  89425. }
  89426. }
  89427. return imageData;
  89428. };
  89429. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  89430. var image = pixel_data;
  89431. var width = header.width, height = header.height;
  89432. var i = 0, x, y;
  89433. var imageData = new Uint8Array(width * height * 4);
  89434. for (y = y_start; y !== y_end; y += y_step) {
  89435. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  89436. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  89437. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  89438. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  89439. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  89440. }
  89441. }
  89442. return imageData;
  89443. };
  89444. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  89445. var image = pixel_data;
  89446. var width = header.width, height = header.height;
  89447. var color, i = 0, x, y;
  89448. var imageData = new Uint8Array(width * height * 4);
  89449. for (y = y_start; y !== y_end; y += y_step) {
  89450. for (x = x_start; x !== x_end; x += x_step, i++) {
  89451. color = image[i];
  89452. imageData[(x + width * y) * 4 + 0] = color;
  89453. imageData[(x + width * y) * 4 + 1] = color;
  89454. imageData[(x + width * y) * 4 + 2] = color;
  89455. imageData[(x + width * y) * 4 + 3] = 255;
  89456. }
  89457. }
  89458. return imageData;
  89459. };
  89460. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  89461. var image = pixel_data;
  89462. var width = header.width, height = header.height;
  89463. var i = 0, x, y;
  89464. var imageData = new Uint8Array(width * height * 4);
  89465. for (y = y_start; y !== y_end; y += y_step) {
  89466. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  89467. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  89468. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  89469. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  89470. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  89471. }
  89472. }
  89473. return imageData;
  89474. };
  89475. //private static _TYPE_NO_DATA = 0;
  89476. TGATools._TYPE_INDEXED = 1;
  89477. TGATools._TYPE_RGB = 2;
  89478. TGATools._TYPE_GREY = 3;
  89479. TGATools._TYPE_RLE_INDEXED = 9;
  89480. TGATools._TYPE_RLE_RGB = 10;
  89481. TGATools._TYPE_RLE_GREY = 11;
  89482. TGATools._ORIGIN_MASK = 0x30;
  89483. TGATools._ORIGIN_SHIFT = 0x04;
  89484. TGATools._ORIGIN_BL = 0x00;
  89485. TGATools._ORIGIN_BR = 0x01;
  89486. TGATools._ORIGIN_UL = 0x02;
  89487. TGATools._ORIGIN_UR = 0x03;
  89488. return TGATools;
  89489. }());
  89490. BABYLON.TGATools = TGATools;
  89491. })(BABYLON || (BABYLON = {}));
  89492. //# sourceMappingURL=babylon.tga.js.map
  89493. var BABYLON;
  89494. (function (BABYLON) {
  89495. /**
  89496. * Implementation of the TGA Texture Loader.
  89497. */
  89498. var TGATextureLoader = /** @class */ (function () {
  89499. function TGATextureLoader() {
  89500. /**
  89501. * Defines wether the loader supports cascade loading the different faces.
  89502. */
  89503. this.supportCascades = false;
  89504. }
  89505. /**
  89506. * This returns if the loader support the current file information.
  89507. * @param extension defines the file extension of the file being loaded
  89508. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89509. * @param fallback defines the fallback internal texture if any
  89510. * @param isBase64 defines whether the texture is encoded as a base64
  89511. * @param isBuffer defines whether the texture data are stored as a buffer
  89512. * @returns true if the loader can load the specified file
  89513. */
  89514. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  89515. return extension.indexOf(".tga") === 0;
  89516. };
  89517. /**
  89518. * Transform the url before loading if required.
  89519. * @param rootUrl the url of the texture
  89520. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89521. * @returns the transformed texture
  89522. */
  89523. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  89524. return rootUrl;
  89525. };
  89526. /**
  89527. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  89528. * @param rootUrl the url of the texture
  89529. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89530. * @returns the fallback texture
  89531. */
  89532. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  89533. return null;
  89534. };
  89535. /**
  89536. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  89537. * @param data contains the texture data
  89538. * @param texture defines the BabylonJS internal texture
  89539. * @param createPolynomials will be true if polynomials have been requested
  89540. * @param onLoad defines the callback to trigger once the texture is ready
  89541. * @param onError defines the callback to trigger in case of error
  89542. */
  89543. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  89544. throw ".env not supported in Cube.";
  89545. };
  89546. /**
  89547. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  89548. * @param data contains the texture data
  89549. * @param texture defines the BabylonJS internal texture
  89550. * @param callback defines the method to call once ready to upload
  89551. */
  89552. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  89553. var uintData = new Uint8Array(data);
  89554. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  89555. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  89556. BABYLON.TGATools.UploadContent(texture, uintData);
  89557. });
  89558. };
  89559. return TGATextureLoader;
  89560. }());
  89561. // Register the loader.
  89562. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  89563. })(BABYLON || (BABYLON = {}));
  89564. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  89565. var BABYLON;
  89566. (function (BABYLON) {
  89567. /**
  89568. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  89569. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  89570. */
  89571. var KhronosTextureContainer = /** @class */ (function () {
  89572. /**
  89573. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  89574. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  89575. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  89576. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  89577. */
  89578. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  89579. this.arrayBuffer = arrayBuffer;
  89580. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  89581. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  89582. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  89583. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  89584. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  89585. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  89586. BABYLON.Tools.Error("texture missing KTX identifier");
  89587. return;
  89588. }
  89589. // load the reset of the header in native 32 bit int
  89590. var header = new Int32Array(this.arrayBuffer, 12, 13);
  89591. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  89592. var oppositeEndianess = header[0] === 0x01020304;
  89593. // read all the header elements in order they exist in the file, without modification (sans endainness)
  89594. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  89595. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  89596. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  89597. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  89598. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  89599. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  89600. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  89601. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  89602. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  89603. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  89604. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  89605. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  89606. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  89607. if (this.glType !== 0) {
  89608. BABYLON.Tools.Error("only compressed formats currently supported");
  89609. return;
  89610. }
  89611. else {
  89612. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  89613. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  89614. }
  89615. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  89616. BABYLON.Tools.Error("only 2D textures currently supported");
  89617. return;
  89618. }
  89619. if (this.numberOfArrayElements !== 0) {
  89620. BABYLON.Tools.Error("texture arrays not currently supported");
  89621. return;
  89622. }
  89623. if (this.numberOfFaces !== facesExpected) {
  89624. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  89625. return;
  89626. }
  89627. // we now have a completely validated file, so could use existence of loadType as success
  89628. // would need to make this more elaborate & adjust checks above to support more than one load type
  89629. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  89630. }
  89631. // not as fast hardware based, but will probably never need to use
  89632. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  89633. return ((val & 0xFF) << 24)
  89634. | ((val & 0xFF00) << 8)
  89635. | ((val >> 8) & 0xFF00)
  89636. | ((val >> 24) & 0xFF);
  89637. };
  89638. /**
  89639. * Uploads KTX content to a Babylon Texture.
  89640. * It is assumed that the texture has already been created & is currently bound
  89641. * @hidden
  89642. */
  89643. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  89644. switch (this.loadType) {
  89645. case KhronosTextureContainer.COMPRESSED_2D:
  89646. this._upload2DCompressedLevels(texture, loadMipmaps);
  89647. break;
  89648. case KhronosTextureContainer.TEX_2D:
  89649. case KhronosTextureContainer.COMPRESSED_3D:
  89650. case KhronosTextureContainer.TEX_3D:
  89651. }
  89652. };
  89653. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  89654. // initialize width & height for level 1
  89655. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  89656. var width = this.pixelWidth;
  89657. var height = this.pixelHeight;
  89658. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  89659. for (var level = 0; level < mipmapCount; level++) {
  89660. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  89661. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  89662. for (var face = 0; face < this.numberOfFaces; face++) {
  89663. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  89664. var engine = texture.getEngine();
  89665. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  89666. dataOffset += imageSize; // add size of the image for the next face/mipmap
  89667. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  89668. }
  89669. width = Math.max(1.0, width * 0.5);
  89670. height = Math.max(1.0, height * 0.5);
  89671. }
  89672. };
  89673. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  89674. // load types
  89675. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  89676. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  89677. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  89678. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  89679. return KhronosTextureContainer;
  89680. }());
  89681. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  89682. })(BABYLON || (BABYLON = {}));
  89683. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  89684. var BABYLON;
  89685. (function (BABYLON) {
  89686. /**
  89687. * Implementation of the KTX Texture Loader.
  89688. */
  89689. var KTXTextureLoader = /** @class */ (function () {
  89690. function KTXTextureLoader() {
  89691. /**
  89692. * Defines wether the loader supports cascade loading the different faces.
  89693. */
  89694. this.supportCascades = false;
  89695. }
  89696. /**
  89697. * This returns if the loader support the current file information.
  89698. * @param extension defines the file extension of the file being loaded
  89699. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89700. * @param fallback defines the fallback internal texture if any
  89701. * @param isBase64 defines whether the texture is encoded as a base64
  89702. * @param isBuffer defines whether the texture data are stored as a buffer
  89703. * @returns true if the loader can load the specified file
  89704. */
  89705. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  89706. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  89707. return true;
  89708. }
  89709. return false;
  89710. };
  89711. /**
  89712. * Transform the url before loading if required.
  89713. * @param rootUrl the url of the texture
  89714. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89715. * @returns the transformed texture
  89716. */
  89717. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  89718. var lastDot = rootUrl.lastIndexOf('.');
  89719. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  89720. };
  89721. /**
  89722. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  89723. * @param rootUrl the url of the texture
  89724. * @param textureFormatInUse defines the current compressed format in use iun the engine
  89725. * @returns the fallback texture
  89726. */
  89727. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  89728. // remove the format appended to the rootUrl in the original createCubeTexture call.
  89729. var exp = new RegExp("" + textureFormatInUse + "$");
  89730. return rootUrl.replace(exp, "");
  89731. };
  89732. /**
  89733. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  89734. * @param data contains the texture data
  89735. * @param texture defines the BabylonJS internal texture
  89736. * @param createPolynomials will be true if polynomials have been requested
  89737. * @param onLoad defines the callback to trigger once the texture is ready
  89738. * @param onError defines the callback to trigger in case of error
  89739. */
  89740. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  89741. if (Array.isArray(data)) {
  89742. return;
  89743. }
  89744. var engine = texture.getEngine();
  89745. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  89746. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  89747. engine._unpackFlipY(true);
  89748. ktx.uploadLevels(texture, texture.generateMipMaps);
  89749. texture.width = ktx.pixelWidth;
  89750. texture.height = ktx.pixelHeight;
  89751. engine._setCubeMapTextureParams(loadMipmap);
  89752. texture.isReady = true;
  89753. };
  89754. /**
  89755. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  89756. * @param data contains the texture data
  89757. * @param texture defines the BabylonJS internal texture
  89758. * @param callback defines the method to call once ready to upload
  89759. */
  89760. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  89761. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  89762. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  89763. ktx.uploadLevels(texture, texture.generateMipMaps);
  89764. });
  89765. };
  89766. return KTXTextureLoader;
  89767. }());
  89768. // Register the loader.
  89769. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  89770. })(BABYLON || (BABYLON = {}));
  89771. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  89772. var BABYLON;
  89773. (function (BABYLON) {
  89774. /**
  89775. * Sets of helpers addressing the serialization and deserialization of environment texture
  89776. * stored in a BabylonJS env file.
  89777. * Those files are usually stored as .env files.
  89778. */
  89779. var EnvironmentTextureTools = /** @class */ (function () {
  89780. function EnvironmentTextureTools() {
  89781. }
  89782. /**
  89783. * Gets the environment info from an env file.
  89784. * @param data The array buffer containing the .env bytes.
  89785. * @returns the environment file info (the json header) if successfully parsed.
  89786. */
  89787. EnvironmentTextureTools.GetEnvInfo = function (data) {
  89788. var dataView = new DataView(data);
  89789. var pos = 0;
  89790. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  89791. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  89792. BABYLON.Tools.Error('Not a babylon environment map');
  89793. return null;
  89794. }
  89795. }
  89796. // Read json manifest - collect characters up to null terminator
  89797. var manifestString = '';
  89798. var charCode = 0x00;
  89799. while ((charCode = dataView.getUint8(pos++))) {
  89800. manifestString += String.fromCharCode(charCode);
  89801. }
  89802. var manifest = JSON.parse(manifestString);
  89803. if (manifest.specular) {
  89804. // Extend the header with the position of the payload.
  89805. manifest.specular.specularDataPosition = pos;
  89806. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  89807. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  89808. }
  89809. return manifest;
  89810. };
  89811. /**
  89812. * Creates an environment texture from a loaded cube texture.
  89813. * @param texture defines the cube texture to convert in env file
  89814. * @return a promise containing the environment data if succesfull.
  89815. */
  89816. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  89817. var _this = this;
  89818. var internalTexture = texture.getInternalTexture();
  89819. if (!internalTexture) {
  89820. return Promise.reject("The cube texture is invalid.");
  89821. }
  89822. if (!texture._prefiltered) {
  89823. return Promise.reject("The cube texture is invalid (not prefiltered).");
  89824. }
  89825. var engine = internalTexture.getEngine();
  89826. if (engine && engine.premultipliedAlpha) {
  89827. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  89828. }
  89829. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  89830. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  89831. }
  89832. var canvas = engine.getRenderingCanvas();
  89833. if (!canvas) {
  89834. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  89835. }
  89836. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  89837. if (!engine.getCaps().textureFloatRender) {
  89838. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  89839. if (!engine.getCaps().textureHalfFloatRender) {
  89840. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  89841. }
  89842. }
  89843. var cubeWidth = internalTexture.width;
  89844. var hostingScene = new BABYLON.Scene(engine);
  89845. var specularTextures = {};
  89846. var promises = [];
  89847. // Read and collect all mipmaps data from the cube.
  89848. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  89849. mipmapsCount = Math.round(mipmapsCount);
  89850. var _loop_1 = function (i) {
  89851. var faceWidth = Math.pow(2, mipmapsCount - i);
  89852. var _loop_2 = function (face) {
  89853. var data = texture.readPixels(face, i);
  89854. // Creates a temp texture with the face data.
  89855. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  89856. // And rgbdEncode them.
  89857. var promise = new Promise(function (resolve, reject) {
  89858. 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);
  89859. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  89860. rgbdPostProcess.onApply = function (effect) {
  89861. effect._bindTexture("textureSampler", tempTexture);
  89862. };
  89863. // As the process needs to happen on the main canvas, keep track of the current size
  89864. var currentW = engine.getRenderWidth();
  89865. var currentH = engine.getRenderHeight();
  89866. // Set the desired size for the texture
  89867. engine.setSize(faceWidth, faceWidth);
  89868. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  89869. // Reading datas from WebGL
  89870. BABYLON.Tools.ToBlob(canvas, function (blob) {
  89871. var fileReader = new FileReader();
  89872. fileReader.onload = function (event) {
  89873. var arrayBuffer = event.target.result;
  89874. specularTextures[i * 6 + face] = arrayBuffer;
  89875. resolve();
  89876. };
  89877. fileReader.readAsArrayBuffer(blob);
  89878. });
  89879. // Reapply the previous canvas size
  89880. engine.setSize(currentW, currentH);
  89881. });
  89882. });
  89883. promises.push(promise);
  89884. };
  89885. // All faces of the cube.
  89886. for (var face = 0; face < 6; face++) {
  89887. _loop_2(face);
  89888. }
  89889. };
  89890. for (var i = 0; i <= mipmapsCount; i++) {
  89891. _loop_1(i);
  89892. }
  89893. // Once all the textures haves been collected as RGBD stored in PNGs
  89894. return Promise.all(promises).then(function () {
  89895. // We can delete the hosting scene keeping track of all the creation objects
  89896. hostingScene.dispose();
  89897. // Creates the json header for the env texture
  89898. var info = {
  89899. version: 1,
  89900. width: cubeWidth,
  89901. irradiance: _this._CreateEnvTextureIrradiance(texture),
  89902. specular: {
  89903. mipmaps: [],
  89904. lodGenerationScale: texture.lodGenerationScale
  89905. }
  89906. };
  89907. // Sets the specular image data information
  89908. var position = 0;
  89909. for (var i = 0; i <= mipmapsCount; i++) {
  89910. for (var face = 0; face < 6; face++) {
  89911. var byteLength = specularTextures[i * 6 + face].byteLength;
  89912. info.specular.mipmaps.push({
  89913. length: byteLength,
  89914. position: position
  89915. });
  89916. position += byteLength;
  89917. }
  89918. }
  89919. // Encode the JSON as an array buffer
  89920. var infoString = JSON.stringify(info);
  89921. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  89922. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  89923. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  89924. infoView[i] = infoString.charCodeAt(i);
  89925. }
  89926. // Ends up with a null terminator for easier parsing
  89927. infoView[infoString.length] = 0x00;
  89928. // Computes the final required size and creates the storage
  89929. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  89930. var finalBuffer = new ArrayBuffer(totalSize);
  89931. var finalBufferView = new Uint8Array(finalBuffer);
  89932. var dataView = new DataView(finalBuffer);
  89933. // Copy the magic bytes identifying the file in
  89934. var pos = 0;
  89935. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  89936. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  89937. }
  89938. // Add the json info
  89939. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  89940. pos += infoBuffer.byteLength;
  89941. // Finally inserts the texture data
  89942. for (var i = 0; i <= mipmapsCount; i++) {
  89943. for (var face = 0; face < 6; face++) {
  89944. var dataBuffer = specularTextures[i * 6 + face];
  89945. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  89946. pos += dataBuffer.byteLength;
  89947. }
  89948. }
  89949. // Voila
  89950. return finalBuffer;
  89951. });
  89952. };
  89953. /**
  89954. * Creates a JSON representation of the spherical data.
  89955. * @param texture defines the texture containing the polynomials
  89956. * @return the JSON representation of the spherical info
  89957. */
  89958. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  89959. var polynmials = texture.sphericalPolynomial;
  89960. if (polynmials == null) {
  89961. return null;
  89962. }
  89963. return {
  89964. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  89965. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  89966. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  89967. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  89968. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  89969. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  89970. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  89971. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  89972. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  89973. };
  89974. };
  89975. /**
  89976. * Uploads the texture info contained in the env file to the GPU.
  89977. * @param texture defines the internal texture to upload to
  89978. * @param arrayBuffer defines the buffer cotaining the data to load
  89979. * @param info defines the texture info retrieved through the GetEnvInfo method
  89980. * @returns a promise
  89981. */
  89982. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  89983. if (info.version !== 1) {
  89984. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  89985. }
  89986. var specularInfo = info.specular;
  89987. if (!specularInfo) {
  89988. // Nothing else parsed so far
  89989. return Promise.resolve();
  89990. }
  89991. // Double checks the enclosed info
  89992. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  89993. mipmapsCount = Math.round(mipmapsCount) + 1;
  89994. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  89995. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  89996. }
  89997. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  89998. var imageData = new Array(mipmapsCount);
  89999. for (var i = 0; i < mipmapsCount; i++) {
  90000. imageData[i] = new Array(6);
  90001. for (var face = 0; face < 6; face++) {
  90002. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  90003. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  90004. }
  90005. }
  90006. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  90007. };
  90008. /**
  90009. * Uploads the levels of image data to the GPU.
  90010. * @param texture defines the internal texture to upload to
  90011. * @param imageData defines the array buffer views of image data [mipmap][face]
  90012. * @returns a promise
  90013. */
  90014. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  90015. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  90016. throw new Error("Texture size must be a power of two");
  90017. }
  90018. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  90019. // Gets everything ready.
  90020. var engine = texture.getEngine();
  90021. var expandTexture = false;
  90022. var generateNonLODTextures = false;
  90023. var rgbdPostProcess = null;
  90024. var cubeRtt = null;
  90025. var lodTextures = null;
  90026. var caps = engine.getCaps();
  90027. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  90028. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  90029. texture.generateMipMaps = true;
  90030. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  90031. // Add extra process if texture lod is not supported
  90032. if (!caps.textureLOD) {
  90033. expandTexture = false;
  90034. generateNonLODTextures = true;
  90035. lodTextures = {};
  90036. }
  90037. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  90038. else if (engine.webGLVersion < 2) {
  90039. expandTexture = false;
  90040. }
  90041. // If half float available we can uncompress the texture
  90042. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  90043. expandTexture = true;
  90044. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  90045. }
  90046. // If full float available we can uncompress the texture
  90047. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  90048. expandTexture = true;
  90049. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  90050. }
  90051. // Expand the texture if possible
  90052. if (expandTexture) {
  90053. // Simply run through the decode PP
  90054. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  90055. texture._isRGBD = false;
  90056. texture.invertY = false;
  90057. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  90058. generateDepthBuffer: false,
  90059. generateMipMaps: true,
  90060. generateStencilBuffer: false,
  90061. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  90062. type: texture.type,
  90063. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  90064. });
  90065. }
  90066. else {
  90067. texture._isRGBD = true;
  90068. texture.invertY = true;
  90069. // In case of missing support, applies the same patch than DDS files.
  90070. if (generateNonLODTextures) {
  90071. var mipSlices = 3;
  90072. var scale = texture._lodGenerationScale;
  90073. var offset = texture._lodGenerationOffset;
  90074. for (var i = 0; i < mipSlices; i++) {
  90075. //compute LOD from even spacing in smoothness (matching shader calculation)
  90076. var smoothness = i / (mipSlices - 1);
  90077. var roughness = 1 - smoothness;
  90078. var minLODIndex = offset; // roughness = 0
  90079. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  90080. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  90081. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  90082. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  90083. glTextureFromLod.isCube = true;
  90084. glTextureFromLod.invertY = true;
  90085. glTextureFromLod.generateMipMaps = false;
  90086. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  90087. // Wrap in a base texture for easy binding.
  90088. var lodTexture = new BABYLON.BaseTexture(null);
  90089. lodTexture.isCube = true;
  90090. lodTexture._texture = glTextureFromLod;
  90091. lodTextures[mipmapIndex] = lodTexture;
  90092. switch (i) {
  90093. case 0:
  90094. texture._lodTextureLow = lodTexture;
  90095. break;
  90096. case 1:
  90097. texture._lodTextureMid = lodTexture;
  90098. break;
  90099. case 2:
  90100. texture._lodTextureHigh = lodTexture;
  90101. break;
  90102. }
  90103. }
  90104. }
  90105. }
  90106. var promises = [];
  90107. var _loop_3 = function (i) {
  90108. var _loop_4 = function (face) {
  90109. // Constructs an image element from image data
  90110. var bytes = imageData[i][face];
  90111. var blob = new Blob([bytes], { type: 'image/png' });
  90112. var url = URL.createObjectURL(blob);
  90113. var image = new Image();
  90114. image.src = url;
  90115. // Enqueue promise to upload to the texture.
  90116. var promise = new Promise(function (resolve, reject) {
  90117. image.onload = function () {
  90118. if (expandTexture) {
  90119. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  90120. reject(message);
  90121. }, image);
  90122. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  90123. // Uncompress the data to a RTT
  90124. rgbdPostProcess.onApply = function (effect) {
  90125. effect._bindTexture("textureSampler", tempTexture_1);
  90126. effect.setFloat2("scale", 1, 1);
  90127. };
  90128. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  90129. // Cleanup
  90130. engine.restoreDefaultFramebuffer();
  90131. tempTexture_1.dispose();
  90132. window.URL.revokeObjectURL(url);
  90133. resolve();
  90134. });
  90135. }
  90136. else {
  90137. engine._uploadImageToTexture(texture, image, face, i);
  90138. // Upload the face to the non lod texture support
  90139. if (generateNonLODTextures) {
  90140. var lodTexture = lodTextures[i];
  90141. if (lodTexture) {
  90142. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  90143. }
  90144. }
  90145. resolve();
  90146. }
  90147. };
  90148. image.onerror = function (error) {
  90149. reject(error);
  90150. };
  90151. });
  90152. promises.push(promise);
  90153. };
  90154. // All faces
  90155. for (var face = 0; face < 6; face++) {
  90156. _loop_4(face);
  90157. }
  90158. };
  90159. // All mipmaps up to provided number of images
  90160. for (var i = 0; i < imageData.length; i++) {
  90161. _loop_3(i);
  90162. }
  90163. // Fill remaining mipmaps with black textures.
  90164. if (imageData.length < mipmapsCount) {
  90165. var data = void 0;
  90166. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  90167. var dataLength = size * size * 4;
  90168. switch (texture.type) {
  90169. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  90170. data = new Uint8Array(dataLength);
  90171. break;
  90172. }
  90173. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  90174. data = new Uint16Array(dataLength);
  90175. break;
  90176. }
  90177. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  90178. data = new Float32Array(dataLength);
  90179. break;
  90180. }
  90181. }
  90182. for (var i = imageData.length; i < mipmapsCount; i++) {
  90183. for (var face = 0; face < 6; face++) {
  90184. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  90185. }
  90186. }
  90187. }
  90188. // Once all done, finishes the cleanup and return
  90189. return Promise.all(promises).then(function () {
  90190. // Release temp RTT.
  90191. if (cubeRtt) {
  90192. engine._releaseFramebufferObjects(cubeRtt);
  90193. cubeRtt._swapAndDie(texture);
  90194. }
  90195. // Release temp Post Process.
  90196. if (rgbdPostProcess) {
  90197. rgbdPostProcess.dispose();
  90198. }
  90199. // Flag internal texture as ready in case they are in use.
  90200. if (generateNonLODTextures) {
  90201. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  90202. texture._lodTextureHigh._texture.isReady = true;
  90203. }
  90204. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  90205. texture._lodTextureMid._texture.isReady = true;
  90206. }
  90207. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  90208. texture._lodTextureLow._texture.isReady = true;
  90209. }
  90210. }
  90211. });
  90212. };
  90213. /**
  90214. * Uploads spherical polynomials information to the texture.
  90215. * @param texture defines the texture we are trying to upload the information to
  90216. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  90217. */
  90218. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  90219. if (info.version !== 1) {
  90220. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  90221. }
  90222. var irradianceInfo = info.irradiance;
  90223. if (!irradianceInfo) {
  90224. return;
  90225. }
  90226. var sp = new BABYLON.SphericalPolynomial();
  90227. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  90228. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  90229. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  90230. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  90231. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  90232. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  90233. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  90234. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  90235. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  90236. texture._sphericalPolynomial = sp;
  90237. };
  90238. /**
  90239. * Magic number identifying the env file.
  90240. */
  90241. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  90242. return EnvironmentTextureTools;
  90243. }());
  90244. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  90245. })(BABYLON || (BABYLON = {}));
  90246. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  90247. var BABYLON;
  90248. (function (BABYLON) {
  90249. /**
  90250. * Implementation of the ENV Texture Loader.
  90251. */
  90252. var ENVTextureLoader = /** @class */ (function () {
  90253. function ENVTextureLoader() {
  90254. /**
  90255. * Defines wether the loader supports cascade loading the different faces.
  90256. */
  90257. this.supportCascades = false;
  90258. }
  90259. /**
  90260. * This returns if the loader support the current file information.
  90261. * @param extension defines the file extension of the file being loaded
  90262. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90263. * @param fallback defines the fallback internal texture if any
  90264. * @param isBase64 defines whether the texture is encoded as a base64
  90265. * @param isBuffer defines whether the texture data are stored as a buffer
  90266. * @returns true if the loader can load the specified file
  90267. */
  90268. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  90269. return extension.indexOf(".env") === 0;
  90270. };
  90271. /**
  90272. * Transform the url before loading if required.
  90273. * @param rootUrl the url of the texture
  90274. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90275. * @returns the transformed texture
  90276. */
  90277. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  90278. return rootUrl;
  90279. };
  90280. /**
  90281. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  90282. * @param rootUrl the url of the texture
  90283. * @param textureFormatInUse defines the current compressed format in use iun the engine
  90284. * @returns the fallback texture
  90285. */
  90286. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  90287. return null;
  90288. };
  90289. /**
  90290. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  90291. * @param data contains the texture data
  90292. * @param texture defines the BabylonJS internal texture
  90293. * @param createPolynomials will be true if polynomials have been requested
  90294. * @param onLoad defines the callback to trigger once the texture is ready
  90295. * @param onError defines the callback to trigger in case of error
  90296. */
  90297. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  90298. if (Array.isArray(data)) {
  90299. return;
  90300. }
  90301. data = data;
  90302. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  90303. if (info) {
  90304. texture.width = info.width;
  90305. texture.height = info.width;
  90306. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  90307. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  90308. texture.isReady = true;
  90309. if (onLoad) {
  90310. onLoad();
  90311. }
  90312. });
  90313. }
  90314. else if (onError) {
  90315. onError("Can not parse the environment file", null);
  90316. }
  90317. };
  90318. /**
  90319. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  90320. * @param data contains the texture data
  90321. * @param texture defines the BabylonJS internal texture
  90322. * @param callback defines the method to call once ready to upload
  90323. */
  90324. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  90325. throw ".env not supported in 2d.";
  90326. };
  90327. return ENVTextureLoader;
  90328. }());
  90329. // Register the loader.
  90330. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  90331. })(BABYLON || (BABYLON = {}));
  90332. //# sourceMappingURL=babylon.envTextureLoader.js.map
  90333. var BABYLON;
  90334. (function (BABYLON) {
  90335. /**
  90336. * Renders a layer on top of an existing scene
  90337. */
  90338. var UtilityLayerRenderer = /** @class */ (function () {
  90339. /**
  90340. * Instantiates a UtilityLayerRenderer
  90341. * @param originalScene the original scene that will be rendered on top of
  90342. */
  90343. function UtilityLayerRenderer(
  90344. /** the original scene that will be rendered on top of */
  90345. originalScene) {
  90346. var _this = this;
  90347. this.originalScene = originalScene;
  90348. this._pointerCaptures = {};
  90349. this._lastPointerEvents = {};
  90350. /**
  90351. * If the utility layer should automatically be rendered on top of existing scene
  90352. */
  90353. this.shouldRender = true;
  90354. /**
  90355. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  90356. */
  90357. this.onlyCheckPointerDownEvents = true;
  90358. /**
  90359. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  90360. */
  90361. this.processAllEvents = false;
  90362. /**
  90363. * Observable raised when the pointer move from the utility layer scene to the main scene
  90364. */
  90365. this.onPointerOutObservable = new BABYLON.Observable();
  90366. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  90367. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  90368. this.utilityLayerScene._allowPostProcessClear = false;
  90369. originalScene.getEngine().scenes.pop();
  90370. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  90371. this.utilityLayerScene.detachControl();
  90372. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  90373. if (!_this.processAllEvents) {
  90374. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  90375. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  90376. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  90377. return;
  90378. }
  90379. }
  90380. var pointerEvent = (prePointerInfo.event);
  90381. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  90382. _this._pointerCaptures[pointerEvent.pointerId] = false;
  90383. return;
  90384. }
  90385. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  90386. if (!prePointerInfo.ray && utilityScenePick) {
  90387. prePointerInfo.ray = utilityScenePick.ray;
  90388. }
  90389. // always fire the prepointer oversvable
  90390. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  90391. // allow every non pointer down event to flow to the utility layer
  90392. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  90393. if (!prePointerInfo.skipOnPointerObservable) {
  90394. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  90395. }
  90396. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  90397. _this._pointerCaptures[pointerEvent.pointerId] = false;
  90398. }
  90399. return;
  90400. }
  90401. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  90402. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  90403. if (utilityScenePick && utilityScenePick.hit) {
  90404. if (!prePointerInfo.skipOnPointerObservable) {
  90405. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  90406. }
  90407. prePointerInfo.skipOnPointerObservable = true;
  90408. }
  90409. }
  90410. else {
  90411. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  90412. var pointerEvent_1 = (prePointerInfo.event);
  90413. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  90414. if (originalScenePick && utilityScenePick) {
  90415. // No pick in utility scene
  90416. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  90417. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  90418. // We touched an utility mesh present in the main scene
  90419. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  90420. prePointerInfo.skipOnPointerObservable = true;
  90421. }
  90422. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  90423. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  90424. }
  90425. }
  90426. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  90427. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  90428. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  90429. // If a previous utility layer set this, do not unset this
  90430. if (!prePointerInfo.skipOnPointerObservable) {
  90431. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  90432. }
  90433. }
  90434. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  90435. // We have a pick in both scenes but main is closer than utility
  90436. // We touched an utility mesh present in the main scene
  90437. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  90438. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  90439. prePointerInfo.skipOnPointerObservable = true;
  90440. }
  90441. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  90442. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  90443. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  90444. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  90445. }
  90446. }
  90447. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  90448. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  90449. }
  90450. }
  90451. }
  90452. });
  90453. // Render directly on top of existing scene without clearing
  90454. this.utilityLayerScene.autoClear = false;
  90455. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  90456. if (_this.shouldRender) {
  90457. _this.render();
  90458. }
  90459. });
  90460. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  90461. _this.dispose();
  90462. });
  90463. this._updateCamera();
  90464. }
  90465. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  90466. /**
  90467. * 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)
  90468. */
  90469. get: function () {
  90470. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  90471. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  90472. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  90473. UtilityLayerRenderer._DefaultUtilityLayer = null;
  90474. });
  90475. }
  90476. return UtilityLayerRenderer._DefaultUtilityLayer;
  90477. },
  90478. enumerable: true,
  90479. configurable: true
  90480. });
  90481. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  90482. /**
  90483. * 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)
  90484. */
  90485. get: function () {
  90486. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  90487. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  90488. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  90489. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  90490. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  90491. });
  90492. }
  90493. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  90494. },
  90495. enumerable: true,
  90496. configurable: true
  90497. });
  90498. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  90499. if (!prePointerInfo.skipOnPointerObservable) {
  90500. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  90501. this._lastPointerEvents[pointerEvent.pointerId] = parseInt(pointerEvent.pointerType);
  90502. }
  90503. };
  90504. /**
  90505. * Renders the utility layers scene on top of the original scene
  90506. */
  90507. UtilityLayerRenderer.prototype.render = function () {
  90508. this._updateCamera();
  90509. if (this.utilityLayerScene.activeCamera) {
  90510. // Set the camera's scene to utility layers scene
  90511. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  90512. var camera = this.utilityLayerScene.activeCamera;
  90513. camera._scene = this.utilityLayerScene;
  90514. if (camera.leftCamera) {
  90515. camera.leftCamera._scene = this.utilityLayerScene;
  90516. }
  90517. if (camera.rightCamera) {
  90518. camera.rightCamera._scene = this.utilityLayerScene;
  90519. }
  90520. this.utilityLayerScene.render(false);
  90521. // Reset camera's scene back to original
  90522. camera._scene = oldScene;
  90523. if (camera.leftCamera) {
  90524. camera.leftCamera._scene = oldScene;
  90525. }
  90526. if (camera.rightCamera) {
  90527. camera.rightCamera._scene = oldScene;
  90528. }
  90529. }
  90530. };
  90531. /**
  90532. * Disposes of the renderer
  90533. */
  90534. UtilityLayerRenderer.prototype.dispose = function () {
  90535. this.onPointerOutObservable.clear();
  90536. if (this._afterRenderObserver) {
  90537. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  90538. }
  90539. if (this._sceneDisposeObserver) {
  90540. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  90541. }
  90542. if (this._originalPointerObserver) {
  90543. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  90544. }
  90545. this.utilityLayerScene.dispose();
  90546. };
  90547. UtilityLayerRenderer.prototype._updateCamera = function () {
  90548. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  90549. };
  90550. UtilityLayerRenderer._DefaultUtilityLayer = null;
  90551. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  90552. return UtilityLayerRenderer;
  90553. }());
  90554. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  90555. })(BABYLON || (BABYLON = {}));
  90556. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  90557. //# sourceMappingURL=babylon.behavior.js.map
  90558. var BABYLON;
  90559. (function (BABYLON) {
  90560. /**
  90561. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  90562. */
  90563. var PointerDragBehavior = /** @class */ (function () {
  90564. /**
  90565. * Creates a pointer drag behavior that can be attached to a mesh
  90566. * @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)
  90567. */
  90568. function PointerDragBehavior(options) {
  90569. /**
  90570. * 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)
  90571. */
  90572. this.maxDragAngle = 0;
  90573. /**
  90574. * @hidden
  90575. */
  90576. this._useAlternatePickedPointAboveMaxDragAngle = false;
  90577. /**
  90578. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  90579. */
  90580. this.currentDraggingPointerID = -1;
  90581. /**
  90582. * If the behavior is currently in a dragging state
  90583. */
  90584. this.dragging = false;
  90585. /**
  90586. * 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)
  90587. */
  90588. this.dragDeltaRatio = 0.2;
  90589. /**
  90590. * If the drag plane orientation should be updated during the dragging (Default: true)
  90591. */
  90592. this.updateDragPlane = true;
  90593. // Debug mode will display drag planes to help visualize behavior
  90594. this._debugMode = false;
  90595. this._moving = false;
  90596. /**
  90597. * Fires each time the attached mesh is dragged with the pointer
  90598. * * delta between last drag position and current drag position in world space
  90599. * * dragDistance along the drag axis
  90600. * * dragPlaneNormal normal of the current drag plane used during the drag
  90601. * * dragPlanePoint in world space where the drag intersects the drag plane
  90602. */
  90603. this.onDragObservable = new BABYLON.Observable();
  90604. /**
  90605. * Fires each time a drag begins (eg. mouse down on mesh)
  90606. */
  90607. this.onDragStartObservable = new BABYLON.Observable();
  90608. /**
  90609. * Fires each time a drag ends (eg. mouse release after drag)
  90610. */
  90611. this.onDragEndObservable = new BABYLON.Observable();
  90612. /**
  90613. * If the attached mesh should be moved when dragged
  90614. */
  90615. this.moveAttached = true;
  90616. /**
  90617. * If the drag behavior will react to drag events (Default: true)
  90618. */
  90619. this.enabled = true;
  90620. /**
  90621. * If camera controls should be detached during the drag
  90622. */
  90623. this.detachCameraControls = true;
  90624. /**
  90625. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  90626. */
  90627. this.useObjectOrienationForDragging = true;
  90628. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  90629. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  90630. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  90631. // Variables to avoid instantiation in the below method
  90632. this._pointA = new BABYLON.Vector3(0, 0, 0);
  90633. this._pointB = new BABYLON.Vector3(0, 0, 0);
  90634. this._pointC = new BABYLON.Vector3(0, 0, 0);
  90635. this._lineA = new BABYLON.Vector3(0, 0, 0);
  90636. this._lineB = new BABYLON.Vector3(0, 0, 0);
  90637. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  90638. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  90639. this._options = options ? options : {};
  90640. var optionCount = 0;
  90641. if (this._options.dragAxis) {
  90642. optionCount++;
  90643. }
  90644. if (this._options.dragPlaneNormal) {
  90645. optionCount++;
  90646. }
  90647. if (optionCount > 1) {
  90648. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  90649. }
  90650. }
  90651. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  90652. /**
  90653. * The name of the behavior
  90654. */
  90655. get: function () {
  90656. return "PointerDrag";
  90657. },
  90658. enumerable: true,
  90659. configurable: true
  90660. });
  90661. /**
  90662. * Initializes the behavior
  90663. */
  90664. PointerDragBehavior.prototype.init = function () { };
  90665. /**
  90666. * Attaches the drag behavior the passed in mesh
  90667. * @param ownerNode The mesh that will be dragged around once attached
  90668. */
  90669. PointerDragBehavior.prototype.attach = function (ownerNode) {
  90670. var _this = this;
  90671. this._scene = ownerNode.getScene();
  90672. this._attachedNode = ownerNode;
  90673. // Initialize drag plane to not interfere with existing scene
  90674. if (!PointerDragBehavior._planeScene) {
  90675. if (this._debugMode) {
  90676. PointerDragBehavior._planeScene = this._scene;
  90677. }
  90678. else {
  90679. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  90680. PointerDragBehavior._planeScene.detachControl();
  90681. this._scene.getEngine().scenes.pop();
  90682. this._scene.onDisposeObservable.addOnce(function () {
  90683. PointerDragBehavior._planeScene.dispose();
  90684. PointerDragBehavior._planeScene = null;
  90685. });
  90686. }
  90687. }
  90688. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  90689. // State of the drag
  90690. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  90691. var delta = new BABYLON.Vector3(0, 0, 0);
  90692. var dragLength = 0;
  90693. var targetPosition = new BABYLON.Vector3(0, 0, 0);
  90694. var pickPredicate = function (m) {
  90695. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  90696. };
  90697. var attachedElement = null;
  90698. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  90699. if (!_this.enabled) {
  90700. return;
  90701. }
  90702. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  90703. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  90704. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  90705. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  90706. if (pickedPoint) {
  90707. _this.dragging = true;
  90708. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  90709. _this.lastDragPosition.copyFrom(pickedPoint);
  90710. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: _this.currentDraggingPointerID });
  90711. targetPosition.copyFrom(_this._attachedNode.absolutePosition);
  90712. // Detatch camera controls
  90713. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  90714. if (_this._scene.activeCamera.inputs.attachedElement) {
  90715. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  90716. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  90717. }
  90718. else {
  90719. attachedElement = null;
  90720. }
  90721. }
  90722. }
  90723. }
  90724. }
  90725. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  90726. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  90727. _this.releaseDrag();
  90728. // Reattach camera controls
  90729. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  90730. _this._scene.activeCamera.attachControl(attachedElement, true);
  90731. }
  90732. }
  90733. }
  90734. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  90735. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  90736. _this._moving = true;
  90737. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  90738. if (pickedPoint) {
  90739. if (_this.updateDragPlane) {
  90740. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pickedPoint);
  90741. }
  90742. // depending on the drag mode option drag accordingly
  90743. if (_this._options.dragAxis) {
  90744. // Convert local drag axis to world
  90745. BABYLON.Vector3.TransformCoordinatesToRef(_this._options.dragAxis, _this._attachedNode.getWorldMatrix().getRotationMatrix(), _this._worldDragAxis);
  90746. // Project delta drag from the drag plane onto the drag axis
  90747. pickedPoint.subtractToRef(_this.lastDragPosition, _this._tmpVector);
  90748. dragLength = BABYLON.Vector3.Dot(_this._tmpVector, _this._worldDragAxis);
  90749. _this._worldDragAxis.scaleToRef(dragLength, delta);
  90750. }
  90751. else {
  90752. dragLength = delta.length();
  90753. pickedPoint.subtractToRef(_this.lastDragPosition, delta);
  90754. }
  90755. targetPosition.addInPlace(delta);
  90756. _this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: delta, dragPlanePoint: pickedPoint, dragPlaneNormal: _this._dragPlane.forward, pointerId: _this.currentDraggingPointerID });
  90757. _this.lastDragPosition.copyFrom(pickedPoint);
  90758. }
  90759. }
  90760. }
  90761. });
  90762. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  90763. if (_this._moving && _this.moveAttached) {
  90764. // Slowly move mesh to avoid jitter
  90765. targetPosition.subtractToRef(_this._attachedNode.absolutePosition, _this._tmpVector);
  90766. _this._tmpVector.scaleInPlace(0.2);
  90767. _this._attachedNode.getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  90768. _this._attachedNode.setAbsolutePosition(_this._tmpVector);
  90769. }
  90770. });
  90771. };
  90772. PointerDragBehavior.prototype.releaseDrag = function () {
  90773. this.dragging = false;
  90774. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  90775. this.currentDraggingPointerID = -1;
  90776. this._moving = false;
  90777. };
  90778. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  90779. var _this = this;
  90780. if (!ray) {
  90781. return null;
  90782. }
  90783. // Calculate angle between plane normal and ray
  90784. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  90785. // Correct if ray is casted from oposite side
  90786. if (angle > Math.PI / 2) {
  90787. angle = Math.PI - angle;
  90788. }
  90789. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  90790. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  90791. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  90792. // Invert ray direction along the towards object axis
  90793. this._tmpVector.copyFrom(ray.direction);
  90794. this._attachedNode.absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  90795. this._alternatePickedPoint.normalize();
  90796. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  90797. this._tmpVector.addInPlace(this._alternatePickedPoint);
  90798. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  90799. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  90800. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  90801. this._alternatePickedPoint.addInPlace(this._tmpVector);
  90802. this._alternatePickedPoint.addInPlace(this._attachedNode.absolutePosition);
  90803. return this._alternatePickedPoint;
  90804. }
  90805. else {
  90806. return null;
  90807. }
  90808. }
  90809. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  90810. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  90811. return pickResult.pickedPoint;
  90812. }
  90813. else {
  90814. return null;
  90815. }
  90816. };
  90817. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  90818. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  90819. this._pointA.copyFrom(dragPlanePosition);
  90820. if (this._options.dragAxis) {
  90821. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  90822. // Calculate plane normal in direction of camera but perpendicular to drag axis
  90823. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  90824. ray.origin.subtractToRef(this._pointA, this._pointC);
  90825. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  90826. // Get perpendicular line from direction to camera and drag axis
  90827. this._pointB.subtractToRef(this._pointA, this._lineA);
  90828. this._pointC.subtractToRef(this._pointA, this._lineB);
  90829. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  90830. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  90831. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  90832. this._lookAt.normalize();
  90833. this._dragPlane.position.copyFrom(this._pointA);
  90834. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  90835. this._dragPlane.lookAt(this._lookAt);
  90836. }
  90837. else if (this._options.dragPlaneNormal) {
  90838. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  90839. this._dragPlane.position.copyFrom(this._pointA);
  90840. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  90841. this._dragPlane.lookAt(this._lookAt);
  90842. }
  90843. else {
  90844. this._dragPlane.position.copyFrom(this._pointA);
  90845. this._dragPlane.lookAt(ray.origin);
  90846. }
  90847. this._dragPlane.computeWorldMatrix(true);
  90848. };
  90849. /**
  90850. * Detaches the behavior from the mesh
  90851. */
  90852. PointerDragBehavior.prototype.detach = function () {
  90853. if (this._pointerObserver) {
  90854. this._scene.onPointerObservable.remove(this._pointerObserver);
  90855. }
  90856. if (this._beforeRenderObserver) {
  90857. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  90858. }
  90859. };
  90860. return PointerDragBehavior;
  90861. }());
  90862. BABYLON.PointerDragBehavior = PointerDragBehavior;
  90863. })(BABYLON || (BABYLON = {}));
  90864. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  90865. var BABYLON;
  90866. (function (BABYLON) {
  90867. /**
  90868. * A behavior that when attached to a mesh will allow the mesh to be scaled
  90869. */
  90870. var MultiPointerScaleBehavior = /** @class */ (function () {
  90871. function MultiPointerScaleBehavior() {
  90872. this._startDistance = 0;
  90873. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  90874. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  90875. this._sceneRenderObserver = null;
  90876. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  90877. this._dragBehaviorA.moveAttached = false;
  90878. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  90879. this._dragBehaviorB.moveAttached = false;
  90880. }
  90881. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  90882. /**
  90883. * The name of the behavior
  90884. */
  90885. get: function () {
  90886. return "MultiPointerScale";
  90887. },
  90888. enumerable: true,
  90889. configurable: true
  90890. });
  90891. /**
  90892. * Initializes the behavior
  90893. */
  90894. MultiPointerScaleBehavior.prototype.init = function () { };
  90895. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  90896. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  90897. };
  90898. /**
  90899. * Attaches the scale behavior the passed in mesh
  90900. * @param ownerNode The mesh that will be scaled around once attached
  90901. */
  90902. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  90903. var _this = this;
  90904. this._ownerNode = ownerNode;
  90905. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  90906. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  90907. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  90908. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  90909. _this._dragBehaviorA.releaseDrag();
  90910. }
  90911. else {
  90912. _this._initialScale.copyFrom(ownerNode.scaling);
  90913. _this._startDistance = _this._getCurrentDistance();
  90914. }
  90915. }
  90916. });
  90917. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  90918. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  90919. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  90920. _this._dragBehaviorB.releaseDrag();
  90921. }
  90922. else {
  90923. _this._initialScale.copyFrom(ownerNode.scaling);
  90924. _this._startDistance = _this._getCurrentDistance();
  90925. }
  90926. }
  90927. });
  90928. // Once both drag behaviors are active scale based on the distance between the two pointers
  90929. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  90930. behavior.onDragObservable.add(function () {
  90931. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  90932. var ratio = _this._getCurrentDistance() / _this._startDistance;
  90933. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  90934. }
  90935. });
  90936. });
  90937. ownerNode.addBehavior(this._dragBehaviorA);
  90938. ownerNode.addBehavior(this._dragBehaviorB);
  90939. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  90940. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  90941. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  90942. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  90943. if (change.length() > 0.01) {
  90944. ownerNode.scaling.addInPlace(change);
  90945. }
  90946. }
  90947. });
  90948. };
  90949. /**
  90950. * Detaches the behavior from the mesh
  90951. */
  90952. MultiPointerScaleBehavior.prototype.detach = function () {
  90953. var _this = this;
  90954. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  90955. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  90956. behavior.onDragStartObservable.clear();
  90957. behavior.onDragObservable.clear();
  90958. _this._ownerNode.removeBehavior(behavior);
  90959. });
  90960. };
  90961. return MultiPointerScaleBehavior;
  90962. }());
  90963. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  90964. })(BABYLON || (BABYLON = {}));
  90965. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  90966. var BABYLON;
  90967. (function (BABYLON) {
  90968. /**
  90969. * 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
  90970. */
  90971. var SixDofDragBehavior = /** @class */ (function () {
  90972. function SixDofDragBehavior() {
  90973. this._sceneRenderObserver = null;
  90974. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  90975. this._moving = false;
  90976. this._startingOrientation = new BABYLON.Quaternion();
  90977. /**
  90978. * 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)
  90979. */
  90980. this.zDragFactor = 3;
  90981. /**
  90982. * If the behavior is currently in a dragging state
  90983. */
  90984. this.dragging = false;
  90985. /**
  90986. * 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)
  90987. */
  90988. this.dragDeltaRatio = 0.2;
  90989. /**
  90990. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  90991. */
  90992. this.currentDraggingPointerID = -1;
  90993. /**
  90994. * If camera controls should be detached during the drag
  90995. */
  90996. this.detachCameraControls = true;
  90997. }
  90998. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  90999. /**
  91000. * The name of the behavior
  91001. */
  91002. get: function () {
  91003. return "SixDofDrag";
  91004. },
  91005. enumerable: true,
  91006. configurable: true
  91007. });
  91008. /**
  91009. * Initializes the behavior
  91010. */
  91011. SixDofDragBehavior.prototype.init = function () { };
  91012. /**
  91013. * Attaches the scale behavior the passed in mesh
  91014. * @param ownerNode The mesh that will be scaled around once attached
  91015. */
  91016. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  91017. var _this = this;
  91018. this._ownerNode = ownerNode;
  91019. this._scene = this._ownerNode.getScene();
  91020. if (!SixDofDragBehavior._virtualScene) {
  91021. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  91022. this._scene.getEngine().scenes.pop();
  91023. }
  91024. var pickedMesh = null;
  91025. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  91026. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  91027. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  91028. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  91029. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  91030. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  91031. var pickPredicate = function (m) {
  91032. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  91033. };
  91034. var attachedElement = null;
  91035. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  91036. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  91037. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  91038. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  91039. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  91040. }
  91041. pickedMesh = _this._ownerNode;
  91042. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  91043. // Set position and orientation of the controller
  91044. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  91045. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  91046. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  91047. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  91048. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  91049. if (!pickedMesh.rotationQuaternion) {
  91050. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  91051. }
  91052. var oldParent = pickedMesh.parent;
  91053. pickedMesh.setParent(null);
  91054. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  91055. pickedMesh.setParent(oldParent);
  91056. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  91057. // Update state
  91058. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  91059. _this.dragging = true;
  91060. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  91061. // Detatch camera controls
  91062. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  91063. if (_this._scene.activeCamera.inputs.attachedElement) {
  91064. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  91065. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  91066. }
  91067. else {
  91068. attachedElement = null;
  91069. }
  91070. }
  91071. }
  91072. }
  91073. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  91074. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  91075. _this.dragging = false;
  91076. _this._moving = false;
  91077. _this.currentDraggingPointerID = -1;
  91078. pickedMesh = null;
  91079. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  91080. // Reattach camera controls
  91081. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  91082. _this._scene.activeCamera.attachControl(attachedElement, true);
  91083. }
  91084. }
  91085. }
  91086. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  91087. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  91088. var zDragFactor = _this.zDragFactor;
  91089. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  91090. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  91091. zDragFactor = 0;
  91092. }
  91093. // Calculate controller drag distance in controller space
  91094. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  91095. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  91096. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  91097. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  91098. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  91099. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  91100. if (_this._virtualDragMesh.position.z < 0) {
  91101. _this._virtualDragMesh.position.z = 0;
  91102. }
  91103. // Update the controller position
  91104. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  91105. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  91106. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  91107. // Move the virtualObjectsPosition into the picked mesh's space if needed
  91108. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  91109. if (pickedMesh.parent) {
  91110. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  91111. }
  91112. if (!_this._moving) {
  91113. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  91114. }
  91115. _this._moving = true;
  91116. }
  91117. }
  91118. });
  91119. var tmpQuaternion = new BABYLON.Quaternion();
  91120. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  91121. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  91122. if (_this.dragging && _this._moving && pickedMesh) {
  91123. // Slowly move mesh to avoid jitter
  91124. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  91125. // Get change in rotation
  91126. tmpQuaternion.copyFrom(_this._startingOrientation);
  91127. tmpQuaternion.x = -tmpQuaternion.x;
  91128. tmpQuaternion.y = -tmpQuaternion.y;
  91129. tmpQuaternion.z = -tmpQuaternion.z;
  91130. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  91131. // Convert change in rotation to only y axis rotation
  91132. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  91133. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  91134. // Slowly move mesh to avoid jitter
  91135. var oldParent = pickedMesh.parent;
  91136. pickedMesh.setParent(null);
  91137. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  91138. pickedMesh.setParent(oldParent);
  91139. }
  91140. });
  91141. };
  91142. /**
  91143. * Detaches the behavior from the mesh
  91144. */
  91145. SixDofDragBehavior.prototype.detach = function () {
  91146. if (this._scene) {
  91147. this._scene.onPointerObservable.remove(this._pointerObserver);
  91148. }
  91149. if (this._ownerNode) {
  91150. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  91151. }
  91152. if (this._virtualOriginMesh) {
  91153. this._virtualOriginMesh.dispose();
  91154. }
  91155. if (this._virtualDragMesh) {
  91156. this._virtualDragMesh.dispose();
  91157. }
  91158. };
  91159. return SixDofDragBehavior;
  91160. }());
  91161. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  91162. })(BABYLON || (BABYLON = {}));
  91163. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  91164. var BABYLON;
  91165. (function (BABYLON) {
  91166. /**
  91167. * @hidden
  91168. */
  91169. var FaceDirectionInfo = /** @class */ (function () {
  91170. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  91171. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  91172. if (diff === void 0) { diff = 0; }
  91173. if (ignore === void 0) { ignore = false; }
  91174. this.direction = direction;
  91175. this.rotatedDirection = rotatedDirection;
  91176. this.diff = diff;
  91177. this.ignore = ignore;
  91178. }
  91179. return FaceDirectionInfo;
  91180. }());
  91181. /**
  91182. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  91183. */
  91184. var AttachToBoxBehavior = /** @class */ (function () {
  91185. /**
  91186. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  91187. * @param ui The transform node that should be attched to the mesh
  91188. */
  91189. function AttachToBoxBehavior(ui) {
  91190. this.ui = ui;
  91191. /**
  91192. * The name of the behavior
  91193. */
  91194. this.name = "AttachToBoxBehavior";
  91195. /**
  91196. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  91197. */
  91198. this.distanceAwayFromFace = 0.15;
  91199. /**
  91200. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  91201. */
  91202. this.distanceAwayFromBottomOfFace = 0.15;
  91203. 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))];
  91204. this._tmpMatrix = new BABYLON.Matrix();
  91205. this._tmpVector = new BABYLON.Vector3();
  91206. this._zeroVector = BABYLON.Vector3.Zero();
  91207. this._lookAtTmpMatrix = new BABYLON.Matrix();
  91208. /* Does nothing */
  91209. }
  91210. /**
  91211. * Initializes the behavior
  91212. */
  91213. AttachToBoxBehavior.prototype.init = function () {
  91214. /* Does nothing */
  91215. };
  91216. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  91217. var _this = this;
  91218. // Go over each face and calculate the angle between the face's normal and targetDirection
  91219. this._faceVectors.forEach(function (v) {
  91220. if (!_this._target.rotationQuaternion) {
  91221. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  91222. }
  91223. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  91224. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  91225. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  91226. });
  91227. // Return the face information of the one with the normal closeset to target direction
  91228. return this._faceVectors.reduce(function (min, p) {
  91229. if (min.ignore) {
  91230. return p;
  91231. }
  91232. else if (p.ignore) {
  91233. return min;
  91234. }
  91235. else {
  91236. return min.diff < p.diff ? min : p;
  91237. }
  91238. }, this._faceVectors[0]);
  91239. };
  91240. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  91241. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  91242. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  91243. this._lookAtTmpMatrix.invert();
  91244. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  91245. };
  91246. /**
  91247. * Attaches the AttachToBoxBehavior to the passed in mesh
  91248. * @param target The mesh that the specified node will be attached to
  91249. */
  91250. AttachToBoxBehavior.prototype.attach = function (target) {
  91251. var _this = this;
  91252. this._target = target;
  91253. this._scene = this._target.getScene();
  91254. // Every frame, update the app bars position
  91255. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  91256. if (!_this._scene.activeCamera) {
  91257. return;
  91258. }
  91259. // Find the face closest to the cameras position
  91260. var cameraPos = _this._scene.activeCamera.position;
  91261. if (_this._scene.activeCamera.devicePosition) {
  91262. cameraPos = _this._scene.activeCamera.devicePosition;
  91263. }
  91264. var facing = _this._closestFace(cameraPos.subtract(target.position));
  91265. if (_this._scene.activeCamera.leftCamera) {
  91266. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  91267. }
  91268. else {
  91269. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  91270. }
  91271. // Get camera up direction
  91272. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  91273. // Ignore faces to not select a parrelel face for the up vector of the UI
  91274. _this._faceVectors.forEach(function (v) {
  91275. if (facing.direction.x && v.direction.x) {
  91276. v.ignore = true;
  91277. }
  91278. if (facing.direction.y && v.direction.y) {
  91279. v.ignore = true;
  91280. }
  91281. if (facing.direction.z && v.direction.z) {
  91282. v.ignore = true;
  91283. }
  91284. });
  91285. var facingUp = _this._closestFace(_this._tmpVector);
  91286. // Unignore faces
  91287. _this._faceVectors.forEach(function (v) {
  91288. v.ignore = false;
  91289. });
  91290. // Position the app bar on that face
  91291. _this.ui.position.copyFrom(target.position);
  91292. if (facing.direction.x) {
  91293. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  91294. _this.ui.position.addInPlace(_this._tmpVector);
  91295. }
  91296. if (facing.direction.y) {
  91297. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  91298. _this.ui.position.addInPlace(_this._tmpVector);
  91299. }
  91300. if (facing.direction.z) {
  91301. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  91302. _this.ui.position.addInPlace(_this._tmpVector);
  91303. }
  91304. // Rotate to be oriented properly to the camera
  91305. if (!_this.ui.rotationQuaternion) {
  91306. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  91307. }
  91308. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  91309. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  91310. // Place ui the correct distance from the bottom of the mesh
  91311. if (facingUp.direction.x) {
  91312. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  91313. }
  91314. if (facingUp.direction.y) {
  91315. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  91316. }
  91317. if (facingUp.direction.z) {
  91318. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  91319. }
  91320. _this.ui.position.addInPlace(_this._tmpVector);
  91321. });
  91322. };
  91323. /**
  91324. * Detaches the behavior from the mesh
  91325. */
  91326. AttachToBoxBehavior.prototype.detach = function () {
  91327. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  91328. };
  91329. return AttachToBoxBehavior;
  91330. }());
  91331. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  91332. })(BABYLON || (BABYLON = {}));
  91333. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  91334. var BABYLON;
  91335. (function (BABYLON) {
  91336. /**
  91337. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  91338. */
  91339. var Gizmo = /** @class */ (function () {
  91340. /**
  91341. * Creates a gizmo
  91342. * @param gizmoLayer The utility layer the gizmo will be added to
  91343. */
  91344. function Gizmo(
  91345. /** The utility layer the gizmo will be added to */
  91346. gizmoLayer) {
  91347. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  91348. var _this = this;
  91349. this.gizmoLayer = gizmoLayer;
  91350. /**
  91351. * Ratio for the scale of the gizmo (Default: 1)
  91352. */
  91353. this.scaleRatio = 1;
  91354. this._tmpMatrix = new BABYLON.Matrix();
  91355. /**
  91356. * If a custom mesh has been set (Default: false)
  91357. */
  91358. this._customMeshSet = false;
  91359. /**
  91360. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  91361. */
  91362. this.updateGizmoRotationToMatchAttachedMesh = true;
  91363. /**
  91364. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  91365. */
  91366. this.updateGizmoPositionToMatchAttachedMesh = true;
  91367. /**
  91368. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  91369. */
  91370. this._updateScale = true;
  91371. this._interactionsEnabled = true;
  91372. this._tempVector = new BABYLON.Vector3();
  91373. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  91374. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  91375. _this._update();
  91376. });
  91377. this.attachedMesh = null;
  91378. }
  91379. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  91380. /**
  91381. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  91382. * * When set, interactions will be enabled
  91383. */
  91384. get: function () {
  91385. return this._attachedMesh;
  91386. },
  91387. set: function (value) {
  91388. this._attachedMesh = value;
  91389. this._rootMesh.setEnabled(value ? true : false);
  91390. this._attachedMeshChanged(value);
  91391. },
  91392. enumerable: true,
  91393. configurable: true
  91394. });
  91395. /**
  91396. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  91397. * @param mesh The mesh to replace the default mesh of the gizmo
  91398. */
  91399. Gizmo.prototype.setCustomMesh = function (mesh) {
  91400. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  91401. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  91402. }
  91403. this._rootMesh.getChildMeshes().forEach(function (c) {
  91404. c.dispose();
  91405. });
  91406. mesh.parent = this._rootMesh;
  91407. this._customMeshSet = true;
  91408. };
  91409. Gizmo.prototype._attachedMeshChanged = function (value) {
  91410. };
  91411. /**
  91412. * @hidden
  91413. * Updates the gizmo to match the attached mesh's position/rotation
  91414. */
  91415. Gizmo.prototype._update = function () {
  91416. if (this.attachedMesh) {
  91417. if (this.updateGizmoRotationToMatchAttachedMesh) {
  91418. if (!this._rootMesh.rotationQuaternion) {
  91419. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  91420. }
  91421. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  91422. this._tempVector.copyFrom(this.attachedMesh.scaling);
  91423. if (this.attachedMesh.scaling.x < 0) {
  91424. this.attachedMesh.scaling.x *= -1;
  91425. }
  91426. if (this.attachedMesh.scaling.y < 0) {
  91427. this.attachedMesh.scaling.y *= -1;
  91428. }
  91429. if (this.attachedMesh.scaling.z < 0) {
  91430. this.attachedMesh.scaling.z *= -1;
  91431. }
  91432. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  91433. this.attachedMesh.scaling.copyFrom(this._tempVector);
  91434. this.attachedMesh.computeWorldMatrix();
  91435. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  91436. }
  91437. else if (this._rootMesh.rotationQuaternion) {
  91438. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  91439. }
  91440. if (this.updateGizmoPositionToMatchAttachedMesh) {
  91441. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  91442. }
  91443. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  91444. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  91445. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  91446. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  91447. }
  91448. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  91449. var dist = this._tempVector.length() * this.scaleRatio;
  91450. this._rootMesh.scaling.set(dist, dist, dist);
  91451. }
  91452. }
  91453. };
  91454. /**
  91455. * Disposes of the gizmo
  91456. */
  91457. Gizmo.prototype.dispose = function () {
  91458. this._rootMesh.dispose();
  91459. if (this._beforeRenderObserver) {
  91460. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  91461. }
  91462. };
  91463. return Gizmo;
  91464. }());
  91465. BABYLON.Gizmo = Gizmo;
  91466. })(BABYLON || (BABYLON = {}));
  91467. //# sourceMappingURL=babylon.gizmo.js.map
  91468. var BABYLON;
  91469. (function (BABYLON) {
  91470. /**
  91471. * Single axis drag gizmo
  91472. */
  91473. var AxisDragGizmo = /** @class */ (function (_super) {
  91474. __extends(AxisDragGizmo, _super);
  91475. /**
  91476. * Creates an AxisDragGizmo
  91477. * @param gizmoLayer The utility layer the gizmo will be added to
  91478. * @param dragAxis The axis which the gizmo will be able to drag on
  91479. * @param color The color of the gizmo
  91480. */
  91481. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  91482. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  91483. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  91484. var _this = _super.call(this, gizmoLayer) || this;
  91485. _this._pointerObserver = null;
  91486. /**
  91487. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  91488. */
  91489. _this.snapDistance = 0;
  91490. /**
  91491. * Event that fires each time the gizmo snaps to a new location.
  91492. * * snapDistance is the the change in distance
  91493. */
  91494. _this.onSnapObservable = new BABYLON.Observable();
  91495. // Create Material
  91496. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  91497. coloredMaterial.disableLighting = true;
  91498. coloredMaterial.emissiveColor = color;
  91499. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  91500. hoverMaterial.disableLighting = true;
  91501. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  91502. // Build mesh on root node
  91503. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  91504. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  91505. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  91506. arrowTail.color = coloredMaterial.emissiveColor;
  91507. arrow.addChild(arrowMesh);
  91508. arrow.addChild(arrowTail);
  91509. // Position arrow pointing in its drag axis
  91510. arrowMesh.scaling.scaleInPlace(0.05);
  91511. arrowMesh.material = coloredMaterial;
  91512. arrowMesh.rotation.x = Math.PI / 2;
  91513. arrowMesh.position.z += 0.3;
  91514. arrowTail.scaling.scaleInPlace(0.26);
  91515. arrowTail.rotation.x = Math.PI / 2;
  91516. arrowTail.material = coloredMaterial;
  91517. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  91518. arrow.scaling.scaleInPlace(1 / 3);
  91519. _this._rootMesh.addChild(arrow);
  91520. var currentSnapDragDistance = 0;
  91521. var tmpVector = new BABYLON.Vector3();
  91522. var tmpSnapEvent = { snapDistance: 0 };
  91523. // Add drag behavior to handle events when the gizmo is dragged
  91524. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  91525. _this.dragBehavior.moveAttached = false;
  91526. _this._rootMesh.addBehavior(_this.dragBehavior);
  91527. var localDelta = new BABYLON.Vector3();
  91528. var tmpMatrix = new BABYLON.Matrix();
  91529. _this.dragBehavior.onDragObservable.add(function (event) {
  91530. if (_this.attachedMesh) {
  91531. // Convert delta to local translation if it has a parent
  91532. if (_this.attachedMesh.parent) {
  91533. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  91534. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  91535. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  91536. }
  91537. else {
  91538. localDelta.copyFrom(event.delta);
  91539. }
  91540. // Snapping logic
  91541. if (_this.snapDistance == 0) {
  91542. _this.attachedMesh.position.addInPlace(localDelta);
  91543. }
  91544. else {
  91545. currentSnapDragDistance += event.dragDistance;
  91546. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  91547. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  91548. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  91549. localDelta.normalizeToRef(tmpVector);
  91550. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  91551. _this.attachedMesh.position.addInPlace(tmpVector);
  91552. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  91553. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  91554. }
  91555. }
  91556. }
  91557. });
  91558. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  91559. if (_this._customMeshSet) {
  91560. return;
  91561. }
  91562. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  91563. var material = isHovered ? hoverMaterial : coloredMaterial;
  91564. _this._rootMesh.getChildMeshes().forEach(function (m) {
  91565. m.material = material;
  91566. if (m.color) {
  91567. m.color = material.emissiveColor;
  91568. }
  91569. });
  91570. });
  91571. return _this;
  91572. }
  91573. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  91574. if (this.dragBehavior) {
  91575. this.dragBehavior.enabled = value ? true : false;
  91576. }
  91577. };
  91578. /**
  91579. * Disposes of the gizmo
  91580. */
  91581. AxisDragGizmo.prototype.dispose = function () {
  91582. this.onSnapObservable.clear();
  91583. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  91584. this.dragBehavior.detach();
  91585. _super.prototype.dispose.call(this);
  91586. };
  91587. return AxisDragGizmo;
  91588. }(BABYLON.Gizmo));
  91589. BABYLON.AxisDragGizmo = AxisDragGizmo;
  91590. })(BABYLON || (BABYLON = {}));
  91591. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  91592. var BABYLON;
  91593. (function (BABYLON) {
  91594. /**
  91595. * Single axis scale gizmo
  91596. */
  91597. var AxisScaleGizmo = /** @class */ (function (_super) {
  91598. __extends(AxisScaleGizmo, _super);
  91599. /**
  91600. * Creates an AxisScaleGizmo
  91601. * @param gizmoLayer The utility layer the gizmo will be added to
  91602. * @param dragAxis The axis which the gizmo will be able to scale on
  91603. * @param color The color of the gizmo
  91604. */
  91605. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  91606. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  91607. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  91608. var _this = _super.call(this, gizmoLayer) || this;
  91609. _this._pointerObserver = null;
  91610. /**
  91611. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  91612. */
  91613. _this.snapDistance = 0;
  91614. /**
  91615. * Event that fires each time the gizmo snaps to a new location.
  91616. * * snapDistance is the the change in distance
  91617. */
  91618. _this.onSnapObservable = new BABYLON.Observable();
  91619. /**
  91620. * If the scaling operation should be done on all axis (default: false)
  91621. */
  91622. _this.uniformScaling = false;
  91623. // Create Material
  91624. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  91625. _this._coloredMaterial.disableLighting = true;
  91626. _this._coloredMaterial.emissiveColor = color;
  91627. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  91628. hoverMaterial.disableLighting = true;
  91629. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  91630. // Build mesh on root node
  91631. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  91632. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  91633. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  91634. arrowTail.color = _this._coloredMaterial.emissiveColor;
  91635. arrow.addChild(arrowMesh);
  91636. arrow.addChild(arrowTail);
  91637. // Position arrow pointing in its drag axis
  91638. arrowMesh.scaling.scaleInPlace(0.1);
  91639. arrowMesh.material = _this._coloredMaterial;
  91640. arrowMesh.rotation.x = Math.PI / 2;
  91641. arrowMesh.position.z += 0.3;
  91642. arrowTail.scaling.scaleInPlace(0.26);
  91643. arrowTail.rotation.x = Math.PI / 2;
  91644. arrowTail.material = _this._coloredMaterial;
  91645. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  91646. _this._rootMesh.addChild(arrow);
  91647. arrow.scaling.scaleInPlace(1 / 3);
  91648. // Add drag behavior to handle events when the gizmo is dragged
  91649. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  91650. _this.dragBehavior.moveAttached = false;
  91651. _this._rootMesh.addBehavior(_this.dragBehavior);
  91652. var currentSnapDragDistance = 0;
  91653. var tmpVector = new BABYLON.Vector3();
  91654. var tmpSnapEvent = { snapDistance: 0 };
  91655. _this.dragBehavior.onDragObservable.add(function (event) {
  91656. if (_this.attachedMesh) {
  91657. // Snapping logic
  91658. var snapped = false;
  91659. var dragSteps = 0;
  91660. if (_this.uniformScaling) {
  91661. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  91662. if (tmpVector.y < 0) {
  91663. tmpVector.scaleInPlace(-1);
  91664. }
  91665. }
  91666. else {
  91667. tmpVector.copyFrom(dragAxis);
  91668. }
  91669. if (_this.snapDistance == 0) {
  91670. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  91671. }
  91672. else {
  91673. currentSnapDragDistance += event.dragDistance;
  91674. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  91675. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  91676. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  91677. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  91678. snapped = true;
  91679. }
  91680. else {
  91681. tmpVector.scaleInPlace(0);
  91682. }
  91683. }
  91684. _this.attachedMesh.scaling.addInPlace(tmpVector);
  91685. if (snapped) {
  91686. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  91687. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  91688. }
  91689. }
  91690. });
  91691. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  91692. if (_this._customMeshSet) {
  91693. return;
  91694. }
  91695. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  91696. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  91697. _this._rootMesh.getChildMeshes().forEach(function (m) {
  91698. m.material = material;
  91699. if (m.color) {
  91700. m.color = material.emissiveColor;
  91701. }
  91702. });
  91703. });
  91704. return _this;
  91705. }
  91706. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  91707. if (this.dragBehavior) {
  91708. this.dragBehavior.enabled = value ? true : false;
  91709. }
  91710. };
  91711. /**
  91712. * Disposes of the gizmo
  91713. */
  91714. AxisScaleGizmo.prototype.dispose = function () {
  91715. this.onSnapObservable.clear();
  91716. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  91717. this.dragBehavior.detach();
  91718. _super.prototype.dispose.call(this);
  91719. };
  91720. /**
  91721. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  91722. * @param mesh The mesh to replace the default mesh of the gizmo
  91723. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  91724. */
  91725. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  91726. var _this = this;
  91727. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  91728. _super.prototype.setCustomMesh.call(this, mesh);
  91729. if (useGizmoMaterial) {
  91730. this._rootMesh.getChildMeshes().forEach(function (m) {
  91731. m.material = _this._coloredMaterial;
  91732. if (m.color) {
  91733. m.color = _this._coloredMaterial.emissiveColor;
  91734. }
  91735. });
  91736. this._customMeshSet = false;
  91737. }
  91738. };
  91739. return AxisScaleGizmo;
  91740. }(BABYLON.Gizmo));
  91741. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  91742. })(BABYLON || (BABYLON = {}));
  91743. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  91744. var BABYLON;
  91745. (function (BABYLON) {
  91746. /**
  91747. * Single plane rotation gizmo
  91748. */
  91749. var PlaneRotationGizmo = /** @class */ (function (_super) {
  91750. __extends(PlaneRotationGizmo, _super);
  91751. /**
  91752. * Creates a PlaneRotationGizmo
  91753. * @param gizmoLayer The utility layer the gizmo will be added to
  91754. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  91755. * @param color The color of the gizmo
  91756. */
  91757. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  91758. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  91759. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  91760. var _this = _super.call(this, gizmoLayer) || this;
  91761. _this._pointerObserver = null;
  91762. /**
  91763. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  91764. */
  91765. _this.snapDistance = 0;
  91766. /**
  91767. * Event that fires each time the gizmo snaps to a new location.
  91768. * * snapDistance is the the change in distance
  91769. */
  91770. _this.onSnapObservable = new BABYLON.Observable();
  91771. // Create Material
  91772. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  91773. coloredMaterial.disableLighting = true;
  91774. coloredMaterial.emissiveColor = color;
  91775. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  91776. hoverMaterial.disableLighting = true;
  91777. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  91778. // Build mesh on root node
  91779. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  91780. // Create circle out of lines
  91781. var tessellation = 20;
  91782. var radius = 0.8;
  91783. var points = new Array();
  91784. for (var i = 0; i < tessellation; i++) {
  91785. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  91786. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  91787. }
  91788. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  91789. rotationMesh.color = coloredMaterial.emissiveColor;
  91790. // Position arrow pointing in its drag axis
  91791. rotationMesh.scaling.scaleInPlace(0.26);
  91792. rotationMesh.material = coloredMaterial;
  91793. rotationMesh.rotation.x = Math.PI / 2;
  91794. parentMesh.addChild(rotationMesh);
  91795. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  91796. _this._rootMesh.addChild(parentMesh);
  91797. parentMesh.scaling.scaleInPlace(1 / 3);
  91798. // Add drag behavior to handle events when the gizmo is dragged
  91799. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  91800. _this.dragBehavior.moveAttached = false;
  91801. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  91802. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  91803. _this._rootMesh.addBehavior(_this.dragBehavior);
  91804. var lastDragPosition = new BABYLON.Vector3();
  91805. _this.dragBehavior.onDragStartObservable.add(function (e) {
  91806. if (_this.attachedMesh) {
  91807. lastDragPosition.copyFrom(e.dragPlanePoint);
  91808. }
  91809. });
  91810. var rotationMatrix = new BABYLON.Matrix();
  91811. var planeNormalTowardsCamera = new BABYLON.Vector3();
  91812. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  91813. var tmpSnapEvent = { snapDistance: 0 };
  91814. var currentSnapDragDistance = 0;
  91815. var tmpMatrix = new BABYLON.Matrix();
  91816. var tmpVector = new BABYLON.Vector3();
  91817. var amountToRotate = new BABYLON.Quaternion();
  91818. _this.dragBehavior.onDragObservable.add(function (event) {
  91819. if (_this.attachedMesh) {
  91820. if (!_this.attachedMesh.rotationQuaternion) {
  91821. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  91822. }
  91823. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  91824. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  91825. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  91826. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  91827. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  91828. var angle = Math.atan2(cross.length(), dot);
  91829. planeNormalTowardsCamera.copyFrom(planeNormal);
  91830. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  91831. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  91832. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  91833. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  91834. }
  91835. // Flip up vector depending on which side the camera is on
  91836. if (gizmoLayer.utilityLayerScene.activeCamera) {
  91837. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  91838. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  91839. planeNormalTowardsCamera.scaleInPlace(-1);
  91840. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  91841. }
  91842. }
  91843. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  91844. if (halfCircleSide)
  91845. angle = -angle;
  91846. // Snapping logic
  91847. var snapped = false;
  91848. if (_this.snapDistance != 0) {
  91849. currentSnapDragDistance += angle;
  91850. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  91851. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  91852. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  91853. angle = _this.snapDistance * dragSteps;
  91854. snapped = true;
  91855. }
  91856. else {
  91857. angle = 0;
  91858. }
  91859. }
  91860. // If the mesh has a parent, convert needed world rotation to local rotation
  91861. tmpMatrix.reset();
  91862. if (_this.attachedMesh.parent) {
  91863. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  91864. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  91865. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  91866. }
  91867. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  91868. var quaternionCoefficient = Math.sin(angle / 2);
  91869. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  91870. // If the meshes local scale is inverted (eg. loaded gltf file parent with z scale of -1) the rotation needs to be inverted on the y axis
  91871. if (tmpMatrix.determinant() > 0) {
  91872. amountToRotate.toEulerAnglesToRef(tmpVector);
  91873. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  91874. }
  91875. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  91876. // Rotate selected mesh quaternion over fixed axis
  91877. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  91878. }
  91879. else {
  91880. // Rotate selected mesh quaternion over rotated axis
  91881. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  91882. }
  91883. lastDragPosition.copyFrom(event.dragPlanePoint);
  91884. if (snapped) {
  91885. tmpSnapEvent.snapDistance = angle;
  91886. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  91887. }
  91888. }
  91889. });
  91890. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  91891. if (_this._customMeshSet) {
  91892. return;
  91893. }
  91894. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  91895. var material = isHovered ? hoverMaterial : coloredMaterial;
  91896. _this._rootMesh.getChildMeshes().forEach(function (m) {
  91897. m.material = material;
  91898. if (m.color) {
  91899. m.color = material.emissiveColor;
  91900. }
  91901. });
  91902. });
  91903. return _this;
  91904. }
  91905. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  91906. if (this.dragBehavior) {
  91907. this.dragBehavior.enabled = value ? true : false;
  91908. }
  91909. };
  91910. /**
  91911. * Disposes of the gizmo
  91912. */
  91913. PlaneRotationGizmo.prototype.dispose = function () {
  91914. this.onSnapObservable.clear();
  91915. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  91916. this.dragBehavior.detach();
  91917. _super.prototype.dispose.call(this);
  91918. };
  91919. return PlaneRotationGizmo;
  91920. }(BABYLON.Gizmo));
  91921. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  91922. })(BABYLON || (BABYLON = {}));
  91923. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  91924. var BABYLON;
  91925. (function (BABYLON) {
  91926. /**
  91927. * Gizmo that enables dragging a mesh along 3 axis
  91928. */
  91929. var PositionGizmo = /** @class */ (function (_super) {
  91930. __extends(PositionGizmo, _super);
  91931. /**
  91932. * Creates a PositionGizmo
  91933. * @param gizmoLayer The utility layer the gizmo will be added to
  91934. */
  91935. function PositionGizmo(gizmoLayer) {
  91936. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  91937. var _this = _super.call(this, gizmoLayer) || this;
  91938. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  91939. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  91940. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  91941. _this.attachedMesh = null;
  91942. return _this;
  91943. }
  91944. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  91945. set: function (mesh) {
  91946. if (this.xGizmo) {
  91947. this.xGizmo.attachedMesh = mesh;
  91948. this.yGizmo.attachedMesh = mesh;
  91949. this.zGizmo.attachedMesh = mesh;
  91950. }
  91951. },
  91952. enumerable: true,
  91953. configurable: true
  91954. });
  91955. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  91956. get: function () {
  91957. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  91958. },
  91959. set: function (value) {
  91960. if (this.xGizmo) {
  91961. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  91962. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  91963. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  91964. }
  91965. },
  91966. enumerable: true,
  91967. configurable: true
  91968. });
  91969. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  91970. get: function () {
  91971. return this.xGizmo.snapDistance;
  91972. },
  91973. /**
  91974. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  91975. */
  91976. set: function (value) {
  91977. if (this.xGizmo) {
  91978. this.xGizmo.snapDistance = value;
  91979. this.yGizmo.snapDistance = value;
  91980. this.zGizmo.snapDistance = value;
  91981. }
  91982. },
  91983. enumerable: true,
  91984. configurable: true
  91985. });
  91986. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  91987. get: function () {
  91988. return this.xGizmo.scaleRatio;
  91989. },
  91990. /**
  91991. * Ratio for the scale of the gizmo (Default: 1)
  91992. */
  91993. set: function (value) {
  91994. if (this.xGizmo) {
  91995. this.xGizmo.scaleRatio = value;
  91996. this.yGizmo.scaleRatio = value;
  91997. this.zGizmo.scaleRatio = value;
  91998. }
  91999. },
  92000. enumerable: true,
  92001. configurable: true
  92002. });
  92003. /**
  92004. * Disposes of the gizmo
  92005. */
  92006. PositionGizmo.prototype.dispose = function () {
  92007. this.xGizmo.dispose();
  92008. this.yGizmo.dispose();
  92009. this.zGizmo.dispose();
  92010. };
  92011. /**
  92012. * CustomMeshes are not supported by this gizmo
  92013. * @param mesh The mesh to replace the default mesh of the gizmo
  92014. */
  92015. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  92016. 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)");
  92017. };
  92018. return PositionGizmo;
  92019. }(BABYLON.Gizmo));
  92020. BABYLON.PositionGizmo = PositionGizmo;
  92021. })(BABYLON || (BABYLON = {}));
  92022. //# sourceMappingURL=babylon.positionGizmo.js.map
  92023. var BABYLON;
  92024. (function (BABYLON) {
  92025. /**
  92026. * Gizmo that enables rotating a mesh along 3 axis
  92027. */
  92028. var RotationGizmo = /** @class */ (function (_super) {
  92029. __extends(RotationGizmo, _super);
  92030. /**
  92031. * Creates a RotationGizmo
  92032. * @param gizmoLayer The utility layer the gizmo will be added to
  92033. */
  92034. function RotationGizmo(gizmoLayer) {
  92035. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  92036. var _this = _super.call(this, gizmoLayer) || this;
  92037. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  92038. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  92039. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  92040. _this.attachedMesh = null;
  92041. return _this;
  92042. }
  92043. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  92044. set: function (mesh) {
  92045. if (this.xGizmo) {
  92046. this.xGizmo.attachedMesh = mesh;
  92047. this.yGizmo.attachedMesh = mesh;
  92048. this.zGizmo.attachedMesh = mesh;
  92049. }
  92050. },
  92051. enumerable: true,
  92052. configurable: true
  92053. });
  92054. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  92055. get: function () {
  92056. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  92057. },
  92058. set: function (value) {
  92059. if (this.xGizmo) {
  92060. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92061. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92062. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92063. }
  92064. },
  92065. enumerable: true,
  92066. configurable: true
  92067. });
  92068. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  92069. get: function () {
  92070. return this.xGizmo.snapDistance;
  92071. },
  92072. /**
  92073. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  92074. */
  92075. set: function (value) {
  92076. if (this.xGizmo) {
  92077. this.xGizmo.snapDistance = value;
  92078. this.yGizmo.snapDistance = value;
  92079. this.zGizmo.snapDistance = value;
  92080. }
  92081. },
  92082. enumerable: true,
  92083. configurable: true
  92084. });
  92085. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  92086. get: function () {
  92087. return this.xGizmo.scaleRatio;
  92088. },
  92089. /**
  92090. * Ratio for the scale of the gizmo (Default: 1)
  92091. */
  92092. set: function (value) {
  92093. if (this.xGizmo) {
  92094. this.xGizmo.scaleRatio = value;
  92095. this.yGizmo.scaleRatio = value;
  92096. this.zGizmo.scaleRatio = value;
  92097. }
  92098. },
  92099. enumerable: true,
  92100. configurable: true
  92101. });
  92102. /**
  92103. * Disposes of the gizmo
  92104. */
  92105. RotationGizmo.prototype.dispose = function () {
  92106. this.xGizmo.dispose();
  92107. this.yGizmo.dispose();
  92108. this.zGizmo.dispose();
  92109. };
  92110. /**
  92111. * CustomMeshes are not supported by this gizmo
  92112. * @param mesh The mesh to replace the default mesh of the gizmo
  92113. */
  92114. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  92115. 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)");
  92116. };
  92117. return RotationGizmo;
  92118. }(BABYLON.Gizmo));
  92119. BABYLON.RotationGizmo = RotationGizmo;
  92120. })(BABYLON || (BABYLON = {}));
  92121. //# sourceMappingURL=babylon.rotationGizmo.js.map
  92122. var BABYLON;
  92123. (function (BABYLON) {
  92124. /**
  92125. * Gizmo that enables scaling a mesh along 3 axis
  92126. */
  92127. var ScaleGizmo = /** @class */ (function (_super) {
  92128. __extends(ScaleGizmo, _super);
  92129. /**
  92130. * Creates a ScaleGizmo
  92131. * @param gizmoLayer The utility layer the gizmo will be added to
  92132. */
  92133. function ScaleGizmo(gizmoLayer) {
  92134. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  92135. var _this = _super.call(this, gizmoLayer) || this;
  92136. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  92137. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  92138. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  92139. // Create uniform scale gizmo
  92140. _this._uniformGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  92141. _this._uniformGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  92142. _this._uniformGizmo.uniformScaling = true;
  92143. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this._uniformGizmo.gizmoLayer.utilityLayerScene);
  92144. octahedron.scaling.scaleInPlace(0.007);
  92145. _this._uniformGizmo.setCustomMesh(octahedron, true);
  92146. _this.attachedMesh = null;
  92147. return _this;
  92148. }
  92149. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  92150. set: function (mesh) {
  92151. if (this.xGizmo) {
  92152. this.xGizmo.attachedMesh = mesh;
  92153. this.yGizmo.attachedMesh = mesh;
  92154. this.zGizmo.attachedMesh = mesh;
  92155. this._uniformGizmo.attachedMesh = mesh;
  92156. }
  92157. },
  92158. enumerable: true,
  92159. configurable: true
  92160. });
  92161. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  92162. get: function () {
  92163. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  92164. },
  92165. set: function (value) {
  92166. if (this.xGizmo) {
  92167. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92168. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92169. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  92170. }
  92171. },
  92172. enumerable: true,
  92173. configurable: true
  92174. });
  92175. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  92176. get: function () {
  92177. return this.xGizmo.snapDistance;
  92178. },
  92179. /**
  92180. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  92181. */
  92182. set: function (value) {
  92183. if (this.xGizmo) {
  92184. this.xGizmo.snapDistance = value;
  92185. this.yGizmo.snapDistance = value;
  92186. this.zGizmo.snapDistance = value;
  92187. this._uniformGizmo.snapDistance = value;
  92188. }
  92189. },
  92190. enumerable: true,
  92191. configurable: true
  92192. });
  92193. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  92194. get: function () {
  92195. return this.xGizmo.scaleRatio;
  92196. },
  92197. /**
  92198. * Ratio for the scale of the gizmo (Default: 1)
  92199. */
  92200. set: function (value) {
  92201. if (this.xGizmo) {
  92202. this.xGizmo.scaleRatio = value;
  92203. this.yGizmo.scaleRatio = value;
  92204. this.zGizmo.scaleRatio = value;
  92205. this._uniformGizmo.scaleRatio = value;
  92206. }
  92207. },
  92208. enumerable: true,
  92209. configurable: true
  92210. });
  92211. /**
  92212. * Disposes of the gizmo
  92213. */
  92214. ScaleGizmo.prototype.dispose = function () {
  92215. this.xGizmo.dispose();
  92216. this.yGizmo.dispose();
  92217. this.zGizmo.dispose();
  92218. this._uniformGizmo.dispose();
  92219. };
  92220. return ScaleGizmo;
  92221. }(BABYLON.Gizmo));
  92222. BABYLON.ScaleGizmo = ScaleGizmo;
  92223. })(BABYLON || (BABYLON = {}));
  92224. //# sourceMappingURL=babylon.scaleGizmo.js.map
  92225. var BABYLON;
  92226. (function (BABYLON) {
  92227. /**
  92228. * Bounding box gizmo
  92229. */
  92230. var BoundingBoxGizmo = /** @class */ (function (_super) {
  92231. __extends(BoundingBoxGizmo, _super);
  92232. /**
  92233. * Creates an BoundingBoxGizmo
  92234. * @param gizmoLayer The utility layer the gizmo will be added to
  92235. * @param color The color of the gizmo
  92236. */
  92237. function BoundingBoxGizmo(color, gizmoLayer) {
  92238. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  92239. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  92240. var _this = _super.call(this, gizmoLayer) || this;
  92241. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  92242. _this._renderObserver = null;
  92243. _this._pointerObserver = null;
  92244. _this._scaleDragSpeed = 0.2;
  92245. _this._tmpQuaternion = new BABYLON.Quaternion();
  92246. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  92247. /**
  92248. * If child meshes should be ignored when calculating the boudning box. This should be set to true to avoid perf hits with heavily nested meshes (Default: false)
  92249. */
  92250. _this.ignoreChildren = false;
  92251. /**
  92252. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  92253. */
  92254. _this.rotationSphereSize = 0.1;
  92255. /**
  92256. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  92257. */
  92258. _this.scaleBoxSize = 0.1;
  92259. /**
  92260. * 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)
  92261. */
  92262. _this.fixedDragMeshScreenSize = false;
  92263. /**
  92264. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  92265. */
  92266. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  92267. /**
  92268. * Fired when a rotation sphere or scale box is dragged
  92269. */
  92270. _this.onDragStartObservable = new BABYLON.Observable();
  92271. /**
  92272. * Fired when a scale box is dragged
  92273. */
  92274. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  92275. /**
  92276. * Fired when a scale box drag is ended
  92277. */
  92278. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  92279. /**
  92280. * Fired when a rotation sphere is dragged
  92281. */
  92282. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  92283. /**
  92284. * Fired when a rotation sphere drag is ended
  92285. */
  92286. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  92287. _this._existingMeshScale = new BABYLON.Vector3();
  92288. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  92289. _this._updateScale = false;
  92290. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  92291. // Create Materials
  92292. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92293. coloredMaterial.disableLighting = true;
  92294. coloredMaterial.emissiveColor = color;
  92295. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  92296. hoverColoredMaterial.disableLighting = true;
  92297. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  92298. // Build bounding box out of lines
  92299. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  92300. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  92301. var lines = [];
  92302. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  92303. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  92304. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  92305. 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));
  92306. 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));
  92307. 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));
  92308. 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));
  92309. 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));
  92310. 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));
  92311. 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));
  92312. 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));
  92313. 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));
  92314. lines.forEach(function (l) {
  92315. l.color = color;
  92316. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  92317. l.isPickable = false;
  92318. _this._lineBoundingBox.addChild(l);
  92319. });
  92320. _this._rootMesh.addChild(_this._lineBoundingBox);
  92321. // Create rotation spheres
  92322. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  92323. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  92324. var _loop_1 = function (i_1) {
  92325. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  92326. sphere.rotationQuaternion = new BABYLON.Quaternion();
  92327. sphere.material = coloredMaterial;
  92328. // Drag behavior
  92329. _dragBehavior = new BABYLON.PointerDragBehavior({});
  92330. _dragBehavior.moveAttached = false;
  92331. _dragBehavior.updateDragPlane = false;
  92332. sphere.addBehavior(_dragBehavior);
  92333. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  92334. var totalTurnAmountOfDrag = 0;
  92335. _dragBehavior.onDragStartObservable.add(function (event) {
  92336. startingTurnDirection.copyFrom(sphere.forward);
  92337. totalTurnAmountOfDrag = 0;
  92338. });
  92339. _dragBehavior.onDragObservable.add(function (event) {
  92340. _this.onRotationSphereDragObservable.notifyObservers({});
  92341. if (_this.attachedMesh) {
  92342. var worldDragDirection = startingTurnDirection;
  92343. // Project the world right on to the drag plane
  92344. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  92345. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  92346. // project drag delta on to the resulting drag axis and rotate based on that
  92347. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  92348. // Make rotation relative to size of mesh.
  92349. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  92350. // Rotate based on axis
  92351. if (!_this.attachedMesh.rotationQuaternion) {
  92352. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  92353. }
  92354. if (!_this._anchorMesh.rotationQuaternion) {
  92355. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  92356. }
  92357. // Do not allow the object to turn more than a full circle
  92358. totalTurnAmountOfDrag += projectDist;
  92359. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  92360. if (i_1 >= 8) {
  92361. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  92362. }
  92363. else if (i_1 >= 4) {
  92364. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  92365. }
  92366. else {
  92367. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  92368. }
  92369. // Rotate around center of bounding box
  92370. _this._anchorMesh.addChild(_this.attachedMesh);
  92371. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  92372. _this._anchorMesh.removeChild(_this.attachedMesh);
  92373. }
  92374. _this.updateBoundingBox();
  92375. }
  92376. });
  92377. // Selection/deselection
  92378. _dragBehavior.onDragStartObservable.add(function () {
  92379. _this.onDragStartObservable.notifyObservers({});
  92380. _this._selectNode(sphere);
  92381. });
  92382. _dragBehavior.onDragEndObservable.add(function () {
  92383. _this.onRotationSphereDragEndObservable.notifyObservers({});
  92384. _this._selectNode(null);
  92385. });
  92386. this_1._rotateSpheresParent.addChild(sphere);
  92387. };
  92388. var this_1 = this, _dragBehavior;
  92389. for (var i_1 = 0; i_1 < 12; i_1++) {
  92390. _loop_1(i_1);
  92391. }
  92392. _this._rootMesh.addChild(_this._rotateSpheresParent);
  92393. // Create scale cubes
  92394. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  92395. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  92396. for (var i = 0; i < 2; i++) {
  92397. for (var j = 0; j < 2; j++) {
  92398. var _loop_2 = function () {
  92399. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  92400. box.material = coloredMaterial;
  92401. // Dragging logic
  92402. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  92403. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  92404. _dragBehavior.moveAttached = false;
  92405. box.addBehavior(_dragBehavior);
  92406. _dragBehavior.onDragObservable.add(function (event) {
  92407. _this.onScaleBoxDragObservable.notifyObservers({});
  92408. if (_this.attachedMesh) {
  92409. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  92410. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  92411. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  92412. _this.updateBoundingBox();
  92413. // Scale from the position of the opposite corner
  92414. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  92415. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  92416. _this._anchorMesh.addChild(_this.attachedMesh);
  92417. _this._anchorMesh.scaling.addInPlace(deltaScale);
  92418. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  92419. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  92420. }
  92421. _this._anchorMesh.removeChild(_this.attachedMesh);
  92422. }
  92423. });
  92424. // Selection/deselection
  92425. _dragBehavior.onDragStartObservable.add(function () {
  92426. _this.onDragStartObservable.notifyObservers({});
  92427. _this._selectNode(box);
  92428. });
  92429. _dragBehavior.onDragEndObservable.add(function () {
  92430. _this.onScaleBoxDragEndObservable.notifyObservers({});
  92431. _this._selectNode(null);
  92432. });
  92433. this_2._scaleBoxesParent.addChild(box);
  92434. };
  92435. var this_2 = this, _dragBehavior;
  92436. for (var k = 0; k < 2; k++) {
  92437. _loop_2();
  92438. }
  92439. }
  92440. }
  92441. _this._rootMesh.addChild(_this._scaleBoxesParent);
  92442. // Hover color change
  92443. var pointerIds = new Array();
  92444. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  92445. if (!pointerIds[pointerInfo.event.pointerId]) {
  92446. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  92447. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  92448. pointerIds[pointerInfo.event.pointerId] = mesh;
  92449. mesh.material = hoverColoredMaterial;
  92450. }
  92451. });
  92452. }
  92453. else {
  92454. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  92455. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  92456. delete pointerIds[pointerInfo.event.pointerId];
  92457. }
  92458. }
  92459. });
  92460. // Update bounding box positions
  92461. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  92462. // Only update the bouding box if scaling has changed
  92463. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  92464. _this.updateBoundingBox();
  92465. }
  92466. });
  92467. _this.updateBoundingBox();
  92468. return _this;
  92469. }
  92470. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  92471. if (value) {
  92472. // Reset anchor mesh to match attached mesh's scale
  92473. // This is needed to avoid invalid box/sphere position on first drag
  92474. this._anchorMesh.addChild(value);
  92475. this._anchorMesh.removeChild(value);
  92476. this.updateBoundingBox();
  92477. }
  92478. };
  92479. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  92480. this._rotateSpheresParent.getChildMeshes()
  92481. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  92482. m.isVisible = (!selectedMesh || m == selectedMesh);
  92483. });
  92484. };
  92485. BoundingBoxGizmo.prototype._recurseComputeWorld = function (mesh) {
  92486. var _this = this;
  92487. mesh.computeWorldMatrix(true);
  92488. if (!this.ignoreChildren) {
  92489. mesh.getChildMeshes().forEach(function (m) {
  92490. _this._recurseComputeWorld(m);
  92491. });
  92492. }
  92493. };
  92494. /**
  92495. * Updates the bounding box information for the Gizmo
  92496. */
  92497. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  92498. this._update();
  92499. if (this.attachedMesh) {
  92500. // Rotate based on axis
  92501. if (!this.attachedMesh.rotationQuaternion) {
  92502. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  92503. }
  92504. if (!this._anchorMesh.rotationQuaternion) {
  92505. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  92506. }
  92507. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  92508. // Store original position and reset mesh to origin before computing the bounding box
  92509. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  92510. this._tmpVector.copyFrom(this.attachedMesh.position);
  92511. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  92512. this.attachedMesh.position.set(0, 0, 0);
  92513. // Update bounding dimensions/positions
  92514. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren);
  92515. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  92516. // Update gizmo to match bounding box scaling and rotation
  92517. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  92518. 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);
  92519. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  92520. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  92521. this._lineBoundingBox.computeWorldMatrix();
  92522. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  92523. // restore position/rotation values
  92524. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  92525. this.attachedMesh.position.copyFrom(this._tmpVector);
  92526. this._recurseComputeWorld(this.attachedMesh);
  92527. }
  92528. // Update rotation sphere locations
  92529. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  92530. for (var i = 0; i < 3; i++) {
  92531. for (var j = 0; j < 2; j++) {
  92532. for (var k = 0; k < 2; k++) {
  92533. var index = ((i * 4) + (j * 2)) + k;
  92534. if (i == 0) {
  92535. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  92536. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  92537. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  92538. }
  92539. if (i == 1) {
  92540. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  92541. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  92542. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  92543. }
  92544. if (i == 2) {
  92545. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  92546. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  92547. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  92548. }
  92549. if (this.fixedDragMeshScreenSize) {
  92550. this._rootMesh.computeWorldMatrix();
  92551. this._rotateSpheresParent.computeWorldMatrix();
  92552. rotateSpheres[index].computeWorldMatrix();
  92553. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  92554. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  92555. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  92556. }
  92557. else {
  92558. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  92559. }
  92560. }
  92561. }
  92562. }
  92563. // Update scale box locations
  92564. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  92565. for (var i = 0; i < 2; i++) {
  92566. for (var j = 0; j < 2; j++) {
  92567. for (var k = 0; k < 2; k++) {
  92568. var index = ((i * 4) + (j * 2)) + k;
  92569. if (scaleBoxes[index]) {
  92570. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  92571. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  92572. if (this.fixedDragMeshScreenSize) {
  92573. this._rootMesh.computeWorldMatrix();
  92574. this._scaleBoxesParent.computeWorldMatrix();
  92575. scaleBoxes[index].computeWorldMatrix();
  92576. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  92577. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  92578. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  92579. }
  92580. else {
  92581. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  92582. }
  92583. }
  92584. }
  92585. }
  92586. }
  92587. if (this.attachedMesh) {
  92588. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  92589. }
  92590. };
  92591. /**
  92592. * Enables rotation on the specified axis and disables rotation on the others
  92593. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  92594. */
  92595. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  92596. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  92597. if (i < 4) {
  92598. m.setEnabled(axis.indexOf("x") != -1);
  92599. }
  92600. else if (i < 8) {
  92601. m.setEnabled(axis.indexOf("y") != -1);
  92602. }
  92603. else {
  92604. m.setEnabled(axis.indexOf("z") != -1);
  92605. }
  92606. });
  92607. };
  92608. /**
  92609. * Disposes of the gizmo
  92610. */
  92611. BoundingBoxGizmo.prototype.dispose = function () {
  92612. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  92613. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  92614. this._lineBoundingBox.dispose();
  92615. this._rotateSpheresParent.dispose();
  92616. this._scaleBoxesParent.dispose();
  92617. _super.prototype.dispose.call(this);
  92618. };
  92619. /**
  92620. * 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)
  92621. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  92622. * @returns the bounding box mesh with the passed in mesh as a child
  92623. */
  92624. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  92625. var makeNotPickable = function (root) {
  92626. root.isPickable = false;
  92627. root.getChildMeshes().forEach(function (c) {
  92628. makeNotPickable(c);
  92629. });
  92630. };
  92631. makeNotPickable(mesh);
  92632. // Reset position to get boudning box from origin with no rotation
  92633. if (!mesh.rotationQuaternion) {
  92634. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  92635. }
  92636. var oldPos = mesh.position.clone();
  92637. var oldRot = mesh.rotationQuaternion.clone();
  92638. mesh.rotationQuaternion.set(0, 0, 0, 1);
  92639. mesh.position.set(0, 0, 0);
  92640. // Update bounding dimensions/positions
  92641. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  92642. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  92643. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  92644. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  92645. // Restore original positions
  92646. mesh.addChild(box);
  92647. mesh.rotationQuaternion.copyFrom(oldRot);
  92648. mesh.position.copyFrom(oldPos);
  92649. // Reverse parenting
  92650. mesh.removeChild(box);
  92651. box.addChild(mesh);
  92652. box.visibility = 0;
  92653. return box;
  92654. };
  92655. /**
  92656. * CustomMeshes are not supported by this gizmo
  92657. * @param mesh The mesh to replace the default mesh of the gizmo
  92658. */
  92659. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  92660. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  92661. };
  92662. return BoundingBoxGizmo;
  92663. }(BABYLON.Gizmo));
  92664. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  92665. })(BABYLON || (BABYLON = {}));
  92666. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  92667. var BABYLON;
  92668. (function (BABYLON) {
  92669. /**
  92670. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  92671. */
  92672. var GizmoManager = /** @class */ (function () {
  92673. /**
  92674. * Instatiates a gizmo manager
  92675. * @param scene the scene to overlay the gizmos on top of
  92676. */
  92677. function GizmoManager(scene) {
  92678. var _this = this;
  92679. this.scene = scene;
  92680. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  92681. this._pointerObserver = null;
  92682. this._attachedMesh = null;
  92683. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  92684. this._dragBehavior = new BABYLON.SixDofDragBehavior();
  92685. /**
  92686. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  92687. */
  92688. this.attachableMeshes = null;
  92689. /**
  92690. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  92691. */
  92692. this.usePointerToAttachGizmos = true;
  92693. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  92694. // Instatiate/dispose gizmos based on pointer actions
  92695. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  92696. if (!_this.usePointerToAttachGizmos) {
  92697. return;
  92698. }
  92699. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  92700. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  92701. var node = pointerInfo.pickInfo.pickedMesh;
  92702. if (_this.attachableMeshes == null) {
  92703. // Attach to the most parent node
  92704. while (node && node.parent != null) {
  92705. node = node.parent;
  92706. }
  92707. }
  92708. else {
  92709. // Attach to the parent node that is an attachableMesh
  92710. var found = false;
  92711. _this.attachableMeshes.forEach(function (mesh) {
  92712. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  92713. node = mesh;
  92714. found = true;
  92715. }
  92716. });
  92717. if (!found) {
  92718. node = null;
  92719. }
  92720. }
  92721. if (node instanceof BABYLON.AbstractMesh) {
  92722. _this.attachToMesh(node);
  92723. }
  92724. else {
  92725. _this.attachToMesh(null);
  92726. }
  92727. }
  92728. else {
  92729. _this.attachToMesh(null);
  92730. }
  92731. }
  92732. });
  92733. }
  92734. /**
  92735. * Attaches a set of gizmos to the specified mesh
  92736. * @param mesh The mesh the gizmo's should be attached to
  92737. */
  92738. GizmoManager.prototype.attachToMesh = function (mesh) {
  92739. if (this._attachedMesh) {
  92740. this._attachedMesh.removeBehavior(this._dragBehavior);
  92741. }
  92742. this._attachedMesh = mesh;
  92743. for (var key in this.gizmos) {
  92744. var gizmo = (this.gizmos[key]);
  92745. if (gizmo && this._gizmosEnabled[key]) {
  92746. gizmo.attachedMesh = mesh;
  92747. }
  92748. }
  92749. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  92750. this._attachedMesh.addBehavior(this._dragBehavior);
  92751. }
  92752. };
  92753. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  92754. get: function () {
  92755. return this._gizmosEnabled.positionGizmo;
  92756. },
  92757. /**
  92758. * If the position gizmo is enabled
  92759. */
  92760. set: function (value) {
  92761. if (value) {
  92762. if (!this.gizmos.positionGizmo) {
  92763. this.gizmos.positionGizmo = new BABYLON.PositionGizmo();
  92764. this.gizmos.positionGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  92765. }
  92766. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  92767. }
  92768. else if (this.gizmos.positionGizmo) {
  92769. this.gizmos.positionGizmo.attachedMesh = null;
  92770. }
  92771. this._gizmosEnabled.positionGizmo = value;
  92772. },
  92773. enumerable: true,
  92774. configurable: true
  92775. });
  92776. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  92777. get: function () {
  92778. return this._gizmosEnabled.rotationGizmo;
  92779. },
  92780. /**
  92781. * If the rotation gizmo is enabled
  92782. */
  92783. set: function (value) {
  92784. if (value) {
  92785. if (!this.gizmos.rotationGizmo) {
  92786. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo();
  92787. this.gizmos.rotationGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  92788. }
  92789. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  92790. }
  92791. else if (this.gizmos.rotationGizmo) {
  92792. this.gizmos.rotationGizmo.attachedMesh = null;
  92793. }
  92794. this._gizmosEnabled.rotationGizmo = value;
  92795. },
  92796. enumerable: true,
  92797. configurable: true
  92798. });
  92799. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  92800. get: function () {
  92801. return this._gizmosEnabled.scaleGizmo;
  92802. },
  92803. /**
  92804. * If the scale gizmo is enabled
  92805. */
  92806. set: function (value) {
  92807. if (value) {
  92808. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo();
  92809. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  92810. }
  92811. else if (this.gizmos.scaleGizmo) {
  92812. this.gizmos.scaleGizmo.attachedMesh = null;
  92813. }
  92814. this._gizmosEnabled.scaleGizmo = value;
  92815. },
  92816. enumerable: true,
  92817. configurable: true
  92818. });
  92819. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  92820. get: function () {
  92821. return this._gizmosEnabled.boundingBoxGizmo;
  92822. },
  92823. /**
  92824. * If the boundingBox gizmo is enabled
  92825. */
  92826. set: function (value) {
  92827. if (value) {
  92828. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor);
  92829. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  92830. if (this._attachedMesh) {
  92831. this._attachedMesh.removeBehavior(this._dragBehavior);
  92832. this._attachedMesh.addBehavior(this._dragBehavior);
  92833. }
  92834. }
  92835. else if (this.gizmos.boundingBoxGizmo) {
  92836. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  92837. }
  92838. this._gizmosEnabled.boundingBoxGizmo = value;
  92839. },
  92840. enumerable: true,
  92841. configurable: true
  92842. });
  92843. /**
  92844. * Disposes of the gizmo manager
  92845. */
  92846. GizmoManager.prototype.dispose = function () {
  92847. this.scene.onPointerObservable.remove(this._pointerObserver);
  92848. for (var key in this.gizmos) {
  92849. var gizmo = (this.gizmos[key]);
  92850. if (gizmo) {
  92851. gizmo.dispose();
  92852. }
  92853. }
  92854. this._dragBehavior.detach();
  92855. };
  92856. return GizmoManager;
  92857. }());
  92858. BABYLON.GizmoManager = GizmoManager;
  92859. })(BABYLON || (BABYLON = {}));
  92860. //# sourceMappingURL=babylon.gizmoManager.js.map
  92861. var BABYLON;
  92862. (function (BABYLON) {
  92863. /**
  92864. * Defines a target to use with MorphTargetManager
  92865. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  92866. */
  92867. var MorphTarget = /** @class */ (function () {
  92868. /**
  92869. * Creates a new MorphTarget
  92870. * @param name defines the name of the target
  92871. * @param influence defines the influence to use
  92872. */
  92873. function MorphTarget(
  92874. /** defines the name of the target */
  92875. name, influence, scene) {
  92876. if (influence === void 0) { influence = 0; }
  92877. if (scene === void 0) { scene = null; }
  92878. this.name = name;
  92879. /**
  92880. * Gets or sets the list of animations
  92881. */
  92882. this.animations = new Array();
  92883. this._positions = null;
  92884. this._normals = null;
  92885. this._tangents = null;
  92886. /**
  92887. * Observable raised when the influence changes
  92888. */
  92889. this.onInfluenceChanged = new BABYLON.Observable();
  92890. this._animationPropertiesOverride = null;
  92891. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  92892. this.influence = influence;
  92893. }
  92894. Object.defineProperty(MorphTarget.prototype, "influence", {
  92895. /**
  92896. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  92897. */
  92898. get: function () {
  92899. return this._influence;
  92900. },
  92901. set: function (influence) {
  92902. if (this._influence === influence) {
  92903. return;
  92904. }
  92905. var previous = this._influence;
  92906. this._influence = influence;
  92907. if (this.onInfluenceChanged.hasObservers) {
  92908. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  92909. }
  92910. },
  92911. enumerable: true,
  92912. configurable: true
  92913. });
  92914. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  92915. /**
  92916. * Gets or sets the animation properties override
  92917. */
  92918. get: function () {
  92919. if (!this._animationPropertiesOverride && this._scene) {
  92920. return this._scene.animationPropertiesOverride;
  92921. }
  92922. return this._animationPropertiesOverride;
  92923. },
  92924. set: function (value) {
  92925. this._animationPropertiesOverride = value;
  92926. },
  92927. enumerable: true,
  92928. configurable: true
  92929. });
  92930. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  92931. /**
  92932. * Gets a boolean defining if the target contains position data
  92933. */
  92934. get: function () {
  92935. return !!this._positions;
  92936. },
  92937. enumerable: true,
  92938. configurable: true
  92939. });
  92940. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  92941. /**
  92942. * Gets a boolean defining if the target contains normal data
  92943. */
  92944. get: function () {
  92945. return !!this._normals;
  92946. },
  92947. enumerable: true,
  92948. configurable: true
  92949. });
  92950. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  92951. /**
  92952. * Gets a boolean defining if the target contains tangent data
  92953. */
  92954. get: function () {
  92955. return !!this._tangents;
  92956. },
  92957. enumerable: true,
  92958. configurable: true
  92959. });
  92960. /**
  92961. * Affects position data to this target
  92962. * @param data defines the position data to use
  92963. */
  92964. MorphTarget.prototype.setPositions = function (data) {
  92965. this._positions = data;
  92966. };
  92967. /**
  92968. * Gets the position data stored in this target
  92969. * @returns a FloatArray containing the position data (or null if not present)
  92970. */
  92971. MorphTarget.prototype.getPositions = function () {
  92972. return this._positions;
  92973. };
  92974. /**
  92975. * Affects normal data to this target
  92976. * @param data defines the normal data to use
  92977. */
  92978. MorphTarget.prototype.setNormals = function (data) {
  92979. this._normals = data;
  92980. };
  92981. /**
  92982. * Gets the normal data stored in this target
  92983. * @returns a FloatArray containing the normal data (or null if not present)
  92984. */
  92985. MorphTarget.prototype.getNormals = function () {
  92986. return this._normals;
  92987. };
  92988. /**
  92989. * Affects tangent data to this target
  92990. * @param data defines the tangent data to use
  92991. */
  92992. MorphTarget.prototype.setTangents = function (data) {
  92993. this._tangents = data;
  92994. };
  92995. /**
  92996. * Gets the tangent data stored in this target
  92997. * @returns a FloatArray containing the tangent data (or null if not present)
  92998. */
  92999. MorphTarget.prototype.getTangents = function () {
  93000. return this._tangents;
  93001. };
  93002. /**
  93003. * Serializes the current target into a Serialization object
  93004. * @returns the serialized object
  93005. */
  93006. MorphTarget.prototype.serialize = function () {
  93007. var serializationObject = {};
  93008. serializationObject.name = this.name;
  93009. serializationObject.influence = this.influence;
  93010. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  93011. if (this.hasNormals) {
  93012. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  93013. }
  93014. if (this.hasTangents) {
  93015. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  93016. }
  93017. // Animations
  93018. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  93019. return serializationObject;
  93020. };
  93021. // Statics
  93022. /**
  93023. * Creates a new target from serialized data
  93024. * @param serializationObject defines the serialized data to use
  93025. * @returns a new MorphTarget
  93026. */
  93027. MorphTarget.Parse = function (serializationObject) {
  93028. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  93029. result.setPositions(serializationObject.positions);
  93030. if (serializationObject.normals) {
  93031. result.setNormals(serializationObject.normals);
  93032. }
  93033. if (serializationObject.tangents) {
  93034. result.setTangents(serializationObject.tangents);
  93035. }
  93036. // Animations
  93037. if (serializationObject.animations) {
  93038. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  93039. var parsedAnimation = serializationObject.animations[animationIndex];
  93040. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  93041. }
  93042. }
  93043. return result;
  93044. };
  93045. /**
  93046. * Creates a MorphTarget from mesh data
  93047. * @param mesh defines the source mesh
  93048. * @param name defines the name to use for the new target
  93049. * @param influence defines the influence to attach to the target
  93050. * @returns a new MorphTarget
  93051. */
  93052. MorphTarget.FromMesh = function (mesh, name, influence) {
  93053. if (!name) {
  93054. name = mesh.name;
  93055. }
  93056. var result = new MorphTarget(name, influence, mesh.getScene());
  93057. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  93058. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  93059. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  93060. }
  93061. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  93062. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  93063. }
  93064. return result;
  93065. };
  93066. return MorphTarget;
  93067. }());
  93068. BABYLON.MorphTarget = MorphTarget;
  93069. })(BABYLON || (BABYLON = {}));
  93070. //# sourceMappingURL=babylon.morphTarget.js.map
  93071. var BABYLON;
  93072. (function (BABYLON) {
  93073. /**
  93074. * This class is used to deform meshes using morphing between different targets
  93075. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  93076. */
  93077. var MorphTargetManager = /** @class */ (function () {
  93078. /**
  93079. * Creates a new MorphTargetManager
  93080. * @param scene defines the current scene
  93081. */
  93082. function MorphTargetManager(scene) {
  93083. if (scene === void 0) { scene = null; }
  93084. this._targets = new Array();
  93085. this._targetObservable = new Array();
  93086. this._activeTargets = new BABYLON.SmartArray(16);
  93087. this._supportsNormals = false;
  93088. this._supportsTangents = false;
  93089. this._vertexCount = 0;
  93090. this._uniqueId = 0;
  93091. this._tempInfluences = new Array();
  93092. if (!scene) {
  93093. scene = BABYLON.Engine.LastCreatedScene;
  93094. }
  93095. this._scene = scene;
  93096. if (this._scene) {
  93097. this._scene.morphTargetManagers.push(this);
  93098. this._uniqueId = this._scene.getUniqueId();
  93099. }
  93100. }
  93101. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  93102. /**
  93103. * Gets the unique ID of this manager
  93104. */
  93105. get: function () {
  93106. return this._uniqueId;
  93107. },
  93108. enumerable: true,
  93109. configurable: true
  93110. });
  93111. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  93112. /**
  93113. * Gets the number of vertices handled by this manager
  93114. */
  93115. get: function () {
  93116. return this._vertexCount;
  93117. },
  93118. enumerable: true,
  93119. configurable: true
  93120. });
  93121. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  93122. /**
  93123. * Gets a boolean indicating if this manager supports morphing of normals
  93124. */
  93125. get: function () {
  93126. return this._supportsNormals;
  93127. },
  93128. enumerable: true,
  93129. configurable: true
  93130. });
  93131. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  93132. /**
  93133. * Gets a boolean indicating if this manager supports morphing of tangents
  93134. */
  93135. get: function () {
  93136. return this._supportsTangents;
  93137. },
  93138. enumerable: true,
  93139. configurable: true
  93140. });
  93141. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  93142. /**
  93143. * Gets the number of targets stored in this manager
  93144. */
  93145. get: function () {
  93146. return this._targets.length;
  93147. },
  93148. enumerable: true,
  93149. configurable: true
  93150. });
  93151. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  93152. /**
  93153. * Gets the number of influencers (ie. the number of targets with influences > 0)
  93154. */
  93155. get: function () {
  93156. return this._activeTargets.length;
  93157. },
  93158. enumerable: true,
  93159. configurable: true
  93160. });
  93161. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  93162. /**
  93163. * Gets the list of influences (one per target)
  93164. */
  93165. get: function () {
  93166. return this._influences;
  93167. },
  93168. enumerable: true,
  93169. configurable: true
  93170. });
  93171. /**
  93172. * Gets the active target at specified index. An active target is a target with an influence > 0
  93173. * @param index defines the index to check
  93174. * @returns the requested target
  93175. */
  93176. MorphTargetManager.prototype.getActiveTarget = function (index) {
  93177. return this._activeTargets.data[index];
  93178. };
  93179. /**
  93180. * Gets the target at specified index
  93181. * @param index defines the index to check
  93182. * @returns the requested target
  93183. */
  93184. MorphTargetManager.prototype.getTarget = function (index) {
  93185. return this._targets[index];
  93186. };
  93187. /**
  93188. * Add a new target to this manager
  93189. * @param target defines the target to add
  93190. */
  93191. MorphTargetManager.prototype.addTarget = function (target) {
  93192. var _this = this;
  93193. this._targets.push(target);
  93194. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  93195. _this._syncActiveTargets(needUpdate);
  93196. }));
  93197. this._syncActiveTargets(true);
  93198. };
  93199. /**
  93200. * Removes a target from the manager
  93201. * @param target defines the target to remove
  93202. */
  93203. MorphTargetManager.prototype.removeTarget = function (target) {
  93204. var index = this._targets.indexOf(target);
  93205. if (index >= 0) {
  93206. this._targets.splice(index, 1);
  93207. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  93208. this._syncActiveTargets(true);
  93209. }
  93210. };
  93211. /**
  93212. * Serializes the current manager into a Serialization object
  93213. * @returns the serialized object
  93214. */
  93215. MorphTargetManager.prototype.serialize = function () {
  93216. var serializationObject = {};
  93217. serializationObject.id = this.uniqueId;
  93218. serializationObject.targets = [];
  93219. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  93220. var target = _a[_i];
  93221. serializationObject.targets.push(target.serialize());
  93222. }
  93223. return serializationObject;
  93224. };
  93225. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  93226. var influenceCount = 0;
  93227. this._activeTargets.reset();
  93228. this._supportsNormals = true;
  93229. this._supportsTangents = true;
  93230. this._vertexCount = 0;
  93231. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  93232. var target = _a[_i];
  93233. this._activeTargets.push(target);
  93234. this._tempInfluences[influenceCount++] = target.influence;
  93235. var positions = target.getPositions();
  93236. if (positions) {
  93237. this._supportsNormals = this._supportsNormals && target.hasNormals;
  93238. this._supportsTangents = this._supportsTangents && target.hasTangents;
  93239. var vertexCount = positions.length / 3;
  93240. if (this._vertexCount === 0) {
  93241. this._vertexCount = vertexCount;
  93242. }
  93243. else if (this._vertexCount !== vertexCount) {
  93244. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  93245. return;
  93246. }
  93247. }
  93248. }
  93249. if (!this._influences || this._influences.length !== influenceCount) {
  93250. this._influences = new Float32Array(influenceCount);
  93251. }
  93252. for (var index = 0; index < influenceCount; index++) {
  93253. this._influences[index] = this._tempInfluences[index];
  93254. }
  93255. if (needUpdate) {
  93256. this.synchronize();
  93257. }
  93258. };
  93259. /**
  93260. * Syncrhonize the targets with all the meshes using this morph target manager
  93261. */
  93262. MorphTargetManager.prototype.synchronize = function () {
  93263. if (!this._scene) {
  93264. return;
  93265. }
  93266. // Flag meshes as dirty to resync with the active targets
  93267. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  93268. var mesh = _a[_i];
  93269. if (mesh.morphTargetManager === this) {
  93270. mesh._syncGeometryWithMorphTargetManager();
  93271. }
  93272. }
  93273. };
  93274. // Statics
  93275. /**
  93276. * Creates a new MorphTargetManager from serialized data
  93277. * @param serializationObject defines the serialized data
  93278. * @param scene defines the hosting scene
  93279. * @returns the new MorphTargetManager
  93280. */
  93281. MorphTargetManager.Parse = function (serializationObject, scene) {
  93282. var result = new MorphTargetManager(scene);
  93283. result._uniqueId = serializationObject.id;
  93284. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  93285. var targetData = _a[_i];
  93286. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  93287. }
  93288. return result;
  93289. };
  93290. return MorphTargetManager;
  93291. }());
  93292. BABYLON.MorphTargetManager = MorphTargetManager;
  93293. })(BABYLON || (BABYLON = {}));
  93294. //# sourceMappingURL=babylon.morphTargetManager.js.map
  93295. var BABYLON;
  93296. (function (BABYLON) {
  93297. var Octree = /** @class */ (function () {
  93298. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  93299. if (maxDepth === void 0) { maxDepth = 2; }
  93300. this.maxDepth = maxDepth;
  93301. this.dynamicContent = new Array();
  93302. this._maxBlockCapacity = maxBlockCapacity || 64;
  93303. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  93304. this._creationFunc = creationFunc;
  93305. }
  93306. // Methods
  93307. Octree.prototype.update = function (worldMin, worldMax, entries) {
  93308. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  93309. };
  93310. Octree.prototype.addMesh = function (entry) {
  93311. for (var index = 0; index < this.blocks.length; index++) {
  93312. var block = this.blocks[index];
  93313. block.addEntry(entry);
  93314. }
  93315. };
  93316. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  93317. this._selectionContent.reset();
  93318. for (var index = 0; index < this.blocks.length; index++) {
  93319. var block = this.blocks[index];
  93320. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  93321. }
  93322. if (allowDuplicate) {
  93323. this._selectionContent.concat(this.dynamicContent);
  93324. }
  93325. else {
  93326. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  93327. }
  93328. return this._selectionContent;
  93329. };
  93330. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  93331. this._selectionContent.reset();
  93332. for (var index = 0; index < this.blocks.length; index++) {
  93333. var block = this.blocks[index];
  93334. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  93335. }
  93336. if (allowDuplicate) {
  93337. this._selectionContent.concat(this.dynamicContent);
  93338. }
  93339. else {
  93340. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  93341. }
  93342. return this._selectionContent;
  93343. };
  93344. Octree.prototype.intersectsRay = function (ray) {
  93345. this._selectionContent.reset();
  93346. for (var index = 0; index < this.blocks.length; index++) {
  93347. var block = this.blocks[index];
  93348. block.intersectsRay(ray, this._selectionContent);
  93349. }
  93350. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  93351. return this._selectionContent;
  93352. };
  93353. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  93354. target.blocks = new Array();
  93355. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  93356. // Segmenting space
  93357. for (var x = 0; x < 2; x++) {
  93358. for (var y = 0; y < 2; y++) {
  93359. for (var z = 0; z < 2; z++) {
  93360. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  93361. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  93362. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  93363. block.addEntries(entries);
  93364. target.blocks.push(block);
  93365. }
  93366. }
  93367. }
  93368. };
  93369. Octree.CreationFuncForMeshes = function (entry, block) {
  93370. var boundingInfo = entry.getBoundingInfo();
  93371. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  93372. block.entries.push(entry);
  93373. }
  93374. };
  93375. Octree.CreationFuncForSubMeshes = function (entry, block) {
  93376. var boundingInfo = entry.getBoundingInfo();
  93377. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  93378. block.entries.push(entry);
  93379. }
  93380. };
  93381. return Octree;
  93382. }());
  93383. BABYLON.Octree = Octree;
  93384. })(BABYLON || (BABYLON = {}));
  93385. //# sourceMappingURL=babylon.octree.js.map
  93386. var BABYLON;
  93387. (function (BABYLON) {
  93388. var OctreeBlock = /** @class */ (function () {
  93389. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  93390. this.entries = new Array();
  93391. this._boundingVectors = new Array();
  93392. this._capacity = capacity;
  93393. this._depth = depth;
  93394. this._maxDepth = maxDepth;
  93395. this._creationFunc = creationFunc;
  93396. this._minPoint = minPoint;
  93397. this._maxPoint = maxPoint;
  93398. this._boundingVectors.push(minPoint.clone());
  93399. this._boundingVectors.push(maxPoint.clone());
  93400. this._boundingVectors.push(minPoint.clone());
  93401. this._boundingVectors[2].x = maxPoint.x;
  93402. this._boundingVectors.push(minPoint.clone());
  93403. this._boundingVectors[3].y = maxPoint.y;
  93404. this._boundingVectors.push(minPoint.clone());
  93405. this._boundingVectors[4].z = maxPoint.z;
  93406. this._boundingVectors.push(maxPoint.clone());
  93407. this._boundingVectors[5].z = minPoint.z;
  93408. this._boundingVectors.push(maxPoint.clone());
  93409. this._boundingVectors[6].x = minPoint.x;
  93410. this._boundingVectors.push(maxPoint.clone());
  93411. this._boundingVectors[7].y = minPoint.y;
  93412. }
  93413. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  93414. // Property
  93415. get: function () {
  93416. return this._capacity;
  93417. },
  93418. enumerable: true,
  93419. configurable: true
  93420. });
  93421. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  93422. get: function () {
  93423. return this._minPoint;
  93424. },
  93425. enumerable: true,
  93426. configurable: true
  93427. });
  93428. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  93429. get: function () {
  93430. return this._maxPoint;
  93431. },
  93432. enumerable: true,
  93433. configurable: true
  93434. });
  93435. // Methods
  93436. OctreeBlock.prototype.addEntry = function (entry) {
  93437. if (this.blocks) {
  93438. for (var index = 0; index < this.blocks.length; index++) {
  93439. var block = this.blocks[index];
  93440. block.addEntry(entry);
  93441. }
  93442. return;
  93443. }
  93444. this._creationFunc(entry, this);
  93445. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  93446. this.createInnerBlocks();
  93447. }
  93448. };
  93449. OctreeBlock.prototype.addEntries = function (entries) {
  93450. for (var index = 0; index < entries.length; index++) {
  93451. var mesh = entries[index];
  93452. this.addEntry(mesh);
  93453. }
  93454. };
  93455. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  93456. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  93457. if (this.blocks) {
  93458. for (var index = 0; index < this.blocks.length; index++) {
  93459. var block = this.blocks[index];
  93460. block.select(frustumPlanes, selection, allowDuplicate);
  93461. }
  93462. return;
  93463. }
  93464. if (allowDuplicate) {
  93465. selection.concat(this.entries);
  93466. }
  93467. else {
  93468. selection.concatWithNoDuplicate(this.entries);
  93469. }
  93470. }
  93471. };
  93472. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  93473. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  93474. if (this.blocks) {
  93475. for (var index = 0; index < this.blocks.length; index++) {
  93476. var block = this.blocks[index];
  93477. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  93478. }
  93479. return;
  93480. }
  93481. if (allowDuplicate) {
  93482. selection.concat(this.entries);
  93483. }
  93484. else {
  93485. selection.concatWithNoDuplicate(this.entries);
  93486. }
  93487. }
  93488. };
  93489. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  93490. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  93491. if (this.blocks) {
  93492. for (var index = 0; index < this.blocks.length; index++) {
  93493. var block = this.blocks[index];
  93494. block.intersectsRay(ray, selection);
  93495. }
  93496. return;
  93497. }
  93498. selection.concatWithNoDuplicate(this.entries);
  93499. }
  93500. };
  93501. OctreeBlock.prototype.createInnerBlocks = function () {
  93502. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  93503. };
  93504. return OctreeBlock;
  93505. }());
  93506. BABYLON.OctreeBlock = OctreeBlock;
  93507. })(BABYLON || (BABYLON = {}));
  93508. //# sourceMappingURL=babylon.octreeBlock.js.map
  93509. var BABYLON;
  93510. (function (BABYLON) {
  93511. /**
  93512. * Postprocess used to generate anaglyphic rendering
  93513. */
  93514. var AnaglyphPostProcess = /** @class */ (function (_super) {
  93515. __extends(AnaglyphPostProcess, _super);
  93516. /**
  93517. * Creates a new AnaglyphPostProcess
  93518. * @param name defines postprocess name
  93519. * @param options defines creation options or target ratio scale
  93520. * @param rigCameras defines cameras using this postprocess
  93521. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  93522. * @param engine defines hosting engine
  93523. * @param reusable defines if the postprocess will be reused multiple times per frame
  93524. */
  93525. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  93526. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  93527. _this._passedProcess = rigCameras[0]._rigPostProcess;
  93528. _this.onApplyObservable.add(function (effect) {
  93529. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  93530. });
  93531. return _this;
  93532. }
  93533. return AnaglyphPostProcess;
  93534. }(BABYLON.PostProcess));
  93535. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  93536. })(BABYLON || (BABYLON = {}));
  93537. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  93538. var BABYLON;
  93539. (function (BABYLON) {
  93540. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  93541. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  93542. });
  93543. /**
  93544. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  93545. */
  93546. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  93547. __extends(AnaglyphArcRotateCamera, _super);
  93548. /**
  93549. * Creates a new AnaglyphArcRotateCamera
  93550. * @param name defines camera name
  93551. * @param alpha defines alpha angle (in radians)
  93552. * @param beta defines beta angle (in radians)
  93553. * @param radius defines radius
  93554. * @param target defines camera target
  93555. * @param interaxialDistance defines distance between each color axis
  93556. * @param scene defines the hosting scene
  93557. */
  93558. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  93559. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  93560. _this.interaxialDistance = interaxialDistance;
  93561. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  93562. return _this;
  93563. }
  93564. /**
  93565. * Gets camera class name
  93566. * @returns AnaglyphArcRotateCamera
  93567. */
  93568. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  93569. return "AnaglyphArcRotateCamera";
  93570. };
  93571. return AnaglyphArcRotateCamera;
  93572. }(BABYLON.ArcRotateCamera));
  93573. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  93574. })(BABYLON || (BABYLON = {}));
  93575. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  93576. var BABYLON;
  93577. (function (BABYLON) {
  93578. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  93579. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  93580. });
  93581. /**
  93582. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  93583. */
  93584. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  93585. __extends(AnaglyphFreeCamera, _super);
  93586. /**
  93587. * Creates a new AnaglyphFreeCamera
  93588. * @param name defines camera name
  93589. * @param position defines initial position
  93590. * @param interaxialDistance defines distance between each color axis
  93591. * @param scene defines the hosting scene
  93592. */
  93593. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  93594. var _this = _super.call(this, name, position, scene) || this;
  93595. _this.interaxialDistance = interaxialDistance;
  93596. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  93597. return _this;
  93598. }
  93599. /**
  93600. * Gets camera class name
  93601. * @returns AnaglyphFreeCamera
  93602. */
  93603. AnaglyphFreeCamera.prototype.getClassName = function () {
  93604. return "AnaglyphFreeCamera";
  93605. };
  93606. return AnaglyphFreeCamera;
  93607. }(BABYLON.FreeCamera));
  93608. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  93609. })(BABYLON || (BABYLON = {}));
  93610. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  93611. var BABYLON;
  93612. (function (BABYLON) {
  93613. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  93614. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  93615. });
  93616. /**
  93617. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  93618. */
  93619. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  93620. __extends(AnaglyphGamepadCamera, _super);
  93621. /**
  93622. * Creates a new AnaglyphGamepadCamera
  93623. * @param name defines camera name
  93624. * @param position defines initial position
  93625. * @param interaxialDistance defines distance between each color axis
  93626. * @param scene defines the hosting scene
  93627. */
  93628. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  93629. var _this = _super.call(this, name, position, scene) || this;
  93630. _this.interaxialDistance = interaxialDistance;
  93631. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  93632. return _this;
  93633. }
  93634. /**
  93635. * Gets camera class name
  93636. * @returns AnaglyphGamepadCamera
  93637. */
  93638. AnaglyphGamepadCamera.prototype.getClassName = function () {
  93639. return "AnaglyphGamepadCamera";
  93640. };
  93641. return AnaglyphGamepadCamera;
  93642. }(BABYLON.GamepadCamera));
  93643. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  93644. })(BABYLON || (BABYLON = {}));
  93645. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  93646. var BABYLON;
  93647. (function (BABYLON) {
  93648. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  93649. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  93650. });
  93651. /**
  93652. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  93653. */
  93654. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  93655. __extends(AnaglyphUniversalCamera, _super);
  93656. /**
  93657. * Creates a new AnaglyphUniversalCamera
  93658. * @param name defines camera name
  93659. * @param position defines initial position
  93660. * @param interaxialDistance defines distance between each color axis
  93661. * @param scene defines the hosting scene
  93662. */
  93663. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  93664. var _this = _super.call(this, name, position, scene) || this;
  93665. _this.interaxialDistance = interaxialDistance;
  93666. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  93667. return _this;
  93668. }
  93669. /**
  93670. * Gets camera class name
  93671. * @returns AnaglyphUniversalCamera
  93672. */
  93673. AnaglyphUniversalCamera.prototype.getClassName = function () {
  93674. return "AnaglyphUniversalCamera";
  93675. };
  93676. return AnaglyphUniversalCamera;
  93677. }(BABYLON.UniversalCamera));
  93678. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  93679. })(BABYLON || (BABYLON = {}));
  93680. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  93681. var BABYLON;
  93682. (function (BABYLON) {
  93683. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  93684. __extends(StereoscopicInterlacePostProcess, _super);
  93685. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  93686. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  93687. _this._passedProcess = rigCameras[0]._rigPostProcess;
  93688. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  93689. _this.onSizeChangedObservable.add(function () {
  93690. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  93691. });
  93692. _this.onApplyObservable.add(function (effect) {
  93693. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  93694. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  93695. });
  93696. return _this;
  93697. }
  93698. return StereoscopicInterlacePostProcess;
  93699. }(BABYLON.PostProcess));
  93700. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  93701. })(BABYLON || (BABYLON = {}));
  93702. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  93703. var BABYLON;
  93704. (function (BABYLON) {
  93705. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  93706. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  93707. });
  93708. /**
  93709. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  93710. */
  93711. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  93712. __extends(StereoscopicArcRotateCamera, _super);
  93713. /**
  93714. * Creates a new StereoscopicArcRotateCamera
  93715. * @param name defines camera name
  93716. * @param alpha defines alpha angle (in radians)
  93717. * @param beta defines beta angle (in radians)
  93718. * @param radius defines radius
  93719. * @param target defines camera target
  93720. * @param interaxialDistance defines distance between each color axis
  93721. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  93722. * @param scene defines the hosting scene
  93723. */
  93724. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  93725. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  93726. _this.interaxialDistance = interaxialDistance;
  93727. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  93728. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  93729. return _this;
  93730. }
  93731. /**
  93732. * Gets camera class name
  93733. * @returns StereoscopicArcRotateCamera
  93734. */
  93735. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  93736. return "StereoscopicArcRotateCamera";
  93737. };
  93738. return StereoscopicArcRotateCamera;
  93739. }(BABYLON.ArcRotateCamera));
  93740. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  93741. })(BABYLON || (BABYLON = {}));
  93742. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  93743. var BABYLON;
  93744. (function (BABYLON) {
  93745. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  93746. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  93747. });
  93748. /**
  93749. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  93750. */
  93751. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  93752. __extends(StereoscopicFreeCamera, _super);
  93753. /**
  93754. * Creates a new StereoscopicFreeCamera
  93755. * @param name defines camera name
  93756. * @param position defines initial position
  93757. * @param interaxialDistance defines distance between each color axis
  93758. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  93759. * @param scene defines the hosting scene
  93760. */
  93761. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  93762. var _this = _super.call(this, name, position, scene) || this;
  93763. _this.interaxialDistance = interaxialDistance;
  93764. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  93765. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  93766. return _this;
  93767. }
  93768. /**
  93769. * Gets camera class name
  93770. * @returns StereoscopicFreeCamera
  93771. */
  93772. StereoscopicFreeCamera.prototype.getClassName = function () {
  93773. return "StereoscopicFreeCamera";
  93774. };
  93775. return StereoscopicFreeCamera;
  93776. }(BABYLON.FreeCamera));
  93777. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  93778. })(BABYLON || (BABYLON = {}));
  93779. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  93780. var BABYLON;
  93781. (function (BABYLON) {
  93782. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  93783. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  93784. });
  93785. /**
  93786. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  93787. */
  93788. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  93789. __extends(StereoscopicGamepadCamera, _super);
  93790. /**
  93791. * Creates a new StereoscopicGamepadCamera
  93792. * @param name defines camera name
  93793. * @param position defines initial position
  93794. * @param interaxialDistance defines distance between each color axis
  93795. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  93796. * @param scene defines the hosting scene
  93797. */
  93798. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  93799. var _this = _super.call(this, name, position, scene) || this;
  93800. _this.interaxialDistance = interaxialDistance;
  93801. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  93802. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  93803. return _this;
  93804. }
  93805. /**
  93806. * Gets camera class name
  93807. * @returns StereoscopicGamepadCamera
  93808. */
  93809. StereoscopicGamepadCamera.prototype.getClassName = function () {
  93810. return "StereoscopicGamepadCamera";
  93811. };
  93812. return StereoscopicGamepadCamera;
  93813. }(BABYLON.GamepadCamera));
  93814. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  93815. })(BABYLON || (BABYLON = {}));
  93816. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  93817. var BABYLON;
  93818. (function (BABYLON) {
  93819. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  93820. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  93821. });
  93822. /**
  93823. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  93824. */
  93825. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  93826. __extends(StereoscopicUniversalCamera, _super);
  93827. /**
  93828. * Creates a new StereoscopicUniversalCamera
  93829. * @param name defines camera name
  93830. * @param position defines initial position
  93831. * @param interaxialDistance defines distance between each color axis
  93832. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  93833. * @param scene defines the hosting scene
  93834. */
  93835. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  93836. var _this = _super.call(this, name, position, scene) || this;
  93837. _this.interaxialDistance = interaxialDistance;
  93838. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  93839. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  93840. return _this;
  93841. }
  93842. /**
  93843. * Gets camera class name
  93844. * @returns StereoscopicUniversalCamera
  93845. */
  93846. StereoscopicUniversalCamera.prototype.getClassName = function () {
  93847. return "StereoscopicUniversalCamera";
  93848. };
  93849. return StereoscopicUniversalCamera;
  93850. }(BABYLON.UniversalCamera));
  93851. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  93852. })(BABYLON || (BABYLON = {}));
  93853. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  93854. var BABYLON;
  93855. (function (BABYLON) {
  93856. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  93857. __extends(VRDistortionCorrectionPostProcess, _super);
  93858. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  93859. var _this = _super.call(this, name, "vrDistortionCorrection", [
  93860. 'LensCenter',
  93861. 'Scale',
  93862. 'ScaleIn',
  93863. 'HmdWarpParam'
  93864. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  93865. _this._isRightEye = isRightEye;
  93866. _this._distortionFactors = vrMetrics.distortionK;
  93867. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  93868. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  93869. _this.adaptScaleToCurrentViewport = true;
  93870. _this.onSizeChangedObservable.add(function () {
  93871. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  93872. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  93873. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  93874. });
  93875. _this.onApplyObservable.add(function (effect) {
  93876. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  93877. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  93878. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  93879. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  93880. });
  93881. return _this;
  93882. }
  93883. return VRDistortionCorrectionPostProcess;
  93884. }(BABYLON.PostProcess));
  93885. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  93886. })(BABYLON || (BABYLON = {}));
  93887. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  93888. var BABYLON;
  93889. (function (BABYLON) {
  93890. /**
  93891. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  93892. * Screen rotation is taken into account.
  93893. */
  93894. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  93895. function FreeCameraDeviceOrientationInput() {
  93896. var _this = this;
  93897. this._screenOrientationAngle = 0;
  93898. this._screenQuaternion = new BABYLON.Quaternion();
  93899. this._alpha = 0;
  93900. this._beta = 0;
  93901. this._gamma = 0;
  93902. this._orientationChanged = function () {
  93903. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  93904. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  93905. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  93906. };
  93907. this._deviceOrientation = function (evt) {
  93908. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  93909. _this._beta = evt.beta !== null ? evt.beta : 0;
  93910. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  93911. };
  93912. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  93913. this._orientationChanged();
  93914. }
  93915. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  93916. get: function () {
  93917. return this._camera;
  93918. },
  93919. set: function (camera) {
  93920. this._camera = camera;
  93921. if (this._camera != null && !this._camera.rotationQuaternion) {
  93922. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  93923. }
  93924. },
  93925. enumerable: true,
  93926. configurable: true
  93927. });
  93928. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  93929. window.addEventListener("orientationchange", this._orientationChanged);
  93930. window.addEventListener("deviceorientation", this._deviceOrientation);
  93931. //In certain cases, the attach control is called AFTER orientation was changed,
  93932. //So this is needed.
  93933. this._orientationChanged();
  93934. };
  93935. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  93936. window.removeEventListener("orientationchange", this._orientationChanged);
  93937. window.removeEventListener("deviceorientation", this._deviceOrientation);
  93938. };
  93939. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  93940. //if no device orientation provided, don't update the rotation.
  93941. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  93942. if (!this._alpha)
  93943. return;
  93944. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  93945. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  93946. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  93947. //Mirror on XY Plane
  93948. this._camera.rotationQuaternion.z *= -1;
  93949. this._camera.rotationQuaternion.w *= -1;
  93950. };
  93951. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  93952. return "FreeCameraDeviceOrientationInput";
  93953. };
  93954. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  93955. return "deviceOrientation";
  93956. };
  93957. return FreeCameraDeviceOrientationInput;
  93958. }());
  93959. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  93960. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  93961. })(BABYLON || (BABYLON = {}));
  93962. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  93963. var BABYLON;
  93964. (function (BABYLON) {
  93965. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  93966. function ArcRotateCameraVRDeviceOrientationInput() {
  93967. this.alphaCorrection = 1;
  93968. this.betaCorrection = 1;
  93969. this.gammaCorrection = 1;
  93970. this._alpha = 0;
  93971. this._gamma = 0;
  93972. this._dirty = false;
  93973. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  93974. }
  93975. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  93976. this.camera.attachControl(element, noPreventDefault);
  93977. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  93978. };
  93979. /** @hidden */
  93980. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  93981. if (evt.alpha !== null) {
  93982. this._alpha = +evt.alpha | 0;
  93983. }
  93984. if (evt.gamma !== null) {
  93985. this._gamma = +evt.gamma | 0;
  93986. }
  93987. this._dirty = true;
  93988. };
  93989. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  93990. if (this._dirty) {
  93991. this._dirty = false;
  93992. if (this._gamma < 0) {
  93993. this._gamma = 180 + this._gamma;
  93994. }
  93995. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  93996. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  93997. }
  93998. };
  93999. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  94000. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  94001. };
  94002. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  94003. return "ArcRotateCameraVRDeviceOrientationInput";
  94004. };
  94005. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  94006. return "VRDeviceOrientation";
  94007. };
  94008. return ArcRotateCameraVRDeviceOrientationInput;
  94009. }());
  94010. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  94011. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  94012. })(BABYLON || (BABYLON = {}));
  94013. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  94014. var BABYLON;
  94015. (function (BABYLON) {
  94016. var VRCameraMetrics = /** @class */ (function () {
  94017. function VRCameraMetrics() {
  94018. this.compensateDistortion = true;
  94019. }
  94020. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  94021. get: function () {
  94022. return this.hResolution / (2 * this.vResolution);
  94023. },
  94024. enumerable: true,
  94025. configurable: true
  94026. });
  94027. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  94028. get: function () {
  94029. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  94030. },
  94031. enumerable: true,
  94032. configurable: true
  94033. });
  94034. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  94035. get: function () {
  94036. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  94037. var h = (4 * meters) / this.hScreenSize;
  94038. return BABYLON.Matrix.Translation(h, 0, 0);
  94039. },
  94040. enumerable: true,
  94041. configurable: true
  94042. });
  94043. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  94044. get: function () {
  94045. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  94046. var h = (4 * meters) / this.hScreenSize;
  94047. return BABYLON.Matrix.Translation(-h, 0, 0);
  94048. },
  94049. enumerable: true,
  94050. configurable: true
  94051. });
  94052. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  94053. get: function () {
  94054. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  94055. },
  94056. enumerable: true,
  94057. configurable: true
  94058. });
  94059. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  94060. get: function () {
  94061. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  94062. },
  94063. enumerable: true,
  94064. configurable: true
  94065. });
  94066. VRCameraMetrics.GetDefault = function () {
  94067. var result = new VRCameraMetrics();
  94068. result.hResolution = 1280;
  94069. result.vResolution = 800;
  94070. result.hScreenSize = 0.149759993;
  94071. result.vScreenSize = 0.0935999975;
  94072. result.vScreenCenter = 0.0467999987;
  94073. result.eyeToScreenDistance = 0.0410000011;
  94074. result.lensSeparationDistance = 0.0635000020;
  94075. result.interpupillaryDistance = 0.0640000030;
  94076. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  94077. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  94078. result.postProcessScaleFactor = 1.714605507808412;
  94079. result.lensCenterOffset = 0.151976421;
  94080. return result;
  94081. };
  94082. return VRCameraMetrics;
  94083. }());
  94084. BABYLON.VRCameraMetrics = VRCameraMetrics;
  94085. })(BABYLON || (BABYLON = {}));
  94086. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  94087. var BABYLON;
  94088. (function (BABYLON) {
  94089. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  94090. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  94091. });
  94092. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  94093. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  94094. });
  94095. /**
  94096. * This represents a WebVR camera.
  94097. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  94098. * @example http://doc.babylonjs.com/how_to/webvr_camera
  94099. */
  94100. var WebVRFreeCamera = /** @class */ (function (_super) {
  94101. __extends(WebVRFreeCamera, _super);
  94102. /**
  94103. * Instantiates a WebVRFreeCamera.
  94104. * @param name The name of the WebVRFreeCamera
  94105. * @param position The starting anchor position for the camera
  94106. * @param scene The scene the camera belongs to
  94107. * @param webVROptions a set of customizable options for the webVRCamera
  94108. */
  94109. function WebVRFreeCamera(name, position, scene, webVROptions) {
  94110. if (webVROptions === void 0) { webVROptions = {}; }
  94111. var _this = _super.call(this, name, position, scene) || this;
  94112. _this.webVROptions = webVROptions;
  94113. /**
  94114. * @hidden
  94115. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  94116. */
  94117. _this._vrDevice = null;
  94118. /**
  94119. * The rawPose of the vrDevice.
  94120. */
  94121. _this.rawPose = null;
  94122. _this._specsVersion = "1.1";
  94123. _this._attached = false;
  94124. _this._descendants = [];
  94125. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  94126. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  94127. /** @hidden */
  94128. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  94129. _this._standingMatrix = null;
  94130. /**
  94131. * Represents device position in babylon space.
  94132. */
  94133. _this.devicePosition = BABYLON.Vector3.Zero();
  94134. /**
  94135. * Represents device rotation in babylon space.
  94136. */
  94137. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  94138. /**
  94139. * The scale of the device to be used when translating from device space to babylon space.
  94140. */
  94141. _this.deviceScaleFactor = 1;
  94142. _this._deviceToWorld = BABYLON.Matrix.Identity();
  94143. _this._worldToDevice = BABYLON.Matrix.Identity();
  94144. /**
  94145. * References to the webVR controllers for the vrDevice.
  94146. */
  94147. _this.controllers = [];
  94148. /**
  94149. * Emits an event when a controller is attached.
  94150. */
  94151. _this.onControllersAttachedObservable = new BABYLON.Observable();
  94152. /**
  94153. * Emits an event when a controller's mesh has been loaded;
  94154. */
  94155. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  94156. /**
  94157. * Emits an event when the HMD's pose has been updated.
  94158. */
  94159. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  94160. _this._poseSet = false;
  94161. /**
  94162. * If the rig cameras be used as parent instead of this camera.
  94163. */
  94164. _this.rigParenting = true;
  94165. _this._defaultHeight = undefined;
  94166. _this._workingVector = BABYLON.Vector3.Zero();
  94167. _this._oneVector = BABYLON.Vector3.One();
  94168. _this._workingMatrix = BABYLON.Matrix.Identity();
  94169. _this._cache.position = BABYLON.Vector3.Zero();
  94170. if (webVROptions.defaultHeight) {
  94171. _this._defaultHeight = webVROptions.defaultHeight;
  94172. _this.position.y = _this._defaultHeight;
  94173. }
  94174. _this.minZ = 0.1;
  94175. //legacy support - the compensation boolean was removed.
  94176. if (arguments.length === 5) {
  94177. _this.webVROptions = arguments[4];
  94178. }
  94179. // default webVR options
  94180. if (_this.webVROptions.trackPosition == undefined) {
  94181. _this.webVROptions.trackPosition = true;
  94182. }
  94183. if (_this.webVROptions.controllerMeshes == undefined) {
  94184. _this.webVROptions.controllerMeshes = true;
  94185. }
  94186. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  94187. _this.webVROptions.defaultLightingOnControllers = true;
  94188. }
  94189. _this.rotationQuaternion = new BABYLON.Quaternion();
  94190. if (_this.webVROptions && _this.webVROptions.positionScale) {
  94191. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  94192. }
  94193. //enable VR
  94194. var engine = _this.getEngine();
  94195. _this._onVREnabled = function (success) { if (success) {
  94196. _this.initControllers();
  94197. } };
  94198. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  94199. engine.initWebVR().add(function (event) {
  94200. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  94201. return;
  94202. }
  94203. _this._vrDevice = event.vrDisplay;
  94204. //reset the rig parameters.
  94205. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  94206. if (_this._attached) {
  94207. _this.getEngine().enableVR();
  94208. }
  94209. });
  94210. if (typeof (VRFrameData) !== "undefined")
  94211. _this._frameData = new VRFrameData();
  94212. /**
  94213. * The idea behind the following lines:
  94214. * objects that have the camera as parent should actually have the rig cameras as a parent.
  94215. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  94216. * the second will not show it correctly.
  94217. *
  94218. * To solve this - each object that has the camera as parent will be added to a protected array.
  94219. * When the rig camera renders, it will take this array and set all of those to be its children.
  94220. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  94221. * Amazing!
  94222. */
  94223. scene.onBeforeCameraRenderObservable.add(function (camera) {
  94224. if (camera.parent === _this && _this.rigParenting) {
  94225. _this._descendants = _this.getDescendants(true, function (n) {
  94226. // don't take the cameras or the controllers!
  94227. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  94228. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  94229. return !isController && !isRigCamera;
  94230. });
  94231. _this._descendants.forEach(function (node) {
  94232. node.parent = camera;
  94233. });
  94234. }
  94235. });
  94236. scene.onAfterCameraRenderObservable.add(function (camera) {
  94237. if (camera.parent === _this && _this.rigParenting) {
  94238. _this._descendants.forEach(function (node) {
  94239. node.parent = _this;
  94240. });
  94241. }
  94242. });
  94243. return _this;
  94244. }
  94245. /**
  94246. * Gets the device distance from the ground in meters.
  94247. * @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.
  94248. */
  94249. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  94250. if (this._standingMatrix) {
  94251. // Add standing matrix offset to get real offset from ground in room
  94252. this._standingMatrix.getTranslationToRef(this._workingVector);
  94253. return this._deviceRoomPosition.y + this._workingVector.y;
  94254. }
  94255. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  94256. return this._defaultHeight || 0;
  94257. };
  94258. /**
  94259. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  94260. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  94261. */
  94262. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  94263. var _this = this;
  94264. if (callback === void 0) { callback = function (bool) { }; }
  94265. // Use standing matrix if available
  94266. this.getEngine().initWebVRAsync().then(function (result) {
  94267. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  94268. callback(false);
  94269. }
  94270. else {
  94271. _this._standingMatrix = new BABYLON.Matrix();
  94272. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  94273. if (!_this.getScene().useRightHandedSystem) {
  94274. [2, 6, 8, 9, 14].forEach(function (num) {
  94275. if (_this._standingMatrix) {
  94276. _this._standingMatrix.m[num] *= -1;
  94277. }
  94278. });
  94279. }
  94280. callback(true);
  94281. }
  94282. });
  94283. };
  94284. /**
  94285. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  94286. * @returns A promise with a boolean set to if the standing matrix is supported.
  94287. */
  94288. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  94289. var _this = this;
  94290. return new Promise(function (res, rej) {
  94291. _this.useStandingMatrix(function (supported) {
  94292. res(supported);
  94293. });
  94294. });
  94295. };
  94296. /**
  94297. * Disposes the camera
  94298. */
  94299. WebVRFreeCamera.prototype.dispose = function () {
  94300. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  94301. _super.prototype.dispose.call(this);
  94302. };
  94303. /**
  94304. * Gets a vrController by name.
  94305. * @param name The name of the controller to retreive
  94306. * @returns the controller matching the name specified or null if not found
  94307. */
  94308. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  94309. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  94310. var gp = _a[_i];
  94311. if (gp.hand === name) {
  94312. return gp;
  94313. }
  94314. }
  94315. return null;
  94316. };
  94317. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  94318. /**
  94319. * The controller corrisponding to the users left hand.
  94320. */
  94321. get: function () {
  94322. if (!this._leftController) {
  94323. this._leftController = this.getControllerByName("left");
  94324. }
  94325. return this._leftController;
  94326. },
  94327. enumerable: true,
  94328. configurable: true
  94329. });
  94330. ;
  94331. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  94332. /**
  94333. * The controller corrisponding to the users right hand.
  94334. */
  94335. get: function () {
  94336. if (!this._rightController) {
  94337. this._rightController = this.getControllerByName("right");
  94338. }
  94339. return this._rightController;
  94340. },
  94341. enumerable: true,
  94342. configurable: true
  94343. });
  94344. ;
  94345. /**
  94346. * Casts a ray forward from the vrCamera's gaze.
  94347. * @param length Length of the ray (default: 100)
  94348. * @returns the ray corrisponding to the gaze
  94349. */
  94350. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  94351. if (length === void 0) { length = 100; }
  94352. if (this.leftCamera) {
  94353. // Use left eye to avoid computation to compute center on every call
  94354. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  94355. }
  94356. else {
  94357. return _super.prototype.getForwardRay.call(this, length);
  94358. }
  94359. };
  94360. /**
  94361. * @hidden
  94362. * Updates the camera based on device's frame data
  94363. */
  94364. WebVRFreeCamera.prototype._checkInputs = function () {
  94365. if (this._vrDevice && this._vrDevice.isPresenting) {
  94366. this._vrDevice.getFrameData(this._frameData);
  94367. this.updateFromDevice(this._frameData.pose);
  94368. }
  94369. _super.prototype._checkInputs.call(this);
  94370. };
  94371. /**
  94372. * Updates the poseControlled values based on the input device pose.
  94373. * @param poseData Pose coming from the device
  94374. */
  94375. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  94376. if (poseData && poseData.orientation) {
  94377. this.rawPose = poseData;
  94378. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  94379. if (this.getScene().useRightHandedSystem) {
  94380. this._deviceRoomRotationQuaternion.z *= -1;
  94381. this._deviceRoomRotationQuaternion.w *= -1;
  94382. }
  94383. if (this.webVROptions.trackPosition && this.rawPose.position) {
  94384. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  94385. if (this.getScene().useRightHandedSystem) {
  94386. this._deviceRoomPosition.z *= -1;
  94387. }
  94388. }
  94389. this._poseSet = true;
  94390. }
  94391. };
  94392. /**
  94393. * WebVR's attach control will start broadcasting frames to the device.
  94394. * Note that in certain browsers (chrome for example) this function must be called
  94395. * within a user-interaction callback. Example:
  94396. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  94397. *
  94398. * @param element html element to attach the vrDevice to
  94399. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  94400. */
  94401. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  94402. _super.prototype.attachControl.call(this, element, noPreventDefault);
  94403. this._attached = true;
  94404. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  94405. if (this._vrDevice) {
  94406. this.getEngine().enableVR();
  94407. }
  94408. };
  94409. /**
  94410. * Detaches the camera from the html element and disables VR
  94411. *
  94412. * @param element html element to detach from
  94413. */
  94414. WebVRFreeCamera.prototype.detachControl = function (element) {
  94415. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  94416. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  94417. _super.prototype.detachControl.call(this, element);
  94418. this._attached = false;
  94419. this.getEngine().disableVR();
  94420. };
  94421. /**
  94422. * @returns the name of this class
  94423. */
  94424. WebVRFreeCamera.prototype.getClassName = function () {
  94425. return "WebVRFreeCamera";
  94426. };
  94427. /**
  94428. * Calls resetPose on the vrDisplay
  94429. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  94430. */
  94431. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  94432. //uses the vrDisplay's "resetPose()".
  94433. //pitch and roll won't be affected.
  94434. this._vrDevice.resetPose();
  94435. };
  94436. /**
  94437. * @hidden
  94438. * Updates the rig cameras (left and right eye)
  94439. */
  94440. WebVRFreeCamera.prototype._updateRigCameras = function () {
  94441. var camLeft = this._rigCameras[0];
  94442. var camRight = this._rigCameras[1];
  94443. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  94444. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  94445. camLeft.position.copyFrom(this._deviceRoomPosition);
  94446. camRight.position.copyFrom(this._deviceRoomPosition);
  94447. };
  94448. /**
  94449. * @hidden
  94450. * Updates the cached values of the camera
  94451. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  94452. */
  94453. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  94454. var _this = this;
  94455. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  94456. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  94457. if (!this.updateCacheCalled) {
  94458. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  94459. this.updateCacheCalled = true;
  94460. this.update();
  94461. }
  94462. // Set working vector to the device position in room space rotated by the new rotation
  94463. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  94464. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  94465. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  94466. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  94467. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  94468. // Add translation from anchor position
  94469. this._deviceToWorld.getTranslationToRef(this._workingVector);
  94470. this._workingVector.addInPlace(this.position);
  94471. this._workingVector.subtractInPlace(this._cache.position);
  94472. this._deviceToWorld.setTranslation(this._workingVector);
  94473. // Set an inverted matrix to be used when updating the camera
  94474. this._deviceToWorld.invertToRef(this._worldToDevice);
  94475. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  94476. this.controllers.forEach(function (controller) {
  94477. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  94478. controller.update();
  94479. });
  94480. }
  94481. if (!ignoreParentClass) {
  94482. _super.prototype._updateCache.call(this);
  94483. }
  94484. this.updateCacheCalled = false;
  94485. };
  94486. /**
  94487. * Updates the current device position and rotation in the babylon world
  94488. */
  94489. WebVRFreeCamera.prototype.update = function () {
  94490. // Get current device position in babylon world
  94491. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  94492. // Get current device rotation in babylon world
  94493. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  94494. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  94495. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  94496. if (this._poseSet) {
  94497. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  94498. }
  94499. _super.prototype.update.call(this);
  94500. };
  94501. /**
  94502. * @hidden
  94503. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  94504. * @returns an identity matrix
  94505. */
  94506. WebVRFreeCamera.prototype._getViewMatrix = function () {
  94507. return BABYLON.Matrix.Identity();
  94508. };
  94509. /**
  94510. * This function is called by the two RIG cameras.
  94511. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  94512. */
  94513. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  94514. var _this = this;
  94515. // Update the parent camera prior to using a child camera to avoid desynchronization
  94516. var parentCamera = this._cameraRigParams["parentCamera"];
  94517. parentCamera._updateCache();
  94518. //WebVR 1.1
  94519. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  94520. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  94521. if (!this.getScene().useRightHandedSystem) {
  94522. [2, 6, 8, 9, 14].forEach(function (num) {
  94523. _this._webvrViewMatrix.m[num] *= -1;
  94524. });
  94525. }
  94526. // update the camera rotation matrix
  94527. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  94528. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  94529. // Computing target and final matrix
  94530. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  94531. // should the view matrix be updated with scale and position offset?
  94532. if (parentCamera.deviceScaleFactor !== 1) {
  94533. this._webvrViewMatrix.invert();
  94534. // scale the position, if set
  94535. if (parentCamera.deviceScaleFactor) {
  94536. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  94537. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  94538. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  94539. }
  94540. this._webvrViewMatrix.invert();
  94541. }
  94542. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  94543. // Compute global position
  94544. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  94545. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  94546. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  94547. this._workingMatrix.getTranslationToRef(this._globalPosition);
  94548. this._markSyncedWithParent();
  94549. return this._webvrViewMatrix;
  94550. };
  94551. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  94552. var _this = this;
  94553. var parentCamera = this.parent;
  94554. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  94555. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  94556. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  94557. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  94558. //babylon compatible matrix
  94559. if (!this.getScene().useRightHandedSystem) {
  94560. [8, 9, 10, 11].forEach(function (num) {
  94561. _this._projectionMatrix.m[num] *= -1;
  94562. });
  94563. }
  94564. return this._projectionMatrix;
  94565. };
  94566. /**
  94567. * Initializes the controllers and their meshes
  94568. */
  94569. WebVRFreeCamera.prototype.initControllers = function () {
  94570. var _this = this;
  94571. this.controllers = [];
  94572. var manager = this.getScene().gamepadManager;
  94573. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  94574. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  94575. var webVrController = gamepad;
  94576. if (webVrController.defaultModel) {
  94577. webVrController.defaultModel.setEnabled(false);
  94578. }
  94579. if (webVrController.hand === "right") {
  94580. _this._rightController = null;
  94581. }
  94582. if (webVrController.hand === "left") {
  94583. _this._leftController = null;
  94584. }
  94585. var controllerIndex = _this.controllers.indexOf(webVrController);
  94586. if (controllerIndex !== -1) {
  94587. _this.controllers.splice(controllerIndex, 1);
  94588. }
  94589. }
  94590. });
  94591. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  94592. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  94593. var webVrController_1 = gamepad;
  94594. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  94595. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  94596. if (_this.webVROptions.controllerMeshes) {
  94597. if (webVrController_1.defaultModel) {
  94598. webVrController_1.defaultModel.setEnabled(true);
  94599. }
  94600. else {
  94601. // Load the meshes
  94602. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  94603. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  94604. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  94605. if (_this.webVROptions.defaultLightingOnControllers) {
  94606. if (!_this._lightOnControllers) {
  94607. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  94608. }
  94609. var activateLightOnSubMeshes_1 = function (mesh, light) {
  94610. var children = mesh.getChildren();
  94611. if (children.length !== 0) {
  94612. children.forEach(function (mesh) {
  94613. light.includedOnlyMeshes.push(mesh);
  94614. activateLightOnSubMeshes_1(mesh, light);
  94615. });
  94616. }
  94617. };
  94618. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  94619. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  94620. }
  94621. });
  94622. }
  94623. }
  94624. webVrController_1.attachToPoseControlledCamera(_this);
  94625. // since this is async - sanity check. Is the controller already stored?
  94626. if (_this.controllers.indexOf(webVrController_1) === -1) {
  94627. //add to the controllers array
  94628. _this.controllers.push(webVrController_1);
  94629. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  94630. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  94631. // So we're overriding setting left & right manually to be sure
  94632. var firstViveWandDetected = false;
  94633. for (var i = 0; i < _this.controllers.length; i++) {
  94634. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  94635. if (!firstViveWandDetected) {
  94636. firstViveWandDetected = true;
  94637. _this.controllers[i].hand = "left";
  94638. }
  94639. else {
  94640. _this.controllers[i].hand = "right";
  94641. }
  94642. }
  94643. }
  94644. //did we find enough controllers? Great! let the developer know.
  94645. if (_this.controllers.length >= 2) {
  94646. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  94647. }
  94648. }
  94649. }
  94650. });
  94651. };
  94652. return WebVRFreeCamera;
  94653. }(BABYLON.FreeCamera));
  94654. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  94655. })(BABYLON || (BABYLON = {}));
  94656. //# sourceMappingURL=babylon.webVRCamera.js.map
  94657. var BABYLON;
  94658. (function (BABYLON) {
  94659. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  94660. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  94661. });
  94662. // We're mainly based on the logic defined into the FreeCamera code
  94663. /**
  94664. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  94665. * being tilted forward or back and left or right.
  94666. */
  94667. var DeviceOrientationCamera = /** @class */ (function (_super) {
  94668. __extends(DeviceOrientationCamera, _super);
  94669. /**
  94670. * Creates a new device orientation camera
  94671. * @param name The name of the camera
  94672. * @param position The start position camera
  94673. * @param scene The scene the camera belongs to
  94674. */
  94675. function DeviceOrientationCamera(name, position, scene) {
  94676. var _this = _super.call(this, name, position, scene) || this;
  94677. _this._quaternionCache = new BABYLON.Quaternion();
  94678. _this.inputs.addDeviceOrientation();
  94679. return _this;
  94680. }
  94681. /**
  94682. * Gets the current instance class name ("DeviceOrientationCamera").
  94683. * This helps avoiding instanceof at run time.
  94684. * @returns the class name
  94685. */
  94686. DeviceOrientationCamera.prototype.getClassName = function () {
  94687. return "DeviceOrientationCamera";
  94688. };
  94689. /**
  94690. * @hidden
  94691. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  94692. */
  94693. DeviceOrientationCamera.prototype._checkInputs = function () {
  94694. _super.prototype._checkInputs.call(this);
  94695. this._quaternionCache.copyFrom(this.rotationQuaternion);
  94696. if (this._initialQuaternion) {
  94697. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  94698. }
  94699. };
  94700. /**
  94701. * Reset the camera to its default orientation on the specified axis only.
  94702. * @param axis The axis to reset
  94703. */
  94704. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  94705. var _this = this;
  94706. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  94707. //can only work if this camera has a rotation quaternion already.
  94708. if (!this.rotationQuaternion)
  94709. return;
  94710. if (!this._initialQuaternion) {
  94711. this._initialQuaternion = new BABYLON.Quaternion();
  94712. }
  94713. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  94714. ['x', 'y', 'z'].forEach(function (axisName) {
  94715. if (!axis[axisName]) {
  94716. _this._initialQuaternion[axisName] = 0;
  94717. }
  94718. else {
  94719. _this._initialQuaternion[axisName] *= -1;
  94720. }
  94721. });
  94722. this._initialQuaternion.normalize();
  94723. //force rotation update
  94724. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  94725. };
  94726. return DeviceOrientationCamera;
  94727. }(BABYLON.FreeCamera));
  94728. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  94729. })(BABYLON || (BABYLON = {}));
  94730. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  94731. var BABYLON;
  94732. (function (BABYLON) {
  94733. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  94734. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  94735. });
  94736. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  94737. __extends(VRDeviceOrientationFreeCamera, _super);
  94738. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  94739. if (compensateDistortion === void 0) { compensateDistortion = true; }
  94740. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  94741. var _this = _super.call(this, name, position, scene) || this;
  94742. vrCameraMetrics.compensateDistortion = compensateDistortion;
  94743. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  94744. return _this;
  94745. }
  94746. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  94747. return "VRDeviceOrientationFreeCamera";
  94748. };
  94749. return VRDeviceOrientationFreeCamera;
  94750. }(BABYLON.DeviceOrientationCamera));
  94751. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  94752. })(BABYLON || (BABYLON = {}));
  94753. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  94754. var BABYLON;
  94755. (function (BABYLON) {
  94756. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  94757. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  94758. });
  94759. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  94760. __extends(VRDeviceOrientationArcRotateCamera, _super);
  94761. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  94762. if (compensateDistortion === void 0) { compensateDistortion = true; }
  94763. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  94764. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  94765. vrCameraMetrics.compensateDistortion = compensateDistortion;
  94766. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  94767. _this.inputs.addVRDeviceOrientation();
  94768. return _this;
  94769. }
  94770. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  94771. return "VRDeviceOrientationArcRotateCamera";
  94772. };
  94773. return VRDeviceOrientationArcRotateCamera;
  94774. }(BABYLON.ArcRotateCamera));
  94775. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  94776. })(BABYLON || (BABYLON = {}));
  94777. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  94778. var BABYLON;
  94779. (function (BABYLON) {
  94780. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  94781. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  94782. });
  94783. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  94784. __extends(VRDeviceOrientationGamepadCamera, _super);
  94785. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  94786. if (compensateDistortion === void 0) { compensateDistortion = true; }
  94787. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  94788. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  94789. _this.inputs.addGamepad();
  94790. return _this;
  94791. }
  94792. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  94793. return "VRDeviceOrientationGamepadCamera";
  94794. };
  94795. return VRDeviceOrientationGamepadCamera;
  94796. }(BABYLON.VRDeviceOrientationFreeCamera));
  94797. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  94798. })(BABYLON || (BABYLON = {}));
  94799. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  94800. var BABYLON;
  94801. (function (BABYLON) {
  94802. var VRExperienceHelperGazer = /** @class */ (function () {
  94803. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  94804. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  94805. this.scene = scene;
  94806. /** @hidden */
  94807. this._pointerDownOnMeshAsked = false;
  94808. /** @hidden */
  94809. this._isActionableMesh = false;
  94810. /** @hidden */
  94811. this._teleportationRequestInitiated = false;
  94812. /** @hidden */
  94813. this._teleportationBackRequestInitiated = false;
  94814. /** @hidden */
  94815. this._rotationRightAsked = false;
  94816. /** @hidden */
  94817. this._rotationLeftAsked = false;
  94818. /** @hidden */
  94819. this._dpadPressed = true;
  94820. /** @hidden */
  94821. this._activePointer = false;
  94822. this._id = VRExperienceHelperGazer._idCounter++;
  94823. // Gaze tracker
  94824. if (!gazeTrackerToClone) {
  94825. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  94826. this._gazeTracker.bakeCurrentTransformIntoVertices();
  94827. this._gazeTracker.isPickable = false;
  94828. this._gazeTracker.isVisible = false;
  94829. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  94830. targetMat.specularColor = BABYLON.Color3.Black();
  94831. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  94832. targetMat.backFaceCulling = false;
  94833. this._gazeTracker.material = targetMat;
  94834. }
  94835. else {
  94836. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  94837. }
  94838. }
  94839. /** @hidden */
  94840. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  94841. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  94842. };
  94843. /** @hidden */
  94844. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  94845. this._pointerDownOnMeshAsked = true;
  94846. if (this._currentHit) {
  94847. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  94848. }
  94849. };
  94850. /** @hidden */
  94851. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  94852. if (this._currentHit) {
  94853. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  94854. }
  94855. this._pointerDownOnMeshAsked = false;
  94856. };
  94857. /** @hidden */
  94858. VRExperienceHelperGazer.prototype._activatePointer = function () {
  94859. this._activePointer = true;
  94860. };
  94861. /** @hidden */
  94862. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  94863. this._activePointer = false;
  94864. };
  94865. /** @hidden */
  94866. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  94867. if (distance === void 0) { distance = 100; }
  94868. };
  94869. VRExperienceHelperGazer.prototype.dispose = function () {
  94870. this._interactionsEnabled = false;
  94871. this._teleportationEnabled = false;
  94872. if (this._gazeTracker) {
  94873. this._gazeTracker.dispose();
  94874. }
  94875. };
  94876. VRExperienceHelperGazer._idCounter = 0;
  94877. return VRExperienceHelperGazer;
  94878. }());
  94879. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  94880. __extends(VRExperienceHelperControllerGazer, _super);
  94881. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  94882. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  94883. _this.webVRController = webVRController;
  94884. // Laser pointer
  94885. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  94886. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  94887. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  94888. laserPointerMaterial.alpha = 0.6;
  94889. _this._laserPointer.material = laserPointerMaterial;
  94890. _this._laserPointer.rotation.x = Math.PI / 2;
  94891. _this._laserPointer.position.z = -0.5;
  94892. _this._laserPointer.isVisible = false;
  94893. _this._laserPointer.isPickable = false;
  94894. if (!webVRController.mesh) {
  94895. // Create an empty mesh that is used prior to loading the high quality model
  94896. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  94897. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  94898. preloadPointerPose.rotation.x = -0.7;
  94899. preloadMesh.addChild(preloadPointerPose);
  94900. webVRController.attachToMesh(preloadMesh);
  94901. }
  94902. _this._setLaserPointerParent(webVRController.mesh);
  94903. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  94904. _this._setLaserPointerParent(mesh);
  94905. });
  94906. return _this;
  94907. }
  94908. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  94909. return this.webVRController.getForwardRay(length);
  94910. };
  94911. /** @hidden */
  94912. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  94913. _super.prototype._activatePointer.call(this);
  94914. this._laserPointer.isVisible = true;
  94915. };
  94916. /** @hidden */
  94917. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  94918. _super.prototype._deactivatePointer.call(this);
  94919. this._laserPointer.isVisible = false;
  94920. };
  94921. /** @hidden */
  94922. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  94923. this._laserPointer.material.emissiveColor = color;
  94924. };
  94925. /** @hidden */
  94926. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  94927. var makeNotPick = function (root) {
  94928. root.isPickable = false;
  94929. root.getChildMeshes().forEach(function (c) {
  94930. makeNotPick(c);
  94931. });
  94932. };
  94933. makeNotPick(mesh);
  94934. var childMeshes = mesh.getChildMeshes();
  94935. this.webVRController._pointingPoseNode = null;
  94936. for (var i = 0; i < childMeshes.length; i++) {
  94937. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  94938. mesh = childMeshes[i];
  94939. this.webVRController._pointingPoseNode = mesh;
  94940. break;
  94941. }
  94942. }
  94943. this._laserPointer.parent = mesh;
  94944. };
  94945. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  94946. if (distance === void 0) { distance = 100; }
  94947. this._laserPointer.scaling.y = distance;
  94948. this._laserPointer.position.z = -distance / 2;
  94949. };
  94950. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  94951. _super.prototype.dispose.call(this);
  94952. this._laserPointer.dispose();
  94953. if (this._meshAttachedObserver) {
  94954. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  94955. }
  94956. };
  94957. return VRExperienceHelperControllerGazer;
  94958. }(VRExperienceHelperGazer));
  94959. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  94960. __extends(VRExperienceHelperCameraGazer, _super);
  94961. function VRExperienceHelperCameraGazer(getCamera, scene) {
  94962. var _this = _super.call(this, scene) || this;
  94963. _this.getCamera = getCamera;
  94964. return _this;
  94965. }
  94966. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  94967. var camera = this.getCamera();
  94968. if (camera) {
  94969. return camera.getForwardRay(length);
  94970. }
  94971. else {
  94972. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  94973. }
  94974. };
  94975. return VRExperienceHelperCameraGazer;
  94976. }(VRExperienceHelperGazer));
  94977. /**
  94978. * Helps to quickly add VR support to an existing scene.
  94979. * See http://doc.babylonjs.com/how_to/webvr_helper
  94980. */
  94981. var VRExperienceHelper = /** @class */ (function () {
  94982. /**
  94983. * Instantiates a VRExperienceHelper.
  94984. * Helps to quickly add VR support to an existing scene.
  94985. * @param scene The scene the VRExperienceHelper belongs to.
  94986. * @param webVROptions Options to modify the vr experience helper's behavior.
  94987. */
  94988. function VRExperienceHelper(scene,
  94989. /** Options to modify the vr experience helper's behavior. */
  94990. webVROptions) {
  94991. if (webVROptions === void 0) { webVROptions = {}; }
  94992. var _this = this;
  94993. this.webVROptions = webVROptions;
  94994. // Can the system support WebVR, even if a headset isn't plugged in?
  94995. this._webVRsupported = false;
  94996. // If WebVR is supported, is a headset plugged in and are we ready to present?
  94997. this._webVRready = false;
  94998. // Are we waiting for the requestPresent callback to complete?
  94999. this._webVRrequesting = false;
  95000. // Are we presenting to the headset right now?
  95001. this._webVRpresenting = false;
  95002. // Are we presenting in the fullscreen fallback?
  95003. this._fullscreenVRpresenting = false;
  95004. /**
  95005. * Observable raised when entering VR.
  95006. */
  95007. this.onEnteringVRObservable = new BABYLON.Observable();
  95008. /**
  95009. * Observable raised when exiting VR.
  95010. */
  95011. this.onExitingVRObservable = new BABYLON.Observable();
  95012. /**
  95013. * Observable raised when controller mesh is loaded.
  95014. */
  95015. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  95016. this._useCustomVRButton = false;
  95017. this._teleportationRequested = false;
  95018. this._teleportActive = false;
  95019. this._floorMeshesCollection = [];
  95020. this._rotationAllowed = true;
  95021. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  95022. this._isDefaultTeleportationTarget = true;
  95023. this._teleportationFillColor = "#444444";
  95024. this._teleportationBorderColor = "#FFFFFF";
  95025. this._rotationAngle = 0;
  95026. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  95027. this._padSensibilityUp = 0.65;
  95028. this._padSensibilityDown = 0.35;
  95029. this._leftController = null;
  95030. this._rightController = null;
  95031. /**
  95032. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  95033. */
  95034. this.onNewMeshSelected = new BABYLON.Observable();
  95035. /**
  95036. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  95037. */
  95038. this.onNewMeshPicked = new BABYLON.Observable();
  95039. /**
  95040. * Observable raised before camera teleportation
  95041. */
  95042. this.onBeforeCameraTeleport = new BABYLON.Observable();
  95043. /**
  95044. * Observable raised after camera teleportation
  95045. */
  95046. this.onAfterCameraTeleport = new BABYLON.Observable();
  95047. /**
  95048. * Observable raised when current selected mesh gets unselected
  95049. */
  95050. this.onSelectedMeshUnselected = new BABYLON.Observable();
  95051. /**
  95052. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  95053. */
  95054. this.teleportationEnabled = true;
  95055. this._teleportationInitialized = false;
  95056. this._interactionsEnabled = false;
  95057. this._interactionsRequested = false;
  95058. this._displayGaze = true;
  95059. this._displayLaserPointer = true;
  95060. this._onResize = function () {
  95061. _this.moveButtonToBottomRight();
  95062. if (_this._fullscreenVRpresenting && _this._webVRready) {
  95063. _this.exitVR();
  95064. }
  95065. };
  95066. this._onFullscreenChange = function () {
  95067. if (document.fullscreen !== undefined) {
  95068. _this._fullscreenVRpresenting = document.fullscreen;
  95069. }
  95070. else if (document.mozFullScreen !== undefined) {
  95071. _this._fullscreenVRpresenting = document.mozFullScreen;
  95072. }
  95073. else if (document.webkitIsFullScreen !== undefined) {
  95074. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  95075. }
  95076. else if (document.msIsFullScreen !== undefined) {
  95077. _this._fullscreenVRpresenting = document.msIsFullScreen;
  95078. }
  95079. else if (document.msFullscreenElement !== undefined) {
  95080. _this._fullscreenVRpresenting = document.msFullscreenElement;
  95081. }
  95082. if (!_this._fullscreenVRpresenting && _this._canvas) {
  95083. _this.exitVR();
  95084. if (!_this._useCustomVRButton) {
  95085. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  95086. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  95087. }
  95088. }
  95089. };
  95090. this.beforeRender = function () {
  95091. if (_this._leftController && _this._leftController._activePointer) {
  95092. _this._castRayAndSelectObject(_this._leftController);
  95093. }
  95094. if (_this._rightController && _this._rightController._activePointer) {
  95095. _this._castRayAndSelectObject(_this._rightController);
  95096. }
  95097. if (_this._noControllerIsActive) {
  95098. _this._castRayAndSelectObject(_this._cameraGazer);
  95099. }
  95100. else {
  95101. _this._cameraGazer._gazeTracker.isVisible = false;
  95102. }
  95103. };
  95104. this._onNewGamepadConnected = function (gamepad) {
  95105. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  95106. if (gamepad.leftStick) {
  95107. gamepad.onleftstickchanged(function (stickValues) {
  95108. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  95109. // Listening to classic/xbox gamepad only if no VR controller is active
  95110. if ((!_this._leftController && !_this._rightController) ||
  95111. ((_this._leftController && !_this._leftController._activePointer) &&
  95112. (_this._rightController && !_this._rightController._activePointer))) {
  95113. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  95114. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  95115. }
  95116. }
  95117. });
  95118. }
  95119. if (gamepad.rightStick) {
  95120. gamepad.onrightstickchanged(function (stickValues) {
  95121. if (_this._teleportationInitialized) {
  95122. _this._checkRotate(stickValues, _this._cameraGazer);
  95123. }
  95124. });
  95125. }
  95126. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  95127. gamepad.onbuttondown(function (buttonPressed) {
  95128. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  95129. _this._cameraGazer._selectionPointerDown();
  95130. }
  95131. });
  95132. gamepad.onbuttonup(function (buttonPressed) {
  95133. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  95134. _this._cameraGazer._selectionPointerUp();
  95135. }
  95136. });
  95137. }
  95138. }
  95139. else {
  95140. var webVRController = gamepad;
  95141. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  95142. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  95143. _this._rightController = controller;
  95144. }
  95145. else {
  95146. _this._leftController = controller;
  95147. }
  95148. _this._tryEnableInteractionOnController(controller);
  95149. }
  95150. };
  95151. // 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
  95152. this._tryEnableInteractionOnController = function (controller) {
  95153. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  95154. _this._enableInteractionOnController(controller);
  95155. }
  95156. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  95157. _this._enableTeleportationOnController(controller);
  95158. }
  95159. };
  95160. this._onNewGamepadDisconnected = function (gamepad) {
  95161. if (gamepad instanceof BABYLON.WebVRController) {
  95162. if (gamepad.hand === "left" && _this._leftController != null) {
  95163. _this._leftController.dispose();
  95164. _this._leftController = null;
  95165. }
  95166. if (gamepad.hand === "right" && _this._rightController != null) {
  95167. _this._rightController.dispose();
  95168. _this._rightController = null;
  95169. }
  95170. }
  95171. };
  95172. this._workingVector = BABYLON.Vector3.Zero();
  95173. this._workingQuaternion = BABYLON.Quaternion.Identity();
  95174. this._workingMatrix = BABYLON.Matrix.Identity();
  95175. this._scene = scene;
  95176. this._canvas = scene.getEngine().getRenderingCanvas();
  95177. // Parse options
  95178. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  95179. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  95180. }
  95181. if (webVROptions.createDeviceOrientationCamera === undefined) {
  95182. webVROptions.createDeviceOrientationCamera = true;
  95183. }
  95184. if (webVROptions.laserToggle === undefined) {
  95185. webVROptions.laserToggle = true;
  95186. }
  95187. if (webVROptions.defaultHeight === undefined) {
  95188. webVROptions.defaultHeight = 1.7;
  95189. }
  95190. if (webVROptions.useCustomVRButton) {
  95191. this._useCustomVRButton = true;
  95192. if (webVROptions.customVRButton) {
  95193. this._btnVR = webVROptions.customVRButton;
  95194. }
  95195. }
  95196. if (webVROptions.rayLength) {
  95197. this._rayLength = webVROptions.rayLength;
  95198. }
  95199. this._defaultHeight = webVROptions.defaultHeight;
  95200. if (webVROptions.positionScale) {
  95201. this._rayLength *= webVROptions.positionScale;
  95202. this._defaultHeight *= webVROptions.positionScale;
  95203. }
  95204. // Set position
  95205. if (this._scene.activeCamera) {
  95206. this._position = this._scene.activeCamera.position.clone();
  95207. }
  95208. else {
  95209. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  95210. }
  95211. // Set non-vr camera
  95212. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  95213. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  95214. // Copy data from existing camera
  95215. if (this._scene.activeCamera) {
  95216. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  95217. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  95218. // Set rotation from previous camera
  95219. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  95220. var targetCamera = this._scene.activeCamera;
  95221. if (targetCamera.rotationQuaternion) {
  95222. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  95223. }
  95224. else {
  95225. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  95226. }
  95227. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  95228. }
  95229. }
  95230. this._scene.activeCamera = this._deviceOrientationCamera;
  95231. if (this._canvas) {
  95232. this._scene.activeCamera.attachControl(this._canvas);
  95233. }
  95234. }
  95235. else {
  95236. this._existingCamera = this._scene.activeCamera;
  95237. }
  95238. // Create VR cameras
  95239. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  95240. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  95241. }
  95242. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  95243. this._webVRCamera.useStandingMatrix();
  95244. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  95245. // Create default button
  95246. if (!this._useCustomVRButton) {
  95247. this._btnVR = document.createElement("BUTTON");
  95248. this._btnVR.className = "babylonVRicon";
  95249. this._btnVR.id = "babylonVRiconbtn";
  95250. this._btnVR.title = "Click to switch to VR";
  95251. 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) }";
  95252. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  95253. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  95254. // css += ".babylonVRicon.vrdisplaysupported { }";
  95255. // css += ".babylonVRicon.vrdisplayready { }";
  95256. // css += ".babylonVRicon.vrdisplayrequesting { }";
  95257. var style = document.createElement('style');
  95258. style.appendChild(document.createTextNode(css));
  95259. document.getElementsByTagName('head')[0].appendChild(style);
  95260. this.moveButtonToBottomRight();
  95261. }
  95262. // VR button click event
  95263. if (this._btnVR) {
  95264. this._btnVR.addEventListener("click", function () {
  95265. if (!_this.isInVRMode) {
  95266. _this.enterVR();
  95267. }
  95268. else {
  95269. _this.exitVR();
  95270. }
  95271. });
  95272. }
  95273. // Window events
  95274. window.addEventListener("resize", this._onResize);
  95275. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  95276. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  95277. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  95278. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  95279. document.onmsfullscreenchange = this._onFullscreenChange;
  95280. // Display vr button when headset is connected
  95281. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  95282. this.displayVRButton();
  95283. }
  95284. else {
  95285. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  95286. if (e.vrDisplay) {
  95287. _this.displayVRButton();
  95288. }
  95289. });
  95290. }
  95291. // Exiting VR mode using 'ESC' key on desktop
  95292. this._onKeyDown = function (event) {
  95293. if (event.keyCode === 27 && _this.isInVRMode) {
  95294. _this.exitVR();
  95295. }
  95296. };
  95297. document.addEventListener("keydown", this._onKeyDown);
  95298. // Exiting VR mode double tapping the touch screen
  95299. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  95300. if (_this.isInVRMode) {
  95301. _this.exitVR();
  95302. if (_this._fullscreenVRpresenting) {
  95303. _this._scene.getEngine().switchFullscreen(true);
  95304. }
  95305. }
  95306. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  95307. // Listen for WebVR display changes
  95308. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  95309. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  95310. this._onVRRequestPresentStart = function () {
  95311. _this._webVRrequesting = true;
  95312. _this.updateButtonVisibility();
  95313. };
  95314. this._onVRRequestPresentComplete = function (success) {
  95315. _this._webVRrequesting = false;
  95316. _this.updateButtonVisibility();
  95317. };
  95318. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  95319. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  95320. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  95321. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  95322. scene.onDisposeObservable.add(function () {
  95323. _this.dispose();
  95324. });
  95325. // Gamepad connection events
  95326. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  95327. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  95328. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  95329. this.updateButtonVisibility();
  95330. //create easing functions
  95331. this._circleEase = new BABYLON.CircleEase();
  95332. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  95333. if (this.webVROptions.floorMeshes) {
  95334. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  95335. }
  95336. }
  95337. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  95338. /** Return this.onEnteringVRObservable
  95339. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  95340. */
  95341. get: function () {
  95342. return this.onEnteringVRObservable;
  95343. },
  95344. enumerable: true,
  95345. configurable: true
  95346. });
  95347. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  95348. /** Return this.onExitingVRObservable
  95349. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  95350. */
  95351. get: function () {
  95352. return this.onExitingVRObservable;
  95353. },
  95354. enumerable: true,
  95355. configurable: true
  95356. });
  95357. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  95358. /** Return this.onControllerMeshLoadedObservable
  95359. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  95360. */
  95361. get: function () {
  95362. return this.onControllerMeshLoadedObservable;
  95363. },
  95364. enumerable: true,
  95365. configurable: true
  95366. });
  95367. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  95368. /**
  95369. * The mesh used to display where the user is going to teleport.
  95370. */
  95371. get: function () {
  95372. return this._teleportationTarget;
  95373. },
  95374. /**
  95375. * Sets the mesh to be used to display where the user is going to teleport.
  95376. */
  95377. set: function (value) {
  95378. if (value) {
  95379. value.name = "teleportationTarget";
  95380. this._isDefaultTeleportationTarget = false;
  95381. this._teleportationTarget = value;
  95382. }
  95383. },
  95384. enumerable: true,
  95385. configurable: true
  95386. });
  95387. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  95388. /**
  95389. * The mesh used to display where the user is selecting,
  95390. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  95391. * See http://doc.babylonjs.com/resources/baking_transformations
  95392. */
  95393. get: function () {
  95394. return this._cameraGazer._gazeTracker;
  95395. },
  95396. set: function (value) {
  95397. if (value) {
  95398. this._cameraGazer._gazeTracker = value;
  95399. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  95400. this._cameraGazer._gazeTracker.isPickable = false;
  95401. this._cameraGazer._gazeTracker.isVisible = false;
  95402. this._cameraGazer._gazeTracker.name = "gazeTracker";
  95403. if (this._leftController) {
  95404. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  95405. }
  95406. if (this._rightController) {
  95407. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  95408. }
  95409. }
  95410. },
  95411. enumerable: true,
  95412. configurable: true
  95413. });
  95414. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  95415. /**
  95416. * If the ray of the gaze should be displayed.
  95417. */
  95418. get: function () {
  95419. return this._displayGaze;
  95420. },
  95421. /**
  95422. * Sets if the ray of the gaze should be displayed.
  95423. */
  95424. set: function (value) {
  95425. this._displayGaze = value;
  95426. if (!value) {
  95427. this._cameraGazer._gazeTracker.isVisible = false;
  95428. if (this._leftController) {
  95429. this._leftController._gazeTracker.isVisible = false;
  95430. }
  95431. if (this._rightController) {
  95432. this._rightController._gazeTracker.isVisible = false;
  95433. }
  95434. }
  95435. },
  95436. enumerable: true,
  95437. configurable: true
  95438. });
  95439. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  95440. /**
  95441. * If the ray of the LaserPointer should be displayed.
  95442. */
  95443. get: function () {
  95444. return this._displayLaserPointer;
  95445. },
  95446. /**
  95447. * Sets if the ray of the LaserPointer should be displayed.
  95448. */
  95449. set: function (value) {
  95450. this._displayLaserPointer = value;
  95451. if (!value) {
  95452. if (this._rightController) {
  95453. this._rightController._deactivatePointer();
  95454. this._rightController._gazeTracker.isVisible = false;
  95455. }
  95456. if (this._leftController) {
  95457. this._leftController._deactivatePointer();
  95458. this._leftController._gazeTracker.isVisible = false;
  95459. }
  95460. }
  95461. else {
  95462. if (this._rightController) {
  95463. this._rightController._activatePointer();
  95464. }
  95465. if (this._leftController) {
  95466. this._leftController._activatePointer();
  95467. }
  95468. }
  95469. },
  95470. enumerable: true,
  95471. configurable: true
  95472. });
  95473. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  95474. /**
  95475. * The deviceOrientationCamera used as the camera when not in VR.
  95476. */
  95477. get: function () {
  95478. return this._deviceOrientationCamera;
  95479. },
  95480. enumerable: true,
  95481. configurable: true
  95482. });
  95483. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  95484. /**
  95485. * Based on the current WebVR support, returns the current VR camera used.
  95486. */
  95487. get: function () {
  95488. if (this._webVRready) {
  95489. return this._webVRCamera;
  95490. }
  95491. else {
  95492. return this._scene.activeCamera;
  95493. }
  95494. },
  95495. enumerable: true,
  95496. configurable: true
  95497. });
  95498. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  95499. /**
  95500. * The webVRCamera which is used when in VR.
  95501. */
  95502. get: function () {
  95503. return this._webVRCamera;
  95504. },
  95505. enumerable: true,
  95506. configurable: true
  95507. });
  95508. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  95509. /**
  95510. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  95511. */
  95512. get: function () {
  95513. return this._vrDeviceOrientationCamera;
  95514. },
  95515. enumerable: true,
  95516. configurable: true
  95517. });
  95518. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  95519. get: function () {
  95520. var result = this._cameraGazer._teleportationRequestInitiated
  95521. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  95522. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  95523. return result;
  95524. },
  95525. enumerable: true,
  95526. configurable: true
  95527. });
  95528. // Raised when one of the controller has loaded successfully its associated default mesh
  95529. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  95530. if (this._leftController && this._leftController.webVRController == webVRController) {
  95531. if (webVRController.mesh) {
  95532. this._leftController._setLaserPointerParent(webVRController.mesh);
  95533. }
  95534. }
  95535. if (this._rightController && this._rightController.webVRController == webVRController) {
  95536. if (webVRController.mesh) {
  95537. this._rightController._setLaserPointerParent(webVRController.mesh);
  95538. }
  95539. }
  95540. try {
  95541. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  95542. }
  95543. catch (err) {
  95544. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  95545. }
  95546. };
  95547. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  95548. /**
  95549. * Gets a value indicating if we are currently in VR mode.
  95550. */
  95551. get: function () {
  95552. return this._webVRpresenting || this._fullscreenVRpresenting;
  95553. },
  95554. enumerable: true,
  95555. configurable: true
  95556. });
  95557. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  95558. var vrDisplay = this._scene.getEngine().getVRDevice();
  95559. if (vrDisplay) {
  95560. var wasPresenting = this._webVRpresenting;
  95561. // A VR display is connected
  95562. this._webVRpresenting = vrDisplay.isPresenting;
  95563. if (wasPresenting && !this._webVRpresenting && this.isInVRMode)
  95564. this.exitVR();
  95565. }
  95566. else {
  95567. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  95568. }
  95569. this.updateButtonVisibility();
  95570. };
  95571. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  95572. this._webVRsupported = eventArgs.vrSupported;
  95573. this._webVRready = !!eventArgs.vrDisplay;
  95574. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  95575. this.updateButtonVisibility();
  95576. };
  95577. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  95578. if (this._canvas && !this._useCustomVRButton) {
  95579. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  95580. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  95581. }
  95582. };
  95583. VRExperienceHelper.prototype.displayVRButton = function () {
  95584. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  95585. document.body.appendChild(this._btnVR);
  95586. this._btnVRDisplayed = true;
  95587. }
  95588. };
  95589. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  95590. if (!this._btnVR || this._useCustomVRButton) {
  95591. return;
  95592. }
  95593. this._btnVR.className = "babylonVRicon";
  95594. if (this.isInVRMode) {
  95595. this._btnVR.className += " vrdisplaypresenting";
  95596. }
  95597. else {
  95598. if (this._webVRready)
  95599. this._btnVR.className += " vrdisplayready";
  95600. if (this._webVRsupported)
  95601. this._btnVR.className += " vrdisplaysupported";
  95602. if (this._webVRrequesting)
  95603. this._btnVR.className += " vrdisplayrequesting";
  95604. }
  95605. };
  95606. /**
  95607. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  95608. * Otherwise, will use the fullscreen API.
  95609. */
  95610. VRExperienceHelper.prototype.enterVR = function () {
  95611. if (this.onEnteringVRObservable) {
  95612. try {
  95613. this.onEnteringVRObservable.notifyObservers(this);
  95614. }
  95615. catch (err) {
  95616. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  95617. }
  95618. }
  95619. if (this._scene.activeCamera) {
  95620. this._position = this._scene.activeCamera.position.clone();
  95621. // make sure that we return to the last active camera
  95622. this._existingCamera = this._scene.activeCamera;
  95623. }
  95624. if (this._webVRrequesting)
  95625. return;
  95626. // If WebVR is supported and a headset is connected
  95627. if (this._webVRready) {
  95628. if (!this._webVRpresenting) {
  95629. this._webVRCamera.position = this._position;
  95630. this._scene.activeCamera = this._webVRCamera;
  95631. }
  95632. }
  95633. else if (this._vrDeviceOrientationCamera) {
  95634. this._vrDeviceOrientationCamera.position = this._position;
  95635. if (this._scene.activeCamera) {
  95636. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  95637. }
  95638. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  95639. this._scene.getEngine().switchFullscreen(true);
  95640. this.updateButtonVisibility();
  95641. }
  95642. if (this._scene.activeCamera && this._canvas) {
  95643. this._scene.activeCamera.attachControl(this._canvas);
  95644. }
  95645. if (this._interactionsEnabled) {
  95646. this._scene.registerBeforeRender(this.beforeRender);
  95647. }
  95648. };
  95649. /**
  95650. * Attempt to exit VR, or fullscreen.
  95651. */
  95652. VRExperienceHelper.prototype.exitVR = function () {
  95653. if (this.onExitingVRObservable) {
  95654. try {
  95655. this.onExitingVRObservable.notifyObservers(this);
  95656. }
  95657. catch (err) {
  95658. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  95659. }
  95660. }
  95661. if (this._webVRpresenting) {
  95662. this._scene.getEngine().disableVR();
  95663. }
  95664. if (this._scene.activeCamera) {
  95665. this._position = this._scene.activeCamera.position.clone();
  95666. }
  95667. if (this._deviceOrientationCamera) {
  95668. this._deviceOrientationCamera.position = this._position;
  95669. this._scene.activeCamera = this._deviceOrientationCamera;
  95670. if (this._canvas) {
  95671. this._scene.activeCamera.attachControl(this._canvas);
  95672. }
  95673. }
  95674. else if (this._existingCamera) {
  95675. this._existingCamera.position = this._position;
  95676. this._scene.activeCamera = this._existingCamera;
  95677. }
  95678. this.updateButtonVisibility();
  95679. if (this._interactionsEnabled) {
  95680. this._scene.unregisterBeforeRender(this.beforeRender);
  95681. this._cameraGazer._gazeTracker.isVisible = false;
  95682. if (this._leftController) {
  95683. this._leftController._gazeTracker.isVisible = false;
  95684. }
  95685. if (this._rightController) {
  95686. this._rightController._gazeTracker.isVisible = false;
  95687. }
  95688. }
  95689. // resize to update width and height when exiting vr exits fullscreen
  95690. this._scene.getEngine().resize();
  95691. };
  95692. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  95693. /**
  95694. * The position of the vr experience helper.
  95695. */
  95696. get: function () {
  95697. return this._position;
  95698. },
  95699. /**
  95700. * Sets the position of the vr experience helper.
  95701. */
  95702. set: function (value) {
  95703. this._position = value;
  95704. if (this._scene.activeCamera) {
  95705. this._scene.activeCamera.position = value;
  95706. }
  95707. },
  95708. enumerable: true,
  95709. configurable: true
  95710. });
  95711. /**
  95712. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  95713. */
  95714. VRExperienceHelper.prototype.enableInteractions = function () {
  95715. var _this = this;
  95716. if (!this._interactionsEnabled) {
  95717. this._interactionsRequested = true;
  95718. if (this._leftController) {
  95719. this._enableInteractionOnController(this._leftController);
  95720. }
  95721. if (this._rightController) {
  95722. this._enableInteractionOnController(this._rightController);
  95723. }
  95724. this.raySelectionPredicate = function (mesh) {
  95725. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  95726. };
  95727. this.meshSelectionPredicate = function (mesh) {
  95728. return true;
  95729. };
  95730. this._raySelectionPredicate = function (mesh) {
  95731. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  95732. && mesh.name.indexOf("teleportationTarget") === -1
  95733. && mesh.name.indexOf("torusTeleportation") === -1)) {
  95734. return _this.raySelectionPredicate(mesh);
  95735. }
  95736. return false;
  95737. };
  95738. this._interactionsEnabled = true;
  95739. }
  95740. };
  95741. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  95742. get: function () {
  95743. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  95744. },
  95745. enumerable: true,
  95746. configurable: true
  95747. });
  95748. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  95749. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  95750. if (this._floorMeshesCollection[i].id === mesh.id) {
  95751. return true;
  95752. }
  95753. }
  95754. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  95755. return true;
  95756. }
  95757. return false;
  95758. };
  95759. /**
  95760. * Adds a floor mesh to be used for teleportation.
  95761. * @param floorMesh the mesh to be used for teleportation.
  95762. */
  95763. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  95764. if (!this._floorMeshesCollection) {
  95765. return;
  95766. }
  95767. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  95768. return;
  95769. }
  95770. this._floorMeshesCollection.push(floorMesh);
  95771. };
  95772. /**
  95773. * Removes a floor mesh from being used for teleportation.
  95774. * @param floorMesh the mesh to be removed.
  95775. */
  95776. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  95777. if (!this._floorMeshesCollection) {
  95778. return;
  95779. }
  95780. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  95781. if (meshIndex !== -1) {
  95782. this._floorMeshesCollection.splice(meshIndex, 1);
  95783. }
  95784. };
  95785. /**
  95786. * Enables interactions and teleportation using the VR controllers and gaze.
  95787. * @param vrTeleportationOptions options to modify teleportation behavior.
  95788. */
  95789. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  95790. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  95791. if (!this._teleportationInitialized) {
  95792. this._teleportationRequested = true;
  95793. this.enableInteractions();
  95794. if (vrTeleportationOptions.floorMeshName) {
  95795. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  95796. }
  95797. if (vrTeleportationOptions.floorMeshes) {
  95798. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  95799. }
  95800. if (this._leftController != null) {
  95801. this._enableTeleportationOnController(this._leftController);
  95802. }
  95803. if (this._rightController != null) {
  95804. this._enableTeleportationOnController(this._rightController);
  95805. }
  95806. // Creates an image processing post process for the vignette not relying
  95807. // on the main scene configuration for image processing to reduce setup and spaces
  95808. // (gamma/linear) conflicts.
  95809. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  95810. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  95811. imageProcessingConfiguration.vignetteEnabled = true;
  95812. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  95813. this._webVRCamera.detachPostProcess(this._postProcessMove);
  95814. this._teleportationInitialized = true;
  95815. if (this._isDefaultTeleportationTarget) {
  95816. this._createTeleportationCircles();
  95817. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  95818. }
  95819. }
  95820. };
  95821. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  95822. var _this = this;
  95823. var controllerMesh = controller.webVRController.mesh;
  95824. if (controllerMesh) {
  95825. controller._interactionsEnabled = true;
  95826. controller._activatePointer();
  95827. if (this.webVROptions.laserToggle) {
  95828. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  95829. // Enabling / disabling laserPointer
  95830. if (_this._displayLaserPointer && stateObject.value === 1) {
  95831. if (controller._activePointer) {
  95832. controller._deactivatePointer();
  95833. }
  95834. else {
  95835. controller._activatePointer();
  95836. }
  95837. if (_this.displayGaze) {
  95838. controller._gazeTracker.isVisible = controller._activePointer;
  95839. }
  95840. }
  95841. });
  95842. }
  95843. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  95844. var gazer = controller;
  95845. if (_this._noControllerIsActive) {
  95846. gazer = _this._cameraGazer;
  95847. }
  95848. if (!gazer._pointerDownOnMeshAsked) {
  95849. if (stateObject.value > _this._padSensibilityUp) {
  95850. gazer._selectionPointerDown();
  95851. }
  95852. }
  95853. else if (stateObject.value < _this._padSensibilityDown) {
  95854. gazer._selectionPointerUp();
  95855. }
  95856. });
  95857. }
  95858. };
  95859. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  95860. // Dont teleport if another gaze already requested teleportation
  95861. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  95862. return;
  95863. }
  95864. if (!gazer._teleportationRequestInitiated) {
  95865. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  95866. gazer._activatePointer();
  95867. gazer._teleportationRequestInitiated = true;
  95868. }
  95869. }
  95870. else {
  95871. // Listening to the proper controller values changes to confirm teleportation
  95872. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  95873. if (this._teleportActive) {
  95874. this._teleportCamera(this._haloCenter);
  95875. }
  95876. gazer._teleportationRequestInitiated = false;
  95877. }
  95878. }
  95879. };
  95880. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  95881. // Only rotate when user is not currently selecting a teleportation location
  95882. if (gazer._teleportationRequestInitiated) {
  95883. return;
  95884. }
  95885. if (!gazer._rotationLeftAsked) {
  95886. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  95887. gazer._rotationLeftAsked = true;
  95888. if (this._rotationAllowed) {
  95889. this._rotateCamera(false);
  95890. }
  95891. }
  95892. }
  95893. else {
  95894. if (stateObject.x > -this._padSensibilityDown) {
  95895. gazer._rotationLeftAsked = false;
  95896. }
  95897. }
  95898. if (!gazer._rotationRightAsked) {
  95899. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  95900. gazer._rotationRightAsked = true;
  95901. if (this._rotationAllowed) {
  95902. this._rotateCamera(true);
  95903. }
  95904. }
  95905. }
  95906. else {
  95907. if (stateObject.x < this._padSensibilityDown) {
  95908. gazer._rotationRightAsked = false;
  95909. }
  95910. }
  95911. };
  95912. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  95913. // Only teleport backwards when user is not currently selecting a teleportation location
  95914. if (gazer._teleportationRequestInitiated) {
  95915. return;
  95916. }
  95917. // Teleport backwards
  95918. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  95919. if (!gazer._teleportationBackRequestInitiated) {
  95920. if (!this.currentVRCamera) {
  95921. return;
  95922. }
  95923. // Get rotation and position of the current camera
  95924. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  95925. var position = this.currentVRCamera.position;
  95926. // If the camera has device position, use that instead
  95927. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  95928. rotation = this.currentVRCamera.deviceRotationQuaternion;
  95929. position = this.currentVRCamera.devicePosition;
  95930. }
  95931. // Get matrix with only the y rotation of the device rotation
  95932. rotation.toEulerAnglesToRef(this._workingVector);
  95933. this._workingVector.z = 0;
  95934. this._workingVector.x = 0;
  95935. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  95936. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  95937. // Rotate backwards ray by device rotation to cast at the ground behind the user
  95938. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  95939. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  95940. var ray = new BABYLON.Ray(position, this._workingVector);
  95941. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  95942. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  95943. this._teleportCamera(hit.pickedPoint);
  95944. }
  95945. gazer._teleportationBackRequestInitiated = true;
  95946. }
  95947. }
  95948. else {
  95949. gazer._teleportationBackRequestInitiated = false;
  95950. }
  95951. };
  95952. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  95953. var _this = this;
  95954. var controllerMesh = controller.webVRController.mesh;
  95955. if (controllerMesh) {
  95956. if (!controller._interactionsEnabled) {
  95957. this._enableInteractionOnController(controller);
  95958. }
  95959. controller._interactionsEnabled = true;
  95960. controller._teleportationEnabled = true;
  95961. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  95962. controller._dpadPressed = false;
  95963. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  95964. controller._dpadPressed = stateObject.pressed;
  95965. if (!controller._dpadPressed) {
  95966. controller._rotationLeftAsked = false;
  95967. controller._rotationRightAsked = false;
  95968. controller._teleportationBackRequestInitiated = false;
  95969. }
  95970. });
  95971. }
  95972. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  95973. if (_this.teleportationEnabled) {
  95974. _this._checkTeleportBackwards(stateObject, controller);
  95975. _this._checkTeleportWithRay(stateObject, controller);
  95976. }
  95977. _this._checkRotate(stateObject, controller);
  95978. });
  95979. }
  95980. };
  95981. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  95982. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  95983. this._teleportationTarget.isPickable = false;
  95984. var length = 512;
  95985. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  95986. dynamicTexture.hasAlpha = true;
  95987. var context = dynamicTexture.getContext();
  95988. var centerX = length / 2;
  95989. var centerY = length / 2;
  95990. var radius = 200;
  95991. context.beginPath();
  95992. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  95993. context.fillStyle = this._teleportationFillColor;
  95994. context.fill();
  95995. context.lineWidth = 10;
  95996. context.strokeStyle = this._teleportationBorderColor;
  95997. context.stroke();
  95998. context.closePath();
  95999. dynamicTexture.update();
  96000. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  96001. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  96002. this._teleportationTarget.material = teleportationCircleMaterial;
  96003. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  96004. torus.isPickable = false;
  96005. torus.parent = this._teleportationTarget;
  96006. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  96007. var keys = [];
  96008. keys.push({
  96009. frame: 0,
  96010. value: 0
  96011. });
  96012. keys.push({
  96013. frame: 30,
  96014. value: 0.4
  96015. });
  96016. keys.push({
  96017. frame: 60,
  96018. value: 0
  96019. });
  96020. animationInnerCircle.setKeys(keys);
  96021. var easingFunction = new BABYLON.SineEase();
  96022. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  96023. animationInnerCircle.setEasingFunction(easingFunction);
  96024. torus.animations = [];
  96025. torus.animations.push(animationInnerCircle);
  96026. this._scene.beginAnimation(torus, 0, 60, true);
  96027. this._hideTeleportationTarget();
  96028. };
  96029. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  96030. this._teleportActive = true;
  96031. if (this._teleportationInitialized) {
  96032. this._teleportationTarget.isVisible = true;
  96033. if (this._isDefaultTeleportationTarget) {
  96034. this._teleportationTarget.getChildren()[0].isVisible = true;
  96035. }
  96036. }
  96037. };
  96038. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  96039. this._teleportActive = false;
  96040. if (this._teleportationInitialized) {
  96041. this._teleportationTarget.isVisible = false;
  96042. if (this._isDefaultTeleportationTarget) {
  96043. this._teleportationTarget.getChildren()[0].isVisible = false;
  96044. }
  96045. }
  96046. };
  96047. VRExperienceHelper.prototype._rotateCamera = function (right) {
  96048. var _this = this;
  96049. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  96050. return;
  96051. }
  96052. if (right) {
  96053. this._rotationAngle++;
  96054. }
  96055. else {
  96056. this._rotationAngle--;
  96057. }
  96058. this.currentVRCamera.animations = [];
  96059. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  96060. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  96061. var animationRotationKeys = [];
  96062. animationRotationKeys.push({
  96063. frame: 0,
  96064. value: this.currentVRCamera.rotationQuaternion
  96065. });
  96066. animationRotationKeys.push({
  96067. frame: 6,
  96068. value: target
  96069. });
  96070. animationRotation.setKeys(animationRotationKeys);
  96071. animationRotation.setEasingFunction(this._circleEase);
  96072. this.currentVRCamera.animations.push(animationRotation);
  96073. this._postProcessMove.animations = [];
  96074. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  96075. var vignetteWeightKeys = [];
  96076. vignetteWeightKeys.push({
  96077. frame: 0,
  96078. value: 0
  96079. });
  96080. vignetteWeightKeys.push({
  96081. frame: 3,
  96082. value: 4
  96083. });
  96084. vignetteWeightKeys.push({
  96085. frame: 6,
  96086. value: 0
  96087. });
  96088. animationPP.setKeys(vignetteWeightKeys);
  96089. animationPP.setEasingFunction(this._circleEase);
  96090. this._postProcessMove.animations.push(animationPP);
  96091. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  96092. var vignetteStretchKeys = [];
  96093. vignetteStretchKeys.push({
  96094. frame: 0,
  96095. value: 0
  96096. });
  96097. vignetteStretchKeys.push({
  96098. frame: 3,
  96099. value: 10
  96100. });
  96101. vignetteStretchKeys.push({
  96102. frame: 6,
  96103. value: 0
  96104. });
  96105. animationPP2.setKeys(vignetteStretchKeys);
  96106. animationPP2.setEasingFunction(this._circleEase);
  96107. this._postProcessMove.animations.push(animationPP2);
  96108. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  96109. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  96110. this._postProcessMove.samples = 4;
  96111. this._webVRCamera.attachPostProcess(this._postProcessMove);
  96112. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  96113. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  96114. });
  96115. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  96116. };
  96117. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  96118. if (hit.pickedPoint) {
  96119. if (gazer._teleportationRequestInitiated) {
  96120. this._displayTeleportationTarget();
  96121. this._haloCenter.copyFrom(hit.pickedPoint);
  96122. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  96123. }
  96124. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  96125. if (pickNormal) {
  96126. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  96127. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  96128. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  96129. }
  96130. this._teleportationTarget.position.y += 0.1;
  96131. }
  96132. };
  96133. VRExperienceHelper.prototype._teleportCamera = function (location) {
  96134. var _this = this;
  96135. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  96136. return;
  96137. }
  96138. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  96139. // offset of the headset from the anchor.
  96140. if (this.webVRCamera.leftCamera) {
  96141. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  96142. this._workingVector.subtractInPlace(this.webVRCamera.position);
  96143. location.subtractToRef(this._workingVector, this._workingVector);
  96144. }
  96145. else {
  96146. this._workingVector.copyFrom(location);
  96147. }
  96148. // Add height to account for user's height offset
  96149. if (this.isInVRMode) {
  96150. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  96151. }
  96152. else {
  96153. this._workingVector.y += this._defaultHeight;
  96154. }
  96155. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  96156. // Create animation from the camera's position to the new location
  96157. this.currentVRCamera.animations = [];
  96158. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  96159. var animationCameraTeleportationKeys = [{
  96160. frame: 0,
  96161. value: this.currentVRCamera.position
  96162. },
  96163. {
  96164. frame: 11,
  96165. value: this._workingVector
  96166. }
  96167. ];
  96168. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  96169. animationCameraTeleportation.setEasingFunction(this._circleEase);
  96170. this.currentVRCamera.animations.push(animationCameraTeleportation);
  96171. this._postProcessMove.animations = [];
  96172. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  96173. var vignetteWeightKeys = [];
  96174. vignetteWeightKeys.push({
  96175. frame: 0,
  96176. value: 0
  96177. });
  96178. vignetteWeightKeys.push({
  96179. frame: 5,
  96180. value: 8
  96181. });
  96182. vignetteWeightKeys.push({
  96183. frame: 11,
  96184. value: 0
  96185. });
  96186. animationPP.setKeys(vignetteWeightKeys);
  96187. this._postProcessMove.animations.push(animationPP);
  96188. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  96189. var vignetteStretchKeys = [];
  96190. vignetteStretchKeys.push({
  96191. frame: 0,
  96192. value: 0
  96193. });
  96194. vignetteStretchKeys.push({
  96195. frame: 5,
  96196. value: 10
  96197. });
  96198. vignetteStretchKeys.push({
  96199. frame: 11,
  96200. value: 0
  96201. });
  96202. animationPP2.setKeys(vignetteStretchKeys);
  96203. this._postProcessMove.animations.push(animationPP2);
  96204. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  96205. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  96206. this._webVRCamera.attachPostProcess(this._postProcessMove);
  96207. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  96208. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  96209. });
  96210. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  96211. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  96212. });
  96213. this._hideTeleportationTarget();
  96214. };
  96215. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  96216. if (normal) {
  96217. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  96218. if (angle < Math.PI / 2) {
  96219. normal.scaleInPlace(-1);
  96220. }
  96221. }
  96222. return normal;
  96223. };
  96224. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  96225. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  96226. return;
  96227. }
  96228. var ray = gazer._getForwardRay(this._rayLength);
  96229. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  96230. if (hit) {
  96231. // Populate the contrllers mesh that can be used for drag/drop
  96232. if (gazer._laserPointer) {
  96233. hit.originMesh = gazer._laserPointer.parent;
  96234. }
  96235. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  96236. }
  96237. gazer._currentHit = hit;
  96238. // Moving the gazeTracker on the mesh face targetted
  96239. if (hit && hit.pickedPoint) {
  96240. if (this._displayGaze) {
  96241. var multiplier = 1;
  96242. gazer._gazeTracker.isVisible = true;
  96243. if (gazer._isActionableMesh) {
  96244. multiplier = 3;
  96245. }
  96246. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  96247. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  96248. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  96249. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  96250. // To avoid z-fighting
  96251. var deltaFighting = 0.002;
  96252. if (pickNormal) {
  96253. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  96254. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  96255. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  96256. }
  96257. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  96258. if (gazer._gazeTracker.position.x < 0) {
  96259. gazer._gazeTracker.position.x += deltaFighting;
  96260. }
  96261. else {
  96262. gazer._gazeTracker.position.x -= deltaFighting;
  96263. }
  96264. if (gazer._gazeTracker.position.y < 0) {
  96265. gazer._gazeTracker.position.y += deltaFighting;
  96266. }
  96267. else {
  96268. gazer._gazeTracker.position.y -= deltaFighting;
  96269. }
  96270. if (gazer._gazeTracker.position.z < 0) {
  96271. gazer._gazeTracker.position.z += deltaFighting;
  96272. }
  96273. else {
  96274. gazer._gazeTracker.position.z -= deltaFighting;
  96275. }
  96276. }
  96277. // Changing the size of the laser pointer based on the distance from the targetted point
  96278. gazer._updatePointerDistance(hit.distance);
  96279. }
  96280. else {
  96281. gazer._updatePointerDistance();
  96282. gazer._gazeTracker.isVisible = false;
  96283. }
  96284. if (hit && hit.pickedMesh) {
  96285. // The object selected is the floor, we're in a teleportation scenario
  96286. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  96287. // Moving the teleportation area to this targetted point
  96288. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  96289. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  96290. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  96291. }
  96292. gazer._currentMeshSelected = null;
  96293. if (gazer._teleportationRequestInitiated) {
  96294. this._moveTeleportationSelectorTo(hit, gazer, ray);
  96295. }
  96296. return;
  96297. }
  96298. // If not, we're in a selection scenario
  96299. //this._teleportationAllowed = false;
  96300. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  96301. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  96302. this.onNewMeshPicked.notifyObservers(hit);
  96303. gazer._currentMeshSelected = hit.pickedMesh;
  96304. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  96305. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  96306. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  96307. gazer._isActionableMesh = true;
  96308. }
  96309. else {
  96310. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  96311. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  96312. gazer._isActionableMesh = false;
  96313. }
  96314. try {
  96315. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  96316. }
  96317. catch (err) {
  96318. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  96319. }
  96320. }
  96321. else {
  96322. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  96323. gazer._currentMeshSelected = null;
  96324. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  96325. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  96326. }
  96327. }
  96328. }
  96329. else {
  96330. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  96331. gazer._currentMeshSelected = null;
  96332. //this._teleportationAllowed = false;
  96333. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  96334. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  96335. }
  96336. };
  96337. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  96338. if (mesh) {
  96339. this.onSelectedMeshUnselected.notifyObservers(mesh);
  96340. }
  96341. };
  96342. /**
  96343. * Sets the color of the laser ray from the vr controllers.
  96344. * @param color new color for the ray.
  96345. */
  96346. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  96347. if (this._leftController) {
  96348. this._leftController._setLaserPointerColor(color);
  96349. }
  96350. if (this._rightController) {
  96351. this._rightController._setLaserPointerColor(color);
  96352. }
  96353. };
  96354. /**
  96355. * Sets the color of the ray from the vr headsets gaze.
  96356. * @param color new color for the ray.
  96357. */
  96358. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  96359. if (!this._cameraGazer._gazeTracker.material) {
  96360. return;
  96361. }
  96362. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  96363. if (this._leftController) {
  96364. this._leftController._gazeTracker.material.emissiveColor = color;
  96365. }
  96366. if (this._rightController) {
  96367. this._rightController._gazeTracker.material.emissiveColor = color;
  96368. }
  96369. };
  96370. /**
  96371. * Exits VR and disposes of the vr experience helper
  96372. */
  96373. VRExperienceHelper.prototype.dispose = function () {
  96374. if (this.isInVRMode) {
  96375. this.exitVR();
  96376. }
  96377. if (this._postProcessMove) {
  96378. this._postProcessMove.dispose();
  96379. }
  96380. if (this._webVRCamera) {
  96381. this._webVRCamera.dispose();
  96382. }
  96383. if (this._vrDeviceOrientationCamera) {
  96384. this._vrDeviceOrientationCamera.dispose();
  96385. }
  96386. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  96387. document.body.removeChild(this._btnVR);
  96388. }
  96389. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  96390. this._deviceOrientationCamera.dispose();
  96391. }
  96392. if (this._cameraGazer) {
  96393. this._cameraGazer.dispose();
  96394. }
  96395. if (this._leftController) {
  96396. this._leftController.dispose();
  96397. }
  96398. if (this._rightController) {
  96399. this._rightController.dispose();
  96400. }
  96401. if (this._teleportationTarget) {
  96402. this._teleportationTarget.dispose();
  96403. }
  96404. this._floorMeshesCollection = [];
  96405. document.removeEventListener("keydown", this._onKeyDown);
  96406. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  96407. window.removeEventListener("resize", this._onResize);
  96408. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  96409. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  96410. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  96411. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  96412. document.onmsfullscreenchange = null;
  96413. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  96414. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  96415. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  96416. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  96417. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  96418. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  96419. this._scene.unregisterBeforeRender(this.beforeRender);
  96420. };
  96421. /**
  96422. * Gets the name of the VRExperienceHelper class
  96423. * @returns "VRExperienceHelper"
  96424. */
  96425. VRExperienceHelper.prototype.getClassName = function () {
  96426. return "VRExperienceHelper";
  96427. };
  96428. return VRExperienceHelper;
  96429. }());
  96430. BABYLON.VRExperienceHelper = VRExperienceHelper;
  96431. })(BABYLON || (BABYLON = {}));
  96432. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  96433. // Mainly based on these 2 articles :
  96434. // 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
  96435. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  96436. var BABYLON;
  96437. (function (BABYLON) {
  96438. /**
  96439. * Defines the potential axis of a Joystick
  96440. */
  96441. var JoystickAxis;
  96442. (function (JoystickAxis) {
  96443. /** X axis */
  96444. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  96445. /** Y axis */
  96446. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  96447. /** Z axis */
  96448. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  96449. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  96450. /**
  96451. * Class used to define virtual joystick (used in touch mode)
  96452. */
  96453. var VirtualJoystick = /** @class */ (function () {
  96454. /**
  96455. * Creates a new virtual joystick
  96456. * @param leftJoystick defines that the joystick is for left hand (false by default)
  96457. */
  96458. function VirtualJoystick(leftJoystick) {
  96459. var _this = this;
  96460. if (leftJoystick) {
  96461. this._leftJoystick = true;
  96462. }
  96463. else {
  96464. this._leftJoystick = false;
  96465. }
  96466. VirtualJoystick._globalJoystickIndex++;
  96467. // By default left & right arrow keys are moving the X
  96468. // and up & down keys are moving the Y
  96469. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  96470. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  96471. this.reverseLeftRight = false;
  96472. this.reverseUpDown = false;
  96473. // collections of pointers
  96474. this._touches = new BABYLON.StringDictionary();
  96475. this.deltaPosition = BABYLON.Vector3.Zero();
  96476. this._joystickSensibility = 25;
  96477. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  96478. this._onResize = function (evt) {
  96479. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  96480. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  96481. if (VirtualJoystick.vjCanvas) {
  96482. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  96483. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  96484. }
  96485. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  96486. };
  96487. // injecting a canvas element on top of the canvas 3D game
  96488. if (!VirtualJoystick.vjCanvas) {
  96489. window.addEventListener("resize", this._onResize, false);
  96490. VirtualJoystick.vjCanvas = document.createElement("canvas");
  96491. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  96492. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  96493. VirtualJoystick.vjCanvas.width = window.innerWidth;
  96494. VirtualJoystick.vjCanvas.height = window.innerHeight;
  96495. VirtualJoystick.vjCanvas.style.width = "100%";
  96496. VirtualJoystick.vjCanvas.style.height = "100%";
  96497. VirtualJoystick.vjCanvas.style.position = "absolute";
  96498. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  96499. VirtualJoystick.vjCanvas.style.top = "0px";
  96500. VirtualJoystick.vjCanvas.style.left = "0px";
  96501. VirtualJoystick.vjCanvas.style.zIndex = "5";
  96502. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  96503. // Support for jQuery PEP polyfill
  96504. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  96505. var context = VirtualJoystick.vjCanvas.getContext('2d');
  96506. if (!context) {
  96507. throw new Error("Unable to create canvas for virtual joystick");
  96508. }
  96509. VirtualJoystick.vjCanvasContext = context;
  96510. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  96511. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  96512. document.body.appendChild(VirtualJoystick.vjCanvas);
  96513. }
  96514. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  96515. this.pressed = false;
  96516. // default joystick color
  96517. this._joystickColor = "cyan";
  96518. this._joystickPointerID = -1;
  96519. // current joystick position
  96520. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  96521. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  96522. // origin joystick position
  96523. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  96524. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  96525. this._onPointerDownHandlerRef = function (evt) {
  96526. _this._onPointerDown(evt);
  96527. };
  96528. this._onPointerMoveHandlerRef = function (evt) {
  96529. _this._onPointerMove(evt);
  96530. };
  96531. this._onPointerUpHandlerRef = function (evt) {
  96532. _this._onPointerUp(evt);
  96533. };
  96534. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  96535. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  96536. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  96537. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  96538. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  96539. evt.preventDefault(); // Disables system menu
  96540. }, false);
  96541. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  96542. }
  96543. /**
  96544. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  96545. * @param newJoystickSensibility defines the new sensibility
  96546. */
  96547. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  96548. this._joystickSensibility = newJoystickSensibility;
  96549. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  96550. };
  96551. VirtualJoystick.prototype._onPointerDown = function (e) {
  96552. var positionOnScreenCondition;
  96553. e.preventDefault();
  96554. if (this._leftJoystick === true) {
  96555. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  96556. }
  96557. else {
  96558. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  96559. }
  96560. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  96561. // First contact will be dedicated to the virtual joystick
  96562. this._joystickPointerID = e.pointerId;
  96563. this._joystickPointerStartPos.x = e.clientX;
  96564. this._joystickPointerStartPos.y = e.clientY;
  96565. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  96566. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  96567. this._deltaJoystickVector.x = 0;
  96568. this._deltaJoystickVector.y = 0;
  96569. this.pressed = true;
  96570. this._touches.add(e.pointerId.toString(), e);
  96571. }
  96572. else {
  96573. // You can only trigger the action buttons with a joystick declared
  96574. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  96575. this._action();
  96576. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  96577. }
  96578. }
  96579. };
  96580. VirtualJoystick.prototype._onPointerMove = function (e) {
  96581. // If the current pointer is the one associated to the joystick (first touch contact)
  96582. if (this._joystickPointerID == e.pointerId) {
  96583. this._joystickPointerPos.x = e.clientX;
  96584. this._joystickPointerPos.y = e.clientY;
  96585. this._deltaJoystickVector = this._joystickPointerPos.clone();
  96586. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  96587. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  96588. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  96589. switch (this._axisTargetedByLeftAndRight) {
  96590. case JoystickAxis.X:
  96591. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  96592. break;
  96593. case JoystickAxis.Y:
  96594. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  96595. break;
  96596. case JoystickAxis.Z:
  96597. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  96598. break;
  96599. }
  96600. var directionUpDown = this.reverseUpDown ? 1 : -1;
  96601. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  96602. switch (this._axisTargetedByUpAndDown) {
  96603. case JoystickAxis.X:
  96604. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  96605. break;
  96606. case JoystickAxis.Y:
  96607. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  96608. break;
  96609. case JoystickAxis.Z:
  96610. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  96611. break;
  96612. }
  96613. }
  96614. else {
  96615. var data = this._touches.get(e.pointerId.toString());
  96616. if (data) {
  96617. data.x = e.clientX;
  96618. data.y = e.clientY;
  96619. }
  96620. }
  96621. };
  96622. VirtualJoystick.prototype._onPointerUp = function (e) {
  96623. if (this._joystickPointerID == e.pointerId) {
  96624. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  96625. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  96626. this._joystickPointerID = -1;
  96627. this.pressed = false;
  96628. }
  96629. else {
  96630. var touch = this._touches.get(e.pointerId.toString());
  96631. if (touch) {
  96632. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  96633. }
  96634. }
  96635. this._deltaJoystickVector.x = 0;
  96636. this._deltaJoystickVector.y = 0;
  96637. this._touches.remove(e.pointerId.toString());
  96638. };
  96639. /**
  96640. * Change the color of the virtual joystick
  96641. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  96642. */
  96643. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  96644. this._joystickColor = newColor;
  96645. };
  96646. /**
  96647. * Defines a callback to call when the joystick is touched
  96648. * @param action defines the callback
  96649. */
  96650. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  96651. this._action = action;
  96652. };
  96653. /**
  96654. * Defines which axis you'd like to control for left & right
  96655. * @param axis defines the axis to use
  96656. */
  96657. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  96658. switch (axis) {
  96659. case JoystickAxis.X:
  96660. case JoystickAxis.Y:
  96661. case JoystickAxis.Z:
  96662. this._axisTargetedByLeftAndRight = axis;
  96663. break;
  96664. default:
  96665. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  96666. break;
  96667. }
  96668. };
  96669. /**
  96670. * Defines which axis you'd like to control for up & down
  96671. * @param axis defines the axis to use
  96672. */
  96673. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  96674. switch (axis) {
  96675. case JoystickAxis.X:
  96676. case JoystickAxis.Y:
  96677. case JoystickAxis.Z:
  96678. this._axisTargetedByUpAndDown = axis;
  96679. break;
  96680. default:
  96681. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  96682. break;
  96683. }
  96684. };
  96685. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  96686. var _this = this;
  96687. if (this.pressed) {
  96688. this._touches.forEach(function (key, touch) {
  96689. if (touch.pointerId === _this._joystickPointerID) {
  96690. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  96691. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  96692. VirtualJoystick.vjCanvasContext.beginPath();
  96693. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  96694. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  96695. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  96696. VirtualJoystick.vjCanvasContext.stroke();
  96697. VirtualJoystick.vjCanvasContext.closePath();
  96698. VirtualJoystick.vjCanvasContext.beginPath();
  96699. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  96700. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  96701. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  96702. VirtualJoystick.vjCanvasContext.stroke();
  96703. VirtualJoystick.vjCanvasContext.closePath();
  96704. VirtualJoystick.vjCanvasContext.beginPath();
  96705. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  96706. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  96707. VirtualJoystick.vjCanvasContext.stroke();
  96708. VirtualJoystick.vjCanvasContext.closePath();
  96709. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  96710. }
  96711. else {
  96712. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  96713. VirtualJoystick.vjCanvasContext.beginPath();
  96714. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  96715. VirtualJoystick.vjCanvasContext.beginPath();
  96716. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  96717. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  96718. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  96719. VirtualJoystick.vjCanvasContext.stroke();
  96720. VirtualJoystick.vjCanvasContext.closePath();
  96721. touch.prevX = touch.x;
  96722. touch.prevY = touch.y;
  96723. }
  96724. ;
  96725. });
  96726. }
  96727. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  96728. };
  96729. /**
  96730. * Release internal HTML canvas
  96731. */
  96732. VirtualJoystick.prototype.releaseCanvas = function () {
  96733. if (VirtualJoystick.vjCanvas) {
  96734. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  96735. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  96736. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  96737. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  96738. window.removeEventListener("resize", this._onResize);
  96739. document.body.removeChild(VirtualJoystick.vjCanvas);
  96740. VirtualJoystick.vjCanvas = null;
  96741. }
  96742. };
  96743. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  96744. VirtualJoystick._globalJoystickIndex = 0;
  96745. return VirtualJoystick;
  96746. }());
  96747. BABYLON.VirtualJoystick = VirtualJoystick;
  96748. })(BABYLON || (BABYLON = {}));
  96749. //# sourceMappingURL=babylon.virtualJoystick.js.map
  96750. var BABYLON;
  96751. (function (BABYLON) {
  96752. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  96753. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  96754. });
  96755. // We're mainly based on the logic defined into the FreeCamera code
  96756. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  96757. __extends(VirtualJoysticksCamera, _super);
  96758. function VirtualJoysticksCamera(name, position, scene) {
  96759. var _this = _super.call(this, name, position, scene) || this;
  96760. _this.inputs.addVirtualJoystick();
  96761. return _this;
  96762. }
  96763. VirtualJoysticksCamera.prototype.getClassName = function () {
  96764. return "VirtualJoysticksCamera";
  96765. };
  96766. return VirtualJoysticksCamera;
  96767. }(BABYLON.FreeCamera));
  96768. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  96769. })(BABYLON || (BABYLON = {}));
  96770. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  96771. var BABYLON;
  96772. (function (BABYLON) {
  96773. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  96774. function FreeCameraVirtualJoystickInput() {
  96775. }
  96776. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  96777. return this._leftjoystick;
  96778. };
  96779. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  96780. return this._rightjoystick;
  96781. };
  96782. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  96783. if (this._leftjoystick) {
  96784. var camera = this.camera;
  96785. var speed = camera._computeLocalCameraSpeed() * 50;
  96786. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  96787. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  96788. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  96789. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  96790. if (!this._leftjoystick.pressed) {
  96791. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  96792. }
  96793. if (!this._rightjoystick.pressed) {
  96794. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  96795. }
  96796. }
  96797. };
  96798. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  96799. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  96800. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  96801. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  96802. this._leftjoystick.setJoystickSensibility(0.15);
  96803. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  96804. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  96805. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  96806. this._rightjoystick.reverseUpDown = true;
  96807. this._rightjoystick.setJoystickSensibility(0.05);
  96808. this._rightjoystick.setJoystickColor("yellow");
  96809. };
  96810. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  96811. this._leftjoystick.releaseCanvas();
  96812. this._rightjoystick.releaseCanvas();
  96813. };
  96814. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  96815. return "FreeCameraVirtualJoystickInput";
  96816. };
  96817. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  96818. return "virtualJoystick";
  96819. };
  96820. return FreeCameraVirtualJoystickInput;
  96821. }());
  96822. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  96823. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  96824. })(BABYLON || (BABYLON = {}));
  96825. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  96826. var BABYLON;
  96827. (function (BABYLON) {
  96828. var SimplificationSettings = /** @class */ (function () {
  96829. function SimplificationSettings(quality, distance, optimizeMesh) {
  96830. this.quality = quality;
  96831. this.distance = distance;
  96832. this.optimizeMesh = optimizeMesh;
  96833. }
  96834. return SimplificationSettings;
  96835. }());
  96836. BABYLON.SimplificationSettings = SimplificationSettings;
  96837. var SimplificationQueue = /** @class */ (function () {
  96838. function SimplificationQueue() {
  96839. this.running = false;
  96840. this._simplificationArray = [];
  96841. }
  96842. SimplificationQueue.prototype.addTask = function (task) {
  96843. this._simplificationArray.push(task);
  96844. };
  96845. SimplificationQueue.prototype.executeNext = function () {
  96846. var task = this._simplificationArray.pop();
  96847. if (task) {
  96848. this.running = true;
  96849. this.runSimplification(task);
  96850. }
  96851. else {
  96852. this.running = false;
  96853. }
  96854. };
  96855. SimplificationQueue.prototype.runSimplification = function (task) {
  96856. var _this = this;
  96857. if (task.parallelProcessing) {
  96858. //parallel simplifier
  96859. task.settings.forEach(function (setting) {
  96860. var simplifier = _this.getSimplifier(task);
  96861. simplifier.simplify(setting, function (newMesh) {
  96862. task.mesh.addLODLevel(setting.distance, newMesh);
  96863. newMesh.isVisible = true;
  96864. //check if it is the last
  96865. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  96866. //all done, run the success callback.
  96867. task.successCallback();
  96868. }
  96869. _this.executeNext();
  96870. });
  96871. });
  96872. }
  96873. else {
  96874. //single simplifier.
  96875. var simplifier = this.getSimplifier(task);
  96876. var runDecimation = function (setting, callback) {
  96877. simplifier.simplify(setting, function (newMesh) {
  96878. task.mesh.addLODLevel(setting.distance, newMesh);
  96879. newMesh.isVisible = true;
  96880. //run the next quality level
  96881. callback();
  96882. });
  96883. };
  96884. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  96885. runDecimation(task.settings[loop.index], function () {
  96886. loop.executeNext();
  96887. });
  96888. }, function () {
  96889. //execution ended, run the success callback.
  96890. if (task.successCallback) {
  96891. task.successCallback();
  96892. }
  96893. _this.executeNext();
  96894. });
  96895. }
  96896. };
  96897. SimplificationQueue.prototype.getSimplifier = function (task) {
  96898. switch (task.simplificationType) {
  96899. case SimplificationType.QUADRATIC:
  96900. default:
  96901. return new QuadraticErrorSimplification(task.mesh);
  96902. }
  96903. };
  96904. return SimplificationQueue;
  96905. }());
  96906. BABYLON.SimplificationQueue = SimplificationQueue;
  96907. /**
  96908. * The implemented types of simplification
  96909. * At the moment only Quadratic Error Decimation is implemented
  96910. */
  96911. var SimplificationType;
  96912. (function (SimplificationType) {
  96913. /** Quadratic error decimation */
  96914. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  96915. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  96916. var DecimationTriangle = /** @class */ (function () {
  96917. function DecimationTriangle(vertices) {
  96918. this.vertices = vertices;
  96919. this.error = new Array(4);
  96920. this.deleted = false;
  96921. this.isDirty = false;
  96922. this.deletePending = false;
  96923. this.borderFactor = 0;
  96924. }
  96925. return DecimationTriangle;
  96926. }());
  96927. BABYLON.DecimationTriangle = DecimationTriangle;
  96928. var DecimationVertex = /** @class */ (function () {
  96929. function DecimationVertex(position, id) {
  96930. this.position = position;
  96931. this.id = id;
  96932. this.isBorder = true;
  96933. this.q = new QuadraticMatrix();
  96934. this.triangleCount = 0;
  96935. this.triangleStart = 0;
  96936. this.originalOffsets = [];
  96937. }
  96938. DecimationVertex.prototype.updatePosition = function (newPosition) {
  96939. this.position.copyFrom(newPosition);
  96940. };
  96941. return DecimationVertex;
  96942. }());
  96943. BABYLON.DecimationVertex = DecimationVertex;
  96944. var QuadraticMatrix = /** @class */ (function () {
  96945. function QuadraticMatrix(data) {
  96946. this.data = new Array(10);
  96947. for (var i = 0; i < 10; ++i) {
  96948. if (data && data[i]) {
  96949. this.data[i] = data[i];
  96950. }
  96951. else {
  96952. this.data[i] = 0;
  96953. }
  96954. }
  96955. }
  96956. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  96957. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  96958. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  96959. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  96960. return det;
  96961. };
  96962. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  96963. for (var i = 0; i < 10; ++i) {
  96964. this.data[i] += matrix.data[i];
  96965. }
  96966. };
  96967. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  96968. for (var i = 0; i < 10; ++i) {
  96969. this.data[i] += data[i];
  96970. }
  96971. };
  96972. QuadraticMatrix.prototype.add = function (matrix) {
  96973. var m = new QuadraticMatrix();
  96974. for (var i = 0; i < 10; ++i) {
  96975. m.data[i] = this.data[i] + matrix.data[i];
  96976. }
  96977. return m;
  96978. };
  96979. QuadraticMatrix.FromData = function (a, b, c, d) {
  96980. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  96981. };
  96982. //returning an array to avoid garbage collection
  96983. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  96984. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  96985. };
  96986. return QuadraticMatrix;
  96987. }());
  96988. BABYLON.QuadraticMatrix = QuadraticMatrix;
  96989. var Reference = /** @class */ (function () {
  96990. function Reference(vertexId, triangleId) {
  96991. this.vertexId = vertexId;
  96992. this.triangleId = triangleId;
  96993. }
  96994. return Reference;
  96995. }());
  96996. BABYLON.Reference = Reference;
  96997. /**
  96998. * An implementation of the Quadratic Error simplification algorithm.
  96999. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  97000. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  97001. * @author RaananW
  97002. */
  97003. var QuadraticErrorSimplification = /** @class */ (function () {
  97004. function QuadraticErrorSimplification(_mesh) {
  97005. this._mesh = _mesh;
  97006. this.syncIterations = 5000;
  97007. this.aggressiveness = 7;
  97008. this.decimationIterations = 100;
  97009. this.boundingBoxEpsilon = BABYLON.Epsilon;
  97010. }
  97011. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  97012. var _this = this;
  97013. this.initDecimatedMesh();
  97014. //iterating through the submeshes array, one after the other.
  97015. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  97016. _this.initWithMesh(loop.index, function () {
  97017. _this.runDecimation(settings, loop.index, function () {
  97018. loop.executeNext();
  97019. });
  97020. }, settings.optimizeMesh);
  97021. }, function () {
  97022. setTimeout(function () {
  97023. successCallback(_this._reconstructedMesh);
  97024. }, 0);
  97025. });
  97026. };
  97027. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  97028. var _this = this;
  97029. var targetCount = ~~(this.triangles.length * settings.quality);
  97030. var deletedTriangles = 0;
  97031. var triangleCount = this.triangles.length;
  97032. var iterationFunction = function (iteration, callback) {
  97033. setTimeout(function () {
  97034. if (iteration % 5 === 0) {
  97035. _this.updateMesh(iteration === 0);
  97036. }
  97037. for (var i = 0; i < _this.triangles.length; ++i) {
  97038. _this.triangles[i].isDirty = false;
  97039. }
  97040. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  97041. var trianglesIterator = function (i) {
  97042. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  97043. var t = _this.triangles[tIdx];
  97044. if (!t)
  97045. return;
  97046. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  97047. return;
  97048. }
  97049. for (var j = 0; j < 3; ++j) {
  97050. if (t.error[j] < threshold) {
  97051. var deleted0 = [];
  97052. var deleted1 = [];
  97053. var v0 = t.vertices[j];
  97054. var v1 = t.vertices[(j + 1) % 3];
  97055. if (v0.isBorder || v1.isBorder)
  97056. continue;
  97057. var p = BABYLON.Vector3.Zero();
  97058. var n = BABYLON.Vector3.Zero();
  97059. var uv = BABYLON.Vector2.Zero();
  97060. var color = new BABYLON.Color4(0, 0, 0, 1);
  97061. _this.calculateError(v0, v1, p, n, uv, color);
  97062. var delTr = new Array();
  97063. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  97064. continue;
  97065. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  97066. continue;
  97067. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  97068. continue;
  97069. var uniqueArray = new Array();
  97070. delTr.forEach(function (deletedT) {
  97071. if (uniqueArray.indexOf(deletedT) === -1) {
  97072. deletedT.deletePending = true;
  97073. uniqueArray.push(deletedT);
  97074. }
  97075. });
  97076. if (uniqueArray.length % 2 !== 0) {
  97077. continue;
  97078. }
  97079. v0.q = v1.q.add(v0.q);
  97080. v0.updatePosition(p);
  97081. var tStart = _this.references.length;
  97082. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  97083. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  97084. var tCount = _this.references.length - tStart;
  97085. if (tCount <= v0.triangleCount) {
  97086. if (tCount) {
  97087. for (var c = 0; c < tCount; c++) {
  97088. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  97089. }
  97090. }
  97091. }
  97092. else {
  97093. v0.triangleStart = tStart;
  97094. }
  97095. v0.triangleCount = tCount;
  97096. break;
  97097. }
  97098. }
  97099. };
  97100. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  97101. }, 0);
  97102. };
  97103. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  97104. if (triangleCount - deletedTriangles <= targetCount)
  97105. loop.breakLoop();
  97106. else {
  97107. iterationFunction(loop.index, function () {
  97108. loop.executeNext();
  97109. });
  97110. }
  97111. }, function () {
  97112. setTimeout(function () {
  97113. //reconstruct this part of the mesh
  97114. _this.reconstructMesh(submeshIndex);
  97115. successCallback();
  97116. }, 0);
  97117. });
  97118. };
  97119. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  97120. var _this = this;
  97121. this.vertices = [];
  97122. this.triangles = [];
  97123. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  97124. var indices = this._mesh.getIndices();
  97125. var submesh = this._mesh.subMeshes[submeshIndex];
  97126. var findInVertices = function (positionToSearch) {
  97127. if (optimizeMesh) {
  97128. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  97129. if (_this.vertices[ii].position.equals(positionToSearch)) {
  97130. return _this.vertices[ii];
  97131. }
  97132. }
  97133. }
  97134. return null;
  97135. };
  97136. var vertexReferences = [];
  97137. var vertexInit = function (i) {
  97138. if (!positionData) {
  97139. return;
  97140. }
  97141. var offset = i + submesh.verticesStart;
  97142. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  97143. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  97144. vertex.originalOffsets.push(offset);
  97145. if (vertex.id === _this.vertices.length) {
  97146. _this.vertices.push(vertex);
  97147. }
  97148. vertexReferences.push(vertex.id);
  97149. };
  97150. //var totalVertices = mesh.getTotalVertices();
  97151. var totalVertices = submesh.verticesCount;
  97152. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  97153. var indicesInit = function (i) {
  97154. if (!indices) {
  97155. return;
  97156. }
  97157. var offset = (submesh.indexStart / 3) + i;
  97158. var pos = (offset * 3);
  97159. var i0 = indices[pos + 0];
  97160. var i1 = indices[pos + 1];
  97161. var i2 = indices[pos + 2];
  97162. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  97163. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  97164. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  97165. var triangle = new DecimationTriangle([v0, v1, v2]);
  97166. triangle.originalOffset = pos;
  97167. _this.triangles.push(triangle);
  97168. };
  97169. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  97170. _this.init(callback);
  97171. });
  97172. });
  97173. };
  97174. QuadraticErrorSimplification.prototype.init = function (callback) {
  97175. var _this = this;
  97176. var triangleInit1 = function (i) {
  97177. var t = _this.triangles[i];
  97178. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  97179. for (var j = 0; j < 3; j++) {
  97180. 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))));
  97181. }
  97182. };
  97183. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  97184. var triangleInit2 = function (i) {
  97185. var t = _this.triangles[i];
  97186. for (var j = 0; j < 3; ++j) {
  97187. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  97188. }
  97189. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  97190. };
  97191. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  97192. callback();
  97193. });
  97194. });
  97195. };
  97196. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  97197. var newTriangles = [];
  97198. var i;
  97199. for (i = 0; i < this.vertices.length; ++i) {
  97200. this.vertices[i].triangleCount = 0;
  97201. }
  97202. var t;
  97203. var j;
  97204. for (i = 0; i < this.triangles.length; ++i) {
  97205. if (!this.triangles[i].deleted) {
  97206. t = this.triangles[i];
  97207. for (j = 0; j < 3; ++j) {
  97208. t.vertices[j].triangleCount = 1;
  97209. }
  97210. newTriangles.push(t);
  97211. }
  97212. }
  97213. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  97214. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  97215. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  97216. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  97217. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  97218. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  97219. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  97220. var vertexCount = 0;
  97221. for (i = 0; i < this.vertices.length; ++i) {
  97222. var vertex = this.vertices[i];
  97223. vertex.id = vertexCount;
  97224. if (vertex.triangleCount) {
  97225. vertex.originalOffsets.forEach(function (originalOffset) {
  97226. if (!normalData) {
  97227. return;
  97228. }
  97229. newPositionData.push(vertex.position.x);
  97230. newPositionData.push(vertex.position.y);
  97231. newPositionData.push(vertex.position.z);
  97232. newNormalData.push(normalData[originalOffset * 3]);
  97233. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  97234. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  97235. if (uvs && uvs.length) {
  97236. newUVsData.push(uvs[(originalOffset * 2)]);
  97237. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  97238. }
  97239. else if (colorsData && colorsData.length) {
  97240. newColorsData.push(colorsData[(originalOffset * 4)]);
  97241. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  97242. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  97243. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  97244. }
  97245. ++vertexCount;
  97246. });
  97247. }
  97248. }
  97249. var startingIndex = this._reconstructedMesh.getTotalIndices();
  97250. var startingVertex = this._reconstructedMesh.getTotalVertices();
  97251. var submeshesArray = this._reconstructedMesh.subMeshes;
  97252. this._reconstructedMesh.subMeshes = [];
  97253. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  97254. var originalIndices = this._mesh.getIndices();
  97255. for (i = 0; i < newTriangles.length; ++i) {
  97256. t = newTriangles[i]; //now get the new referencing point for each vertex
  97257. [0, 1, 2].forEach(function (idx) {
  97258. var id = originalIndices[t.originalOffset + idx];
  97259. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  97260. if (offset < 0)
  97261. offset = 0;
  97262. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  97263. });
  97264. }
  97265. //overwriting the old vertex buffers and indices.
  97266. this._reconstructedMesh.setIndices(newIndicesArray);
  97267. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  97268. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  97269. if (newUVsData.length > 0)
  97270. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  97271. if (newColorsData.length > 0)
  97272. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  97273. //create submesh
  97274. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  97275. if (submeshIndex > 0) {
  97276. this._reconstructedMesh.subMeshes = [];
  97277. submeshesArray.forEach(function (submesh) {
  97278. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  97279. });
  97280. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  97281. }
  97282. };
  97283. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  97284. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  97285. this._reconstructedMesh.material = this._mesh.material;
  97286. this._reconstructedMesh.parent = this._mesh.parent;
  97287. this._reconstructedMesh.isVisible = false;
  97288. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  97289. };
  97290. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  97291. for (var i = 0; i < vertex1.triangleCount; ++i) {
  97292. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  97293. if (t.deleted)
  97294. continue;
  97295. var s = this.references[vertex1.triangleStart + i].vertexId;
  97296. var v1 = t.vertices[(s + 1) % 3];
  97297. var v2 = t.vertices[(s + 2) % 3];
  97298. if ((v1 === vertex2 || v2 === vertex2)) {
  97299. deletedArray[i] = true;
  97300. delTr.push(t);
  97301. continue;
  97302. }
  97303. var d1 = v1.position.subtract(point);
  97304. d1 = d1.normalize();
  97305. var d2 = v2.position.subtract(point);
  97306. d2 = d2.normalize();
  97307. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  97308. return true;
  97309. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  97310. deletedArray[i] = false;
  97311. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  97312. return true;
  97313. }
  97314. return false;
  97315. };
  97316. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  97317. var newDeleted = deletedTriangles;
  97318. for (var i = 0; i < vertex.triangleCount; ++i) {
  97319. var ref = this.references[vertex.triangleStart + i];
  97320. var t = this.triangles[ref.triangleId];
  97321. if (t.deleted)
  97322. continue;
  97323. if (deletedArray[i] && t.deletePending) {
  97324. t.deleted = true;
  97325. newDeleted++;
  97326. continue;
  97327. }
  97328. t.vertices[ref.vertexId] = origVertex;
  97329. t.isDirty = true;
  97330. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  97331. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  97332. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  97333. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  97334. this.references.push(ref);
  97335. }
  97336. return newDeleted;
  97337. };
  97338. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  97339. for (var i = 0; i < this.vertices.length; ++i) {
  97340. var vCount = [];
  97341. var vId = [];
  97342. var v = this.vertices[i];
  97343. var j;
  97344. for (j = 0; j < v.triangleCount; ++j) {
  97345. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  97346. for (var ii = 0; ii < 3; ii++) {
  97347. var ofs = 0;
  97348. var vv = triangle.vertices[ii];
  97349. while (ofs < vCount.length) {
  97350. if (vId[ofs] === vv.id)
  97351. break;
  97352. ++ofs;
  97353. }
  97354. if (ofs === vCount.length) {
  97355. vCount.push(1);
  97356. vId.push(vv.id);
  97357. }
  97358. else {
  97359. vCount[ofs]++;
  97360. }
  97361. }
  97362. }
  97363. for (j = 0; j < vCount.length; ++j) {
  97364. if (vCount[j] === 1) {
  97365. this.vertices[vId[j]].isBorder = true;
  97366. }
  97367. else {
  97368. this.vertices[vId[j]].isBorder = false;
  97369. }
  97370. }
  97371. }
  97372. };
  97373. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  97374. if (identifyBorders === void 0) { identifyBorders = false; }
  97375. var i;
  97376. if (!identifyBorders) {
  97377. var newTrianglesVector = [];
  97378. for (i = 0; i < this.triangles.length; ++i) {
  97379. if (!this.triangles[i].deleted) {
  97380. newTrianglesVector.push(this.triangles[i]);
  97381. }
  97382. }
  97383. this.triangles = newTrianglesVector;
  97384. }
  97385. for (i = 0; i < this.vertices.length; ++i) {
  97386. this.vertices[i].triangleCount = 0;
  97387. this.vertices[i].triangleStart = 0;
  97388. }
  97389. var t;
  97390. var j;
  97391. var v;
  97392. for (i = 0; i < this.triangles.length; ++i) {
  97393. t = this.triangles[i];
  97394. for (j = 0; j < 3; ++j) {
  97395. v = t.vertices[j];
  97396. v.triangleCount++;
  97397. }
  97398. }
  97399. var tStart = 0;
  97400. for (i = 0; i < this.vertices.length; ++i) {
  97401. this.vertices[i].triangleStart = tStart;
  97402. tStart += this.vertices[i].triangleCount;
  97403. this.vertices[i].triangleCount = 0;
  97404. }
  97405. var newReferences = new Array(this.triangles.length * 3);
  97406. for (i = 0; i < this.triangles.length; ++i) {
  97407. t = this.triangles[i];
  97408. for (j = 0; j < 3; ++j) {
  97409. v = t.vertices[j];
  97410. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  97411. v.triangleCount++;
  97412. }
  97413. }
  97414. this.references = newReferences;
  97415. if (identifyBorders) {
  97416. this.identifyBorder();
  97417. }
  97418. };
  97419. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  97420. var x = point.x;
  97421. var y = point.y;
  97422. var z = point.z;
  97423. 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
  97424. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  97425. };
  97426. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  97427. var q = vertex1.q.add(vertex2.q);
  97428. var border = vertex1.isBorder && vertex2.isBorder;
  97429. var error = 0;
  97430. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  97431. if (qDet !== 0 && !border) {
  97432. if (!pointResult) {
  97433. pointResult = BABYLON.Vector3.Zero();
  97434. }
  97435. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  97436. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  97437. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  97438. error = this.vertexError(q, pointResult);
  97439. }
  97440. else {
  97441. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  97442. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  97443. var error1 = this.vertexError(q, vertex1.position);
  97444. var error2 = this.vertexError(q, vertex2.position);
  97445. var error3 = this.vertexError(q, p3);
  97446. error = Math.min(error1, error2, error3);
  97447. if (error === error1) {
  97448. if (pointResult) {
  97449. pointResult.copyFrom(vertex1.position);
  97450. }
  97451. }
  97452. else if (error === error2) {
  97453. if (pointResult) {
  97454. pointResult.copyFrom(vertex2.position);
  97455. }
  97456. }
  97457. else {
  97458. if (pointResult) {
  97459. pointResult.copyFrom(p3);
  97460. }
  97461. }
  97462. }
  97463. return error;
  97464. };
  97465. return QuadraticErrorSimplification;
  97466. }());
  97467. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  97468. })(BABYLON || (BABYLON = {}));
  97469. //# sourceMappingURL=babylon.meshSimplification.js.map
  97470. var BABYLON;
  97471. (function (BABYLON) {
  97472. var MeshLODLevel = /** @class */ (function () {
  97473. function MeshLODLevel(distance, mesh) {
  97474. this.distance = distance;
  97475. this.mesh = mesh;
  97476. }
  97477. return MeshLODLevel;
  97478. }());
  97479. BABYLON.MeshLODLevel = MeshLODLevel;
  97480. })(BABYLON || (BABYLON = {}));
  97481. //# sourceMappingURL=babylon.meshLODLevel.js.map
  97482. var BABYLON;
  97483. (function (BABYLON) {
  97484. /**
  97485. * Defines the root class used to create scene optimization to use with SceneOptimizer
  97486. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  97487. */
  97488. var SceneOptimization = /** @class */ (function () {
  97489. /**
  97490. * Creates the SceneOptimization object
  97491. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  97492. * @param desc defines the description associated with the optimization
  97493. */
  97494. function SceneOptimization(
  97495. /**
  97496. * Defines the priority of this optimization (0 by default which means first in the list)
  97497. */
  97498. priority) {
  97499. if (priority === void 0) { priority = 0; }
  97500. this.priority = priority;
  97501. }
  97502. /**
  97503. * Gets a string describing the action executed by the current optimization
  97504. * @returns description string
  97505. */
  97506. SceneOptimization.prototype.getDescription = function () {
  97507. return "";
  97508. };
  97509. /**
  97510. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  97511. * @param scene defines the current scene where to apply this optimization
  97512. * @param optimizer defines the current optimizer
  97513. * @returns true if everything that can be done was applied
  97514. */
  97515. SceneOptimization.prototype.apply = function (scene, optimizer) {
  97516. return true;
  97517. };
  97518. ;
  97519. return SceneOptimization;
  97520. }());
  97521. BABYLON.SceneOptimization = SceneOptimization;
  97522. /**
  97523. * Defines an optimization used to reduce the size of render target textures
  97524. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  97525. */
  97526. var TextureOptimization = /** @class */ (function (_super) {
  97527. __extends(TextureOptimization, _super);
  97528. /**
  97529. * Creates the TextureOptimization object
  97530. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  97531. * @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
  97532. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  97533. */
  97534. function TextureOptimization(
  97535. /**
  97536. * Defines the priority of this optimization (0 by default which means first in the list)
  97537. */
  97538. priority,
  97539. /**
  97540. * 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
  97541. */
  97542. maximumSize,
  97543. /**
  97544. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  97545. */
  97546. step) {
  97547. if (priority === void 0) { priority = 0; }
  97548. if (maximumSize === void 0) { maximumSize = 1024; }
  97549. if (step === void 0) { step = 0.5; }
  97550. var _this = _super.call(this, priority) || this;
  97551. _this.priority = priority;
  97552. _this.maximumSize = maximumSize;
  97553. _this.step = step;
  97554. return _this;
  97555. }
  97556. /**
  97557. * Gets a string describing the action executed by the current optimization
  97558. * @returns description string
  97559. */
  97560. TextureOptimization.prototype.getDescription = function () {
  97561. return "Reducing render target texture size to " + this.maximumSize;
  97562. };
  97563. /**
  97564. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  97565. * @param scene defines the current scene where to apply this optimization
  97566. * @param optimizer defines the current optimizer
  97567. * @returns true if everything that can be done was applied
  97568. */
  97569. TextureOptimization.prototype.apply = function (scene, optimizer) {
  97570. var allDone = true;
  97571. for (var index = 0; index < scene.textures.length; index++) {
  97572. var texture = scene.textures[index];
  97573. if (!texture.canRescale || texture.getContext) {
  97574. continue;
  97575. }
  97576. var currentSize = texture.getSize();
  97577. var maxDimension = Math.max(currentSize.width, currentSize.height);
  97578. if (maxDimension > this.maximumSize) {
  97579. texture.scale(this.step);
  97580. allDone = false;
  97581. }
  97582. }
  97583. return allDone;
  97584. };
  97585. return TextureOptimization;
  97586. }(SceneOptimization));
  97587. BABYLON.TextureOptimization = TextureOptimization;
  97588. /**
  97589. * Defines an optimization used to increase or decrease the rendering resolution
  97590. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  97591. */
  97592. var HardwareScalingOptimization = /** @class */ (function (_super) {
  97593. __extends(HardwareScalingOptimization, _super);
  97594. /**
  97595. * Creates the HardwareScalingOptimization object
  97596. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  97597. * @param maximumScale defines the maximum scale to use (2 by default)
  97598. * @param step defines the step to use between two passes (0.5 by default)
  97599. */
  97600. function HardwareScalingOptimization(
  97601. /**
  97602. * Defines the priority of this optimization (0 by default which means first in the list)
  97603. */
  97604. priority,
  97605. /**
  97606. * Defines the maximum scale to use (2 by default)
  97607. */
  97608. maximumScale,
  97609. /**
  97610. * Defines the step to use between two passes (0.5 by default)
  97611. */
  97612. step) {
  97613. if (priority === void 0) { priority = 0; }
  97614. if (maximumScale === void 0) { maximumScale = 2; }
  97615. if (step === void 0) { step = 0.25; }
  97616. var _this = _super.call(this, priority) || this;
  97617. _this.priority = priority;
  97618. _this.maximumScale = maximumScale;
  97619. _this.step = step;
  97620. _this._currentScale = -1;
  97621. _this._directionOffset = 1;
  97622. return _this;
  97623. }
  97624. /**
  97625. * Gets a string describing the action executed by the current optimization
  97626. * @return description string
  97627. */
  97628. HardwareScalingOptimization.prototype.getDescription = function () {
  97629. return "Setting hardware scaling level to " + this._currentScale;
  97630. };
  97631. /**
  97632. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  97633. * @param scene defines the current scene where to apply this optimization
  97634. * @param optimizer defines the current optimizer
  97635. * @returns true if everything that can be done was applied
  97636. */
  97637. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  97638. if (this._currentScale === -1) {
  97639. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  97640. if (this._currentScale > this.maximumScale) {
  97641. this._directionOffset = -1;
  97642. }
  97643. }
  97644. this._currentScale += this._directionOffset * this.step;
  97645. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  97646. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  97647. };
  97648. ;
  97649. return HardwareScalingOptimization;
  97650. }(SceneOptimization));
  97651. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  97652. /**
  97653. * Defines an optimization used to remove shadows
  97654. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  97655. */
  97656. var ShadowsOptimization = /** @class */ (function (_super) {
  97657. __extends(ShadowsOptimization, _super);
  97658. function ShadowsOptimization() {
  97659. return _super !== null && _super.apply(this, arguments) || this;
  97660. }
  97661. /**
  97662. * Gets a string describing the action executed by the current optimization
  97663. * @return description string
  97664. */
  97665. ShadowsOptimization.prototype.getDescription = function () {
  97666. return "Turning shadows on/off";
  97667. };
  97668. /**
  97669. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  97670. * @param scene defines the current scene where to apply this optimization
  97671. * @param optimizer defines the current optimizer
  97672. * @returns true if everything that can be done was applied
  97673. */
  97674. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  97675. scene.shadowsEnabled = optimizer.isInImprovementMode;
  97676. return true;
  97677. };
  97678. ;
  97679. return ShadowsOptimization;
  97680. }(SceneOptimization));
  97681. BABYLON.ShadowsOptimization = ShadowsOptimization;
  97682. /**
  97683. * Defines an optimization used to turn post-processes off
  97684. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  97685. */
  97686. var PostProcessesOptimization = /** @class */ (function (_super) {
  97687. __extends(PostProcessesOptimization, _super);
  97688. function PostProcessesOptimization() {
  97689. return _super !== null && _super.apply(this, arguments) || this;
  97690. }
  97691. /**
  97692. * Gets a string describing the action executed by the current optimization
  97693. * @return description string
  97694. */
  97695. PostProcessesOptimization.prototype.getDescription = function () {
  97696. return "Turning post-processes on/off";
  97697. };
  97698. /**
  97699. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  97700. * @param scene defines the current scene where to apply this optimization
  97701. * @param optimizer defines the current optimizer
  97702. * @returns true if everything that can be done was applied
  97703. */
  97704. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  97705. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  97706. return true;
  97707. };
  97708. ;
  97709. return PostProcessesOptimization;
  97710. }(SceneOptimization));
  97711. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  97712. /**
  97713. * Defines an optimization used to turn lens flares off
  97714. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  97715. */
  97716. var LensFlaresOptimization = /** @class */ (function (_super) {
  97717. __extends(LensFlaresOptimization, _super);
  97718. function LensFlaresOptimization() {
  97719. return _super !== null && _super.apply(this, arguments) || this;
  97720. }
  97721. /**
  97722. * Gets a string describing the action executed by the current optimization
  97723. * @return description string
  97724. */
  97725. LensFlaresOptimization.prototype.getDescription = function () {
  97726. return "Turning lens flares on/off";
  97727. };
  97728. /**
  97729. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  97730. * @param scene defines the current scene where to apply this optimization
  97731. * @param optimizer defines the current optimizer
  97732. * @returns true if everything that can be done was applied
  97733. */
  97734. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  97735. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  97736. return true;
  97737. };
  97738. ;
  97739. return LensFlaresOptimization;
  97740. }(SceneOptimization));
  97741. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  97742. /**
  97743. * Defines an optimization based on user defined callback.
  97744. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  97745. */
  97746. var CustomOptimization = /** @class */ (function (_super) {
  97747. __extends(CustomOptimization, _super);
  97748. function CustomOptimization() {
  97749. return _super !== null && _super.apply(this, arguments) || this;
  97750. }
  97751. /**
  97752. * Gets a string describing the action executed by the current optimization
  97753. * @returns description string
  97754. */
  97755. CustomOptimization.prototype.getDescription = function () {
  97756. if (this.onGetDescription) {
  97757. return this.onGetDescription();
  97758. }
  97759. return "Running user defined callback";
  97760. };
  97761. /**
  97762. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  97763. * @param scene defines the current scene where to apply this optimization
  97764. * @param optimizer defines the current optimizer
  97765. * @returns true if everything that can be done was applied
  97766. */
  97767. CustomOptimization.prototype.apply = function (scene, optimizer) {
  97768. if (this.onApply) {
  97769. return this.onApply(scene, optimizer);
  97770. }
  97771. return true;
  97772. };
  97773. ;
  97774. return CustomOptimization;
  97775. }(SceneOptimization));
  97776. BABYLON.CustomOptimization = CustomOptimization;
  97777. /**
  97778. * Defines an optimization used to turn particles off
  97779. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  97780. */
  97781. var ParticlesOptimization = /** @class */ (function (_super) {
  97782. __extends(ParticlesOptimization, _super);
  97783. function ParticlesOptimization() {
  97784. return _super !== null && _super.apply(this, arguments) || this;
  97785. }
  97786. /**
  97787. * Gets a string describing the action executed by the current optimization
  97788. * @return description string
  97789. */
  97790. ParticlesOptimization.prototype.getDescription = function () {
  97791. return "Turning particles on/off";
  97792. };
  97793. /**
  97794. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  97795. * @param scene defines the current scene where to apply this optimization
  97796. * @param optimizer defines the current optimizer
  97797. * @returns true if everything that can be done was applied
  97798. */
  97799. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  97800. scene.particlesEnabled = optimizer.isInImprovementMode;
  97801. return true;
  97802. };
  97803. ;
  97804. return ParticlesOptimization;
  97805. }(SceneOptimization));
  97806. BABYLON.ParticlesOptimization = ParticlesOptimization;
  97807. /**
  97808. * Defines an optimization used to turn render targets off
  97809. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  97810. */
  97811. var RenderTargetsOptimization = /** @class */ (function (_super) {
  97812. __extends(RenderTargetsOptimization, _super);
  97813. function RenderTargetsOptimization() {
  97814. return _super !== null && _super.apply(this, arguments) || this;
  97815. }
  97816. /**
  97817. * Gets a string describing the action executed by the current optimization
  97818. * @return description string
  97819. */
  97820. RenderTargetsOptimization.prototype.getDescription = function () {
  97821. return "Turning render targets off";
  97822. };
  97823. /**
  97824. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  97825. * @param scene defines the current scene where to apply this optimization
  97826. * @param optimizer defines the current optimizer
  97827. * @returns true if everything that can be done was applied
  97828. */
  97829. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  97830. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  97831. return true;
  97832. };
  97833. ;
  97834. return RenderTargetsOptimization;
  97835. }(SceneOptimization));
  97836. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  97837. /**
  97838. * Defines an optimization used to merge meshes with compatible materials
  97839. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  97840. */
  97841. var MergeMeshesOptimization = /** @class */ (function (_super) {
  97842. __extends(MergeMeshesOptimization, _super);
  97843. function MergeMeshesOptimization() {
  97844. var _this = _super !== null && _super.apply(this, arguments) || this;
  97845. _this._canBeMerged = function (abstractMesh) {
  97846. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  97847. return false;
  97848. }
  97849. var mesh = abstractMesh;
  97850. if (mesh.isDisposed()) {
  97851. return false;
  97852. }
  97853. if (!mesh.isVisible || !mesh.isEnabled()) {
  97854. return false;
  97855. }
  97856. if (mesh.instances.length > 0) {
  97857. return false;
  97858. }
  97859. if (mesh.skeleton || mesh.hasLODLevels) {
  97860. return false;
  97861. }
  97862. return true;
  97863. };
  97864. return _this;
  97865. }
  97866. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  97867. /**
  97868. * Gets or sets a boolean which defines if optimization octree has to be updated
  97869. */
  97870. get: function () {
  97871. return MergeMeshesOptimization._UpdateSelectionTree;
  97872. },
  97873. /**
  97874. * Gets or sets a boolean which defines if optimization octree has to be updated
  97875. */
  97876. set: function (value) {
  97877. MergeMeshesOptimization._UpdateSelectionTree = value;
  97878. },
  97879. enumerable: true,
  97880. configurable: true
  97881. });
  97882. /**
  97883. * Gets a string describing the action executed by the current optimization
  97884. * @return description string
  97885. */
  97886. MergeMeshesOptimization.prototype.getDescription = function () {
  97887. return "Merging similar meshes together";
  97888. };
  97889. /**
  97890. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  97891. * @param scene defines the current scene where to apply this optimization
  97892. * @param optimizer defines the current optimizer
  97893. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  97894. * @returns true if everything that can be done was applied
  97895. */
  97896. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  97897. var globalPool = scene.meshes.slice(0);
  97898. var globalLength = globalPool.length;
  97899. for (var index = 0; index < globalLength; index++) {
  97900. var currentPool = new Array();
  97901. var current = globalPool[index];
  97902. // Checks
  97903. if (!this._canBeMerged(current)) {
  97904. continue;
  97905. }
  97906. currentPool.push(current);
  97907. // Find compatible meshes
  97908. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  97909. var otherMesh = globalPool[subIndex];
  97910. if (!this._canBeMerged(otherMesh)) {
  97911. continue;
  97912. }
  97913. if (otherMesh.material !== current.material) {
  97914. continue;
  97915. }
  97916. if (otherMesh.checkCollisions !== current.checkCollisions) {
  97917. continue;
  97918. }
  97919. currentPool.push(otherMesh);
  97920. globalLength--;
  97921. globalPool.splice(subIndex, 1);
  97922. subIndex--;
  97923. }
  97924. if (currentPool.length < 2) {
  97925. continue;
  97926. }
  97927. // Merge meshes
  97928. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  97929. }
  97930. if (updateSelectionTree != undefined) {
  97931. if (updateSelectionTree) {
  97932. scene.createOrUpdateSelectionOctree();
  97933. }
  97934. }
  97935. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  97936. scene.createOrUpdateSelectionOctree();
  97937. }
  97938. return true;
  97939. };
  97940. ;
  97941. MergeMeshesOptimization._UpdateSelectionTree = false;
  97942. return MergeMeshesOptimization;
  97943. }(SceneOptimization));
  97944. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  97945. /**
  97946. * Defines a list of options used by SceneOptimizer
  97947. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  97948. */
  97949. var SceneOptimizerOptions = /** @class */ (function () {
  97950. /**
  97951. * Creates a new list of options used by SceneOptimizer
  97952. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  97953. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  97954. */
  97955. function SceneOptimizerOptions(
  97956. /**
  97957. * Defines the target frame rate to reach (60 by default)
  97958. */
  97959. targetFrameRate,
  97960. /**
  97961. * Defines the interval between two checkes (2000ms by default)
  97962. */
  97963. trackerDuration) {
  97964. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  97965. if (trackerDuration === void 0) { trackerDuration = 2000; }
  97966. this.targetFrameRate = targetFrameRate;
  97967. this.trackerDuration = trackerDuration;
  97968. /**
  97969. * Gets the list of optimizations to apply
  97970. */
  97971. this.optimizations = new Array();
  97972. }
  97973. /**
  97974. * Add a new optimization
  97975. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  97976. * @returns the current SceneOptimizerOptions
  97977. */
  97978. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  97979. this.optimizations.push(optimization);
  97980. return this;
  97981. };
  97982. /**
  97983. * Add a new custom optimization
  97984. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  97985. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  97986. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  97987. * @returns the current SceneOptimizerOptions
  97988. */
  97989. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  97990. if (priority === void 0) { priority = 0; }
  97991. var optimization = new CustomOptimization(priority);
  97992. optimization.onApply = onApply;
  97993. optimization.onGetDescription = onGetDescription;
  97994. this.optimizations.push(optimization);
  97995. return this;
  97996. };
  97997. /**
  97998. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  97999. * @param targetFrameRate defines the target frame rate (60 by default)
  98000. * @returns a SceneOptimizerOptions object
  98001. */
  98002. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  98003. var result = new SceneOptimizerOptions(targetFrameRate);
  98004. var priority = 0;
  98005. result.addOptimization(new MergeMeshesOptimization(priority));
  98006. result.addOptimization(new ShadowsOptimization(priority));
  98007. result.addOptimization(new LensFlaresOptimization(priority));
  98008. // Next priority
  98009. priority++;
  98010. result.addOptimization(new PostProcessesOptimization(priority));
  98011. result.addOptimization(new ParticlesOptimization(priority));
  98012. // Next priority
  98013. priority++;
  98014. result.addOptimization(new TextureOptimization(priority, 1024));
  98015. return result;
  98016. };
  98017. /**
  98018. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  98019. * @param targetFrameRate defines the target frame rate (60 by default)
  98020. * @returns a SceneOptimizerOptions object
  98021. */
  98022. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  98023. var result = new SceneOptimizerOptions(targetFrameRate);
  98024. var priority = 0;
  98025. result.addOptimization(new MergeMeshesOptimization(priority));
  98026. result.addOptimization(new ShadowsOptimization(priority));
  98027. result.addOptimization(new LensFlaresOptimization(priority));
  98028. // Next priority
  98029. priority++;
  98030. result.addOptimization(new PostProcessesOptimization(priority));
  98031. result.addOptimization(new ParticlesOptimization(priority));
  98032. // Next priority
  98033. priority++;
  98034. result.addOptimization(new TextureOptimization(priority, 512));
  98035. // Next priority
  98036. priority++;
  98037. result.addOptimization(new RenderTargetsOptimization(priority));
  98038. // Next priority
  98039. priority++;
  98040. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  98041. return result;
  98042. };
  98043. /**
  98044. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  98045. * @param targetFrameRate defines the target frame rate (60 by default)
  98046. * @returns a SceneOptimizerOptions object
  98047. */
  98048. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  98049. var result = new SceneOptimizerOptions(targetFrameRate);
  98050. var priority = 0;
  98051. result.addOptimization(new MergeMeshesOptimization(priority));
  98052. result.addOptimization(new ShadowsOptimization(priority));
  98053. result.addOptimization(new LensFlaresOptimization(priority));
  98054. // Next priority
  98055. priority++;
  98056. result.addOptimization(new PostProcessesOptimization(priority));
  98057. result.addOptimization(new ParticlesOptimization(priority));
  98058. // Next priority
  98059. priority++;
  98060. result.addOptimization(new TextureOptimization(priority, 256));
  98061. // Next priority
  98062. priority++;
  98063. result.addOptimization(new RenderTargetsOptimization(priority));
  98064. // Next priority
  98065. priority++;
  98066. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  98067. return result;
  98068. };
  98069. return SceneOptimizerOptions;
  98070. }());
  98071. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  98072. /**
  98073. * Class used to run optimizations in order to reach a target frame rate
  98074. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  98075. */
  98076. var SceneOptimizer = /** @class */ (function () {
  98077. /**
  98078. * Creates a new SceneOptimizer
  98079. * @param scene defines the scene to work on
  98080. * @param options defines the options to use with the SceneOptimizer
  98081. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  98082. * @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)
  98083. */
  98084. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  98085. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  98086. if (improvementMode === void 0) { improvementMode = false; }
  98087. var _this = this;
  98088. this._isRunning = false;
  98089. this._currentPriorityLevel = 0;
  98090. this._targetFrameRate = 60;
  98091. this._trackerDuration = 2000;
  98092. this._currentFrameRate = 0;
  98093. this._improvementMode = false;
  98094. /**
  98095. * Defines an observable called when the optimizer reaches the target frame rate
  98096. */
  98097. this.onSuccessObservable = new BABYLON.Observable();
  98098. /**
  98099. * Defines an observable called when the optimizer enables an optimization
  98100. */
  98101. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  98102. /**
  98103. * Defines an observable called when the optimizer is not able to reach the target frame rate
  98104. */
  98105. this.onFailureObservable = new BABYLON.Observable();
  98106. if (!options) {
  98107. this._options = new SceneOptimizerOptions();
  98108. }
  98109. else {
  98110. this._options = options;
  98111. }
  98112. if (this._options.targetFrameRate) {
  98113. this._targetFrameRate = this._options.targetFrameRate;
  98114. }
  98115. if (this._options.trackerDuration) {
  98116. this._trackerDuration = this._options.trackerDuration;
  98117. }
  98118. if (autoGeneratePriorities) {
  98119. var priority = 0;
  98120. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  98121. var optim = _a[_i];
  98122. optim.priority = priority++;
  98123. }
  98124. }
  98125. this._improvementMode = improvementMode;
  98126. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  98127. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  98128. _this._sceneDisposeObserver = null;
  98129. _this.dispose();
  98130. });
  98131. }
  98132. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  98133. /**
  98134. * Gets a boolean indicating if the optimizer is in improvement mode
  98135. */
  98136. get: function () {
  98137. return this._improvementMode;
  98138. },
  98139. enumerable: true,
  98140. configurable: true
  98141. });
  98142. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  98143. /**
  98144. * Gets the current priority level (0 at start)
  98145. */
  98146. get: function () {
  98147. return this._currentPriorityLevel;
  98148. },
  98149. enumerable: true,
  98150. configurable: true
  98151. });
  98152. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  98153. /**
  98154. * Gets the current frame rate checked by the SceneOptimizer
  98155. */
  98156. get: function () {
  98157. return this._currentFrameRate;
  98158. },
  98159. enumerable: true,
  98160. configurable: true
  98161. });
  98162. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  98163. /**
  98164. * Gets or sets the current target frame rate (60 by default)
  98165. */
  98166. get: function () {
  98167. return this._targetFrameRate;
  98168. },
  98169. /**
  98170. * Gets or sets the current target frame rate (60 by default)
  98171. */
  98172. set: function (value) {
  98173. this._targetFrameRate = value;
  98174. },
  98175. enumerable: true,
  98176. configurable: true
  98177. });
  98178. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  98179. /**
  98180. * Gets or sets the current interval between two checks (every 2000ms by default)
  98181. */
  98182. get: function () {
  98183. return this._trackerDuration;
  98184. },
  98185. /**
  98186. * Gets or sets the current interval between two checks (every 2000ms by default)
  98187. */
  98188. set: function (value) {
  98189. this._trackerDuration = value;
  98190. },
  98191. enumerable: true,
  98192. configurable: true
  98193. });
  98194. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  98195. /**
  98196. * Gets the list of active optimizations
  98197. */
  98198. get: function () {
  98199. return this._options.optimizations;
  98200. },
  98201. enumerable: true,
  98202. configurable: true
  98203. });
  98204. /**
  98205. * Stops the current optimizer
  98206. */
  98207. SceneOptimizer.prototype.stop = function () {
  98208. this._isRunning = false;
  98209. };
  98210. /**
  98211. * Reset the optimizer to initial step (current priority level = 0)
  98212. */
  98213. SceneOptimizer.prototype.reset = function () {
  98214. this._currentPriorityLevel = 0;
  98215. };
  98216. /**
  98217. * Start the optimizer. By default it will try to reach a specific framerate
  98218. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  98219. */
  98220. SceneOptimizer.prototype.start = function () {
  98221. var _this = this;
  98222. if (this._isRunning) {
  98223. return;
  98224. }
  98225. this._isRunning = true;
  98226. // Let's wait for the scene to be ready before running our check
  98227. this._scene.executeWhenReady(function () {
  98228. setTimeout(function () {
  98229. _this._checkCurrentState();
  98230. }, _this._trackerDuration);
  98231. });
  98232. };
  98233. SceneOptimizer.prototype._checkCurrentState = function () {
  98234. var _this = this;
  98235. if (!this._isRunning) {
  98236. return;
  98237. }
  98238. var scene = this._scene;
  98239. var options = this._options;
  98240. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  98241. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  98242. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  98243. this._isRunning = false;
  98244. this.onSuccessObservable.notifyObservers(this);
  98245. return;
  98246. }
  98247. // Apply current level of optimizations
  98248. var allDone = true;
  98249. var noOptimizationApplied = true;
  98250. for (var index = 0; index < options.optimizations.length; index++) {
  98251. var optimization = options.optimizations[index];
  98252. if (optimization.priority === this._currentPriorityLevel) {
  98253. noOptimizationApplied = false;
  98254. allDone = allDone && optimization.apply(scene, this);
  98255. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  98256. }
  98257. }
  98258. // If no optimization was applied, this is a failure :(
  98259. if (noOptimizationApplied) {
  98260. this._isRunning = false;
  98261. this.onFailureObservable.notifyObservers(this);
  98262. return;
  98263. }
  98264. // If all optimizations were done, move to next level
  98265. if (allDone) {
  98266. this._currentPriorityLevel++;
  98267. }
  98268. // Let's the system running for a specific amount of time before checking FPS
  98269. scene.executeWhenReady(function () {
  98270. setTimeout(function () {
  98271. _this._checkCurrentState();
  98272. }, _this._trackerDuration);
  98273. });
  98274. };
  98275. /**
  98276. * Release all resources
  98277. */
  98278. SceneOptimizer.prototype.dispose = function () {
  98279. this.stop();
  98280. this.onSuccessObservable.clear();
  98281. this.onFailureObservable.clear();
  98282. this.onNewOptimizationAppliedObservable.clear();
  98283. if (this._sceneDisposeObserver) {
  98284. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  98285. }
  98286. };
  98287. /**
  98288. * Helper function to create a SceneOptimizer with one single line of code
  98289. * @param scene defines the scene to work on
  98290. * @param options defines the options to use with the SceneOptimizer
  98291. * @param onSuccess defines a callback to call on success
  98292. * @param onFailure defines a callback to call on failure
  98293. * @returns the new SceneOptimizer object
  98294. */
  98295. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  98296. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  98297. if (onSuccess) {
  98298. optimizer.onSuccessObservable.add(function () {
  98299. onSuccess();
  98300. });
  98301. }
  98302. if (onFailure) {
  98303. optimizer.onFailureObservable.add(function () {
  98304. onFailure();
  98305. });
  98306. }
  98307. optimizer.start();
  98308. return optimizer;
  98309. };
  98310. return SceneOptimizer;
  98311. }());
  98312. BABYLON.SceneOptimizer = SceneOptimizer;
  98313. })(BABYLON || (BABYLON = {}));
  98314. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  98315. var BABYLON;
  98316. (function (BABYLON) {
  98317. var OutlineRenderer = /** @class */ (function () {
  98318. function OutlineRenderer(scene) {
  98319. this.zOffset = 1;
  98320. this._scene = scene;
  98321. }
  98322. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  98323. var _this = this;
  98324. if (useOverlay === void 0) { useOverlay = false; }
  98325. var scene = this._scene;
  98326. var engine = this._scene.getEngine();
  98327. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  98328. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  98329. return;
  98330. }
  98331. var mesh = subMesh.getRenderingMesh();
  98332. var material = subMesh.getMaterial();
  98333. if (!material || !scene.activeCamera) {
  98334. return;
  98335. }
  98336. engine.enableEffect(this._effect);
  98337. // Logarithmic depth
  98338. if (material.useLogarithmicDepth) {
  98339. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  98340. }
  98341. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  98342. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  98343. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  98344. // Bones
  98345. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  98346. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  98347. }
  98348. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  98349. // Alpha test
  98350. if (material && material.needAlphaTesting()) {
  98351. var alphaTexture = material.getAlphaTestTexture();
  98352. if (alphaTexture) {
  98353. this._effect.setTexture("diffuseSampler", alphaTexture);
  98354. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  98355. }
  98356. }
  98357. engine.setZOffset(-this.zOffset);
  98358. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  98359. engine.setZOffset(0);
  98360. };
  98361. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  98362. var defines = [];
  98363. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  98364. var mesh = subMesh.getMesh();
  98365. var material = subMesh.getMaterial();
  98366. if (material) {
  98367. // Alpha test
  98368. if (material.needAlphaTesting()) {
  98369. defines.push("#define ALPHATEST");
  98370. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  98371. attribs.push(BABYLON.VertexBuffer.UVKind);
  98372. defines.push("#define UV1");
  98373. }
  98374. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  98375. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  98376. defines.push("#define UV2");
  98377. }
  98378. }
  98379. //Logarithmic depth
  98380. if (material.useLogarithmicDepth) {
  98381. defines.push("#define LOGARITHMICDEPTH");
  98382. }
  98383. }
  98384. // Bones
  98385. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  98386. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  98387. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  98388. if (mesh.numBoneInfluencers > 4) {
  98389. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  98390. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  98391. }
  98392. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  98393. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  98394. }
  98395. else {
  98396. defines.push("#define NUM_BONE_INFLUENCERS 0");
  98397. }
  98398. // Instances
  98399. if (useInstances) {
  98400. defines.push("#define INSTANCES");
  98401. attribs.push("world0");
  98402. attribs.push("world1");
  98403. attribs.push("world2");
  98404. attribs.push("world3");
  98405. }
  98406. // Get correct effect
  98407. var join = defines.join("\n");
  98408. if (this._cachedDefines !== join) {
  98409. this._cachedDefines = join;
  98410. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  98411. }
  98412. return this._effect.isReady();
  98413. };
  98414. return OutlineRenderer;
  98415. }());
  98416. BABYLON.OutlineRenderer = OutlineRenderer;
  98417. })(BABYLON || (BABYLON = {}));
  98418. //# sourceMappingURL=babylon.outlineRenderer.js.map
  98419. var BABYLON;
  98420. (function (BABYLON) {
  98421. var FaceAdjacencies = /** @class */ (function () {
  98422. function FaceAdjacencies() {
  98423. this.edges = new Array();
  98424. this.edgesConnectedCount = 0;
  98425. }
  98426. return FaceAdjacencies;
  98427. }());
  98428. var EdgesRenderer = /** @class */ (function () {
  98429. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  98430. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  98431. if (epsilon === void 0) { epsilon = 0.95; }
  98432. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  98433. this.edgesWidthScalerForOrthographic = 1000.0;
  98434. this.edgesWidthScalerForPerspective = 50.0;
  98435. this._linesPositions = new Array();
  98436. this._linesNormals = new Array();
  98437. this._linesIndices = new Array();
  98438. this._buffers = {};
  98439. this._checkVerticesInsteadOfIndices = false;
  98440. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  98441. this.isEnabled = true;
  98442. this._source = source;
  98443. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  98444. this._epsilon = epsilon;
  98445. this._prepareRessources();
  98446. this._generateEdgesLines();
  98447. }
  98448. EdgesRenderer.prototype._prepareRessources = function () {
  98449. if (this._lineShader) {
  98450. return;
  98451. }
  98452. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  98453. attributes: ["position", "normal"],
  98454. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  98455. });
  98456. this._lineShader.disableDepthWrite = true;
  98457. this._lineShader.backFaceCulling = false;
  98458. };
  98459. /** @hidden */
  98460. EdgesRenderer.prototype._rebuild = function () {
  98461. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  98462. if (buffer) {
  98463. buffer._rebuild();
  98464. }
  98465. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  98466. if (buffer) {
  98467. buffer._rebuild();
  98468. }
  98469. var scene = this._source.getScene();
  98470. var engine = scene.getEngine();
  98471. this._ib = engine.createIndexBuffer(this._linesIndices);
  98472. };
  98473. EdgesRenderer.prototype.dispose = function () {
  98474. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  98475. if (buffer) {
  98476. buffer.dispose();
  98477. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  98478. }
  98479. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  98480. if (buffer) {
  98481. buffer.dispose();
  98482. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  98483. }
  98484. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  98485. this._lineShader.dispose();
  98486. };
  98487. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  98488. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  98489. return 0;
  98490. }
  98491. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  98492. return 1;
  98493. }
  98494. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  98495. return 2;
  98496. }
  98497. return -1;
  98498. };
  98499. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  98500. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  98501. return 0;
  98502. }
  98503. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  98504. return 1;
  98505. }
  98506. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  98507. return 2;
  98508. }
  98509. return -1;
  98510. };
  98511. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  98512. var needToCreateLine;
  98513. if (edge === undefined) {
  98514. needToCreateLine = true;
  98515. }
  98516. else {
  98517. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  98518. needToCreateLine = dotProduct < this._epsilon;
  98519. }
  98520. if (needToCreateLine) {
  98521. var offset = this._linesPositions.length / 3;
  98522. var normal = p0.subtract(p1);
  98523. normal.normalize();
  98524. // Positions
  98525. this._linesPositions.push(p0.x);
  98526. this._linesPositions.push(p0.y);
  98527. this._linesPositions.push(p0.z);
  98528. this._linesPositions.push(p0.x);
  98529. this._linesPositions.push(p0.y);
  98530. this._linesPositions.push(p0.z);
  98531. this._linesPositions.push(p1.x);
  98532. this._linesPositions.push(p1.y);
  98533. this._linesPositions.push(p1.z);
  98534. this._linesPositions.push(p1.x);
  98535. this._linesPositions.push(p1.y);
  98536. this._linesPositions.push(p1.z);
  98537. // Normals
  98538. this._linesNormals.push(p1.x);
  98539. this._linesNormals.push(p1.y);
  98540. this._linesNormals.push(p1.z);
  98541. this._linesNormals.push(-1);
  98542. this._linesNormals.push(p1.x);
  98543. this._linesNormals.push(p1.y);
  98544. this._linesNormals.push(p1.z);
  98545. this._linesNormals.push(1);
  98546. this._linesNormals.push(p0.x);
  98547. this._linesNormals.push(p0.y);
  98548. this._linesNormals.push(p0.z);
  98549. this._linesNormals.push(-1);
  98550. this._linesNormals.push(p0.x);
  98551. this._linesNormals.push(p0.y);
  98552. this._linesNormals.push(p0.z);
  98553. this._linesNormals.push(1);
  98554. // Indices
  98555. this._linesIndices.push(offset);
  98556. this._linesIndices.push(offset + 1);
  98557. this._linesIndices.push(offset + 2);
  98558. this._linesIndices.push(offset);
  98559. this._linesIndices.push(offset + 2);
  98560. this._linesIndices.push(offset + 3);
  98561. }
  98562. };
  98563. EdgesRenderer.prototype._generateEdgesLines = function () {
  98564. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  98565. var indices = this._source.getIndices();
  98566. if (!indices || !positions) {
  98567. return;
  98568. }
  98569. // First let's find adjacencies
  98570. var adjacencies = new Array();
  98571. var faceNormals = new Array();
  98572. var index;
  98573. var faceAdjacencies;
  98574. // Prepare faces
  98575. for (index = 0; index < indices.length; index += 3) {
  98576. faceAdjacencies = new FaceAdjacencies();
  98577. var p0Index = indices[index];
  98578. var p1Index = indices[index + 1];
  98579. var p2Index = indices[index + 2];
  98580. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  98581. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  98582. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  98583. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  98584. faceNormal.normalize();
  98585. faceNormals.push(faceNormal);
  98586. adjacencies.push(faceAdjacencies);
  98587. }
  98588. // Scan
  98589. for (index = 0; index < adjacencies.length; index++) {
  98590. faceAdjacencies = adjacencies[index];
  98591. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  98592. var otherFaceAdjacencies = adjacencies[otherIndex];
  98593. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  98594. break;
  98595. }
  98596. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  98597. continue;
  98598. }
  98599. var otherP0 = indices[otherIndex * 3];
  98600. var otherP1 = indices[otherIndex * 3 + 1];
  98601. var otherP2 = indices[otherIndex * 3 + 2];
  98602. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  98603. var otherEdgeIndex = 0;
  98604. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  98605. continue;
  98606. }
  98607. switch (edgeIndex) {
  98608. case 0:
  98609. if (this._checkVerticesInsteadOfIndices) {
  98610. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  98611. }
  98612. else {
  98613. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  98614. }
  98615. break;
  98616. case 1:
  98617. if (this._checkVerticesInsteadOfIndices) {
  98618. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  98619. }
  98620. else {
  98621. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  98622. }
  98623. break;
  98624. case 2:
  98625. if (this._checkVerticesInsteadOfIndices) {
  98626. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  98627. }
  98628. else {
  98629. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  98630. }
  98631. break;
  98632. }
  98633. if (otherEdgeIndex === -1) {
  98634. continue;
  98635. }
  98636. faceAdjacencies.edges[edgeIndex] = otherIndex;
  98637. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  98638. faceAdjacencies.edgesConnectedCount++;
  98639. otherFaceAdjacencies.edgesConnectedCount++;
  98640. if (faceAdjacencies.edgesConnectedCount === 3) {
  98641. break;
  98642. }
  98643. }
  98644. }
  98645. }
  98646. // Create lines
  98647. for (index = 0; index < adjacencies.length; index++) {
  98648. // 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
  98649. var current = adjacencies[index];
  98650. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  98651. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  98652. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  98653. }
  98654. // Merge into a single mesh
  98655. var engine = this._source.getScene().getEngine();
  98656. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  98657. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  98658. this._ib = engine.createIndexBuffer(this._linesIndices);
  98659. this._indicesCount = this._linesIndices.length;
  98660. };
  98661. EdgesRenderer.prototype.render = function () {
  98662. var scene = this._source.getScene();
  98663. if (!this._lineShader.isReady() || !scene.activeCamera) {
  98664. return;
  98665. }
  98666. var engine = scene.getEngine();
  98667. this._lineShader._preBind();
  98668. if (this._source.edgesColor.a !== 1) {
  98669. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  98670. }
  98671. else {
  98672. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  98673. }
  98674. // VBOs
  98675. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  98676. scene.resetCachedMaterial();
  98677. this._lineShader.setColor4("color", this._source.edgesColor);
  98678. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  98679. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  98680. }
  98681. else {
  98682. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  98683. }
  98684. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  98685. this._lineShader.bind(this._source.getWorldMatrix());
  98686. // Draw order
  98687. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  98688. this._lineShader.unbind();
  98689. };
  98690. return EdgesRenderer;
  98691. }());
  98692. BABYLON.EdgesRenderer = EdgesRenderer;
  98693. })(BABYLON || (BABYLON = {}));
  98694. //# sourceMappingURL=babylon.edgesRenderer.js.map
  98695. var BABYLON;
  98696. (function (BABYLON) {
  98697. // Adds the parser to the scene parsers.
  98698. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  98699. if (parsedData.effectLayers) {
  98700. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  98701. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  98702. container.effectLayers.push(effectLayer);
  98703. }
  98704. }
  98705. });
  98706. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  98707. var index = this.effectLayers.indexOf(toRemove);
  98708. if (index !== -1) {
  98709. this.effectLayers.splice(index, 1);
  98710. }
  98711. return index;
  98712. };
  98713. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  98714. this.effectLayers.push(newEffectLayer);
  98715. };
  98716. /**
  98717. * Defines the layer scene component responsible to manage any effect layers
  98718. * in a given scene.
  98719. */
  98720. var EffectLayerSceneComponent = /** @class */ (function () {
  98721. /**
  98722. * Creates a new instance of the component for the given scene
  98723. * @param scene Defines the scene to register the component in
  98724. */
  98725. function EffectLayerSceneComponent(scene) {
  98726. /**
  98727. * The component name helpfull to identify the component in the list of scene components.
  98728. */
  98729. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  98730. this._renderEffects = false;
  98731. this._needStencil = false;
  98732. this._previousStencilState = false;
  98733. this.scene = scene;
  98734. this._engine = scene.getEngine();
  98735. scene.effectLayers = new Array();
  98736. }
  98737. /**
  98738. * Registers the component in a given scene
  98739. */
  98740. EffectLayerSceneComponent.prototype.register = function () {
  98741. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  98742. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  98743. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  98744. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  98745. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  98746. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  98747. };
  98748. /**
  98749. * Rebuilds the elements related to this component in case of
  98750. * context lost for instance.
  98751. */
  98752. EffectLayerSceneComponent.prototype.rebuild = function () {
  98753. var layers = this.scene.effectLayers;
  98754. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  98755. var effectLayer = layers_1[_i];
  98756. effectLayer._rebuild();
  98757. }
  98758. };
  98759. /**
  98760. * Serializes the component data to the specified json object
  98761. * @param serializationObject The object to serialize to
  98762. */
  98763. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  98764. // Effect layers
  98765. serializationObject.effectLayers = [];
  98766. var layers = this.scene.effectLayers;
  98767. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  98768. var effectLayer = layers_2[_i];
  98769. if (effectLayer.serialize) {
  98770. serializationObject.effectLayers.push(effectLayer.serialize());
  98771. }
  98772. }
  98773. };
  98774. /**
  98775. * Adds all the element from the container to the scene
  98776. * @param container the container holding the elements
  98777. */
  98778. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  98779. var _this = this;
  98780. if (!container.effectLayers) {
  98781. return;
  98782. }
  98783. container.effectLayers.forEach(function (o) {
  98784. _this.scene.addEffectLayer(o);
  98785. });
  98786. };
  98787. /**
  98788. * Removes all the elements in the container from the scene
  98789. * @param container contains the elements to remove
  98790. */
  98791. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  98792. var _this = this;
  98793. if (!container.effectLayers) {
  98794. return;
  98795. }
  98796. container.effectLayers.forEach(function (o) {
  98797. _this.scene.removeEffectLayer(o);
  98798. });
  98799. };
  98800. /**
  98801. * Disposes the component and the associated ressources.
  98802. */
  98803. EffectLayerSceneComponent.prototype.dispose = function () {
  98804. var layers = this.scene.effectLayers;
  98805. while (layers.length) {
  98806. layers[0].dispose();
  98807. }
  98808. };
  98809. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  98810. var layers = this.scene.effectLayers;
  98811. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  98812. var layer = layers_3[_i];
  98813. if (!layer.hasMesh(mesh)) {
  98814. continue;
  98815. }
  98816. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  98817. var subMesh = _b[_a];
  98818. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  98819. return false;
  98820. }
  98821. }
  98822. }
  98823. return true;
  98824. };
  98825. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  98826. this._renderEffects = false;
  98827. this._needStencil = false;
  98828. var layers = this.scene.effectLayers;
  98829. if (layers && layers.length > 0) {
  98830. this._previousStencilState = this._engine.getStencilBuffer();
  98831. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  98832. var effectLayer = layers_4[_i];
  98833. if (effectLayer.shouldRender() &&
  98834. (!effectLayer.camera ||
  98835. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  98836. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  98837. this._renderEffects = true;
  98838. this._needStencil = this._needStencil || effectLayer.needStencil();
  98839. var renderTarget = effectLayer._mainTexture;
  98840. if (renderTarget._shouldRender()) {
  98841. this.scene.incrementRenderId();
  98842. renderTarget.render(false, false);
  98843. }
  98844. }
  98845. }
  98846. this.scene.incrementRenderId();
  98847. }
  98848. };
  98849. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  98850. // Activate effect Layer stencil
  98851. if (this._needStencil) {
  98852. this._engine.setStencilBuffer(true);
  98853. }
  98854. };
  98855. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  98856. // Restore effect Layer stencil
  98857. if (this._needStencil) {
  98858. this._engine.setStencilBuffer(this._previousStencilState);
  98859. }
  98860. };
  98861. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  98862. if (this._renderEffects) {
  98863. this._engine.setDepthBuffer(false);
  98864. var layers = this.scene.effectLayers;
  98865. for (var i = 0; i < layers.length; i++) {
  98866. var effectLayer = layers[i];
  98867. if (effectLayer.renderingGroupId === renderingGroupId) {
  98868. if (effectLayer.shouldRender()) {
  98869. effectLayer.render();
  98870. }
  98871. }
  98872. }
  98873. this._engine.setDepthBuffer(true);
  98874. }
  98875. };
  98876. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  98877. if (this._renderEffects) {
  98878. this._draw(-1);
  98879. }
  98880. };
  98881. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  98882. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  98883. this._draw(index);
  98884. }
  98885. };
  98886. return EffectLayerSceneComponent;
  98887. }());
  98888. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  98889. })(BABYLON || (BABYLON = {}));
  98890. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  98891. var __assign = (this && this.__assign) || function () {
  98892. __assign = Object.assign || function(t) {
  98893. for (var s, i = 1, n = arguments.length; i < n; i++) {
  98894. s = arguments[i];
  98895. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  98896. t[p] = s[p];
  98897. }
  98898. return t;
  98899. };
  98900. return __assign.apply(this, arguments);
  98901. };
  98902. var BABYLON;
  98903. (function (BABYLON) {
  98904. /**
  98905. * The effect layer Helps adding post process effect blended with the main pass.
  98906. *
  98907. * This can be for instance use to generate glow or higlight effects on the scene.
  98908. *
  98909. * The effect layer class can not be used directly and is intented to inherited from to be
  98910. * customized per effects.
  98911. */
  98912. var EffectLayer = /** @class */ (function () {
  98913. /**
  98914. * Instantiates a new effect Layer and references it in the scene.
  98915. * @param name The name of the layer
  98916. * @param scene The scene to use the layer in
  98917. */
  98918. function EffectLayer(
  98919. /** The Friendly of the effect in the scene */
  98920. name, scene) {
  98921. this._vertexBuffers = {};
  98922. this._maxSize = 0;
  98923. this._mainTextureDesiredSize = { width: 0, height: 0 };
  98924. this._shouldRender = true;
  98925. this._postProcesses = [];
  98926. this._textures = [];
  98927. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  98928. /**
  98929. * The clear color of the texture used to generate the glow map.
  98930. */
  98931. this.neutralColor = new BABYLON.Color4();
  98932. /**
  98933. * Specifies wether the highlight layer is enabled or not.
  98934. */
  98935. this.isEnabled = true;
  98936. /**
  98937. * An event triggered when the effect layer has been disposed.
  98938. */
  98939. this.onDisposeObservable = new BABYLON.Observable();
  98940. /**
  98941. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  98942. */
  98943. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  98944. /**
  98945. * An event triggered when the generated texture is being merged in the scene.
  98946. */
  98947. this.onBeforeComposeObservable = new BABYLON.Observable();
  98948. /**
  98949. * An event triggered when the generated texture has been merged in the scene.
  98950. */
  98951. this.onAfterComposeObservable = new BABYLON.Observable();
  98952. /**
  98953. * An event triggered when the efffect layer changes its size.
  98954. */
  98955. this.onSizeChangedObservable = new BABYLON.Observable();
  98956. this.name = name;
  98957. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  98958. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  98959. if (!component) {
  98960. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  98961. this._scene._addComponent(component);
  98962. }
  98963. this._engine = this._scene.getEngine();
  98964. this._maxSize = this._engine.getCaps().maxTextureSize;
  98965. this._scene.effectLayers.push(this);
  98966. // Generate Buffers
  98967. this._generateIndexBuffer();
  98968. this._genrateVertexBuffer();
  98969. }
  98970. Object.defineProperty(EffectLayer.prototype, "camera", {
  98971. /**
  98972. * Gets the camera attached to the layer.
  98973. */
  98974. get: function () {
  98975. return this._effectLayerOptions.camera;
  98976. },
  98977. enumerable: true,
  98978. configurable: true
  98979. });
  98980. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  98981. /**
  98982. * Gets the rendering group id the layer should render in.
  98983. */
  98984. get: function () {
  98985. return this._effectLayerOptions.renderingGroupId;
  98986. },
  98987. enumerable: true,
  98988. configurable: true
  98989. });
  98990. /**
  98991. * Initializes the effect layer with the required options.
  98992. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  98993. */
  98994. EffectLayer.prototype._init = function (options) {
  98995. // Adapt options
  98996. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  98997. this._setMainTextureSize();
  98998. this._createMainTexture();
  98999. this._createTextureAndPostProcesses();
  99000. this._mergeEffect = this._createMergeEffect();
  99001. };
  99002. /**
  99003. * Generates the index buffer of the full screen quad blending to the main canvas.
  99004. */
  99005. EffectLayer.prototype._generateIndexBuffer = function () {
  99006. // Indices
  99007. var indices = [];
  99008. indices.push(0);
  99009. indices.push(1);
  99010. indices.push(2);
  99011. indices.push(0);
  99012. indices.push(2);
  99013. indices.push(3);
  99014. this._indexBuffer = this._engine.createIndexBuffer(indices);
  99015. };
  99016. /**
  99017. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  99018. */
  99019. EffectLayer.prototype._genrateVertexBuffer = function () {
  99020. // VBO
  99021. var vertices = [];
  99022. vertices.push(1, 1);
  99023. vertices.push(-1, 1);
  99024. vertices.push(-1, -1);
  99025. vertices.push(1, -1);
  99026. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  99027. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  99028. };
  99029. /**
  99030. * Sets the main texture desired size which is the closest power of two
  99031. * of the engine canvas size.
  99032. */
  99033. EffectLayer.prototype._setMainTextureSize = function () {
  99034. if (this._effectLayerOptions.mainTextureFixedSize) {
  99035. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  99036. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  99037. }
  99038. else {
  99039. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  99040. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  99041. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  99042. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  99043. }
  99044. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  99045. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  99046. };
  99047. /**
  99048. * Creates the main texture for the effect layer.
  99049. */
  99050. EffectLayer.prototype._createMainTexture = function () {
  99051. var _this = this;
  99052. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  99053. width: this._mainTextureDesiredSize.width,
  99054. height: this._mainTextureDesiredSize.height
  99055. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  99056. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  99057. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99058. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99059. this._mainTexture.anisotropicFilteringLevel = 1;
  99060. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  99061. this._mainTexture.renderParticles = false;
  99062. this._mainTexture.renderList = null;
  99063. this._mainTexture.ignoreCameraViewport = true;
  99064. // Custom render function
  99065. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  99066. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  99067. var index;
  99068. var engine = _this._scene.getEngine();
  99069. if (depthOnlySubMeshes.length) {
  99070. engine.setColorWrite(false);
  99071. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  99072. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  99073. }
  99074. engine.setColorWrite(true);
  99075. }
  99076. for (index = 0; index < opaqueSubMeshes.length; index++) {
  99077. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  99078. }
  99079. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  99080. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  99081. }
  99082. for (index = 0; index < transparentSubMeshes.length; index++) {
  99083. _this._renderSubMesh(transparentSubMeshes.data[index]);
  99084. }
  99085. };
  99086. this._mainTexture.onClearObservable.add(function (engine) {
  99087. engine.clear(_this.neutralColor, true, true, true);
  99088. });
  99089. };
  99090. /**
  99091. * Checks for the readiness of the element composing the layer.
  99092. * @param subMesh the mesh to check for
  99093. * @param useInstances specify wether or not to use instances to render the mesh
  99094. * @param emissiveTexture the associated emissive texture used to generate the glow
  99095. * @return true if ready otherwise, false
  99096. */
  99097. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  99098. var material = subMesh.getMaterial();
  99099. if (!material) {
  99100. return false;
  99101. }
  99102. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  99103. return false;
  99104. }
  99105. var defines = [];
  99106. var attribs = [BABYLON.VertexBuffer.PositionKind];
  99107. var mesh = subMesh.getMesh();
  99108. var uv1 = false;
  99109. var uv2 = false;
  99110. // Alpha test
  99111. if (material && material.needAlphaTesting()) {
  99112. var alphaTexture = material.getAlphaTestTexture();
  99113. if (alphaTexture) {
  99114. defines.push("#define ALPHATEST");
  99115. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  99116. alphaTexture.coordinatesIndex === 1) {
  99117. defines.push("#define DIFFUSEUV2");
  99118. uv2 = true;
  99119. }
  99120. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  99121. defines.push("#define DIFFUSEUV1");
  99122. uv1 = true;
  99123. }
  99124. }
  99125. }
  99126. // Emissive
  99127. if (emissiveTexture) {
  99128. defines.push("#define EMISSIVE");
  99129. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  99130. emissiveTexture.coordinatesIndex === 1) {
  99131. defines.push("#define EMISSIVEUV2");
  99132. uv2 = true;
  99133. }
  99134. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  99135. defines.push("#define EMISSIVEUV1");
  99136. uv1 = true;
  99137. }
  99138. }
  99139. if (uv1) {
  99140. attribs.push(BABYLON.VertexBuffer.UVKind);
  99141. defines.push("#define UV1");
  99142. }
  99143. if (uv2) {
  99144. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  99145. defines.push("#define UV2");
  99146. }
  99147. // Bones
  99148. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  99149. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  99150. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  99151. if (mesh.numBoneInfluencers > 4) {
  99152. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  99153. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  99154. }
  99155. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  99156. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  99157. }
  99158. else {
  99159. defines.push("#define NUM_BONE_INFLUENCERS 0");
  99160. }
  99161. // Morph targets
  99162. var manager = mesh.morphTargetManager;
  99163. var morphInfluencers = 0;
  99164. if (manager) {
  99165. if (manager.numInfluencers > 0) {
  99166. defines.push("#define MORPHTARGETS");
  99167. morphInfluencers = manager.numInfluencers;
  99168. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  99169. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  99170. }
  99171. }
  99172. // Instances
  99173. if (useInstances) {
  99174. defines.push("#define INSTANCES");
  99175. attribs.push("world0");
  99176. attribs.push("world1");
  99177. attribs.push("world2");
  99178. attribs.push("world3");
  99179. }
  99180. // Get correct effect
  99181. var join = defines.join("\n");
  99182. if (this._cachedDefines !== join) {
  99183. this._cachedDefines = join;
  99184. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  99185. }
  99186. return this._effectLayerMapGenerationEffect.isReady();
  99187. };
  99188. /**
  99189. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  99190. */
  99191. EffectLayer.prototype.render = function () {
  99192. var currentEffect = this._mergeEffect;
  99193. // Check
  99194. if (!currentEffect.isReady())
  99195. return;
  99196. for (var i = 0; i < this._postProcesses.length; i++) {
  99197. if (!this._postProcesses[i].isReady()) {
  99198. return;
  99199. }
  99200. }
  99201. var engine = this._scene.getEngine();
  99202. this.onBeforeComposeObservable.notifyObservers(this);
  99203. // Render
  99204. engine.enableEffect(currentEffect);
  99205. engine.setState(false);
  99206. // VBOs
  99207. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  99208. // Cache
  99209. var previousAlphaMode = engine.getAlphaMode();
  99210. // Go Blend.
  99211. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  99212. // Blends the map on the main canvas.
  99213. this._internalRender(currentEffect);
  99214. // Restore Alpha
  99215. engine.setAlphaMode(previousAlphaMode);
  99216. this.onAfterComposeObservable.notifyObservers(this);
  99217. // Handle size changes.
  99218. var size = this._mainTexture.getSize();
  99219. this._setMainTextureSize();
  99220. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  99221. // Recreate RTT and post processes on size change.
  99222. this.onSizeChangedObservable.notifyObservers(this);
  99223. this._disposeTextureAndPostProcesses();
  99224. this._createMainTexture();
  99225. this._createTextureAndPostProcesses();
  99226. }
  99227. };
  99228. /**
  99229. * Determine if a given mesh will be used in the current effect.
  99230. * @param mesh mesh to test
  99231. * @returns true if the mesh will be used
  99232. */
  99233. EffectLayer.prototype.hasMesh = function (mesh) {
  99234. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  99235. return true;
  99236. }
  99237. return false;
  99238. };
  99239. /**
  99240. * Returns true if the layer contains information to display, otherwise false.
  99241. * @returns true if the glow layer should be rendered
  99242. */
  99243. EffectLayer.prototype.shouldRender = function () {
  99244. return this.isEnabled && this._shouldRender;
  99245. };
  99246. /**
  99247. * Returns true if the mesh should render, otherwise false.
  99248. * @param mesh The mesh to render
  99249. * @returns true if it should render otherwise false
  99250. */
  99251. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  99252. return true;
  99253. };
  99254. /**
  99255. * Returns true if the mesh should render, otherwise false.
  99256. * @param mesh The mesh to render
  99257. * @returns true if it should render otherwise false
  99258. */
  99259. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  99260. return true;
  99261. };
  99262. /**
  99263. * Renders the submesh passed in parameter to the generation map.
  99264. */
  99265. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  99266. var _this = this;
  99267. if (!this.shouldRender()) {
  99268. return;
  99269. }
  99270. var material = subMesh.getMaterial();
  99271. var mesh = subMesh.getRenderingMesh();
  99272. var scene = this._scene;
  99273. var engine = scene.getEngine();
  99274. if (!material) {
  99275. return;
  99276. }
  99277. // Do not block in blend mode.
  99278. if (material.needAlphaBlendingForMesh(mesh)) {
  99279. return;
  99280. }
  99281. // Culling
  99282. engine.setState(material.backFaceCulling);
  99283. // Managing instances
  99284. var batch = mesh._getInstancesRenderList(subMesh._id);
  99285. if (batch.mustReturn) {
  99286. return;
  99287. }
  99288. // Early Exit per mesh
  99289. if (!this._shouldRenderMesh(mesh)) {
  99290. return;
  99291. }
  99292. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  99293. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  99294. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  99295. engine.enableEffect(this._effectLayerMapGenerationEffect);
  99296. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  99297. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  99298. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  99299. // Alpha test
  99300. if (material && material.needAlphaTesting()) {
  99301. var alphaTexture = material.getAlphaTestTexture();
  99302. if (alphaTexture) {
  99303. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  99304. var textureMatrix = alphaTexture.getTextureMatrix();
  99305. if (textureMatrix) {
  99306. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  99307. }
  99308. }
  99309. }
  99310. // Glow emissive only
  99311. if (this._emissiveTextureAndColor.texture) {
  99312. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  99313. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  99314. }
  99315. // Bones
  99316. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  99317. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  99318. }
  99319. // Morph targets
  99320. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  99321. // Draw
  99322. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  99323. }
  99324. else {
  99325. // Need to reset refresh rate of the main map
  99326. this._mainTexture.resetRefreshCounter();
  99327. }
  99328. };
  99329. /**
  99330. * Rebuild the required buffers.
  99331. * @hidden Internal use only.
  99332. */
  99333. EffectLayer.prototype._rebuild = function () {
  99334. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  99335. if (vb) {
  99336. vb._rebuild();
  99337. }
  99338. this._generateIndexBuffer();
  99339. };
  99340. /**
  99341. * Dispose only the render target textures and post process.
  99342. */
  99343. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  99344. this._mainTexture.dispose();
  99345. for (var i = 0; i < this._postProcesses.length; i++) {
  99346. if (this._postProcesses[i]) {
  99347. this._postProcesses[i].dispose();
  99348. }
  99349. }
  99350. this._postProcesses = [];
  99351. for (var i = 0; i < this._textures.length; i++) {
  99352. if (this._textures[i]) {
  99353. this._textures[i].dispose();
  99354. }
  99355. }
  99356. this._textures = [];
  99357. };
  99358. /**
  99359. * Dispose the highlight layer and free resources.
  99360. */
  99361. EffectLayer.prototype.dispose = function () {
  99362. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  99363. if (vertexBuffer) {
  99364. vertexBuffer.dispose();
  99365. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  99366. }
  99367. if (this._indexBuffer) {
  99368. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  99369. this._indexBuffer = null;
  99370. }
  99371. // Clean textures and post processes
  99372. this._disposeTextureAndPostProcesses();
  99373. // Remove from scene
  99374. var index = this._scene.effectLayers.indexOf(this, 0);
  99375. if (index > -1) {
  99376. this._scene.effectLayers.splice(index, 1);
  99377. }
  99378. // Callback
  99379. this.onDisposeObservable.notifyObservers(this);
  99380. this.onDisposeObservable.clear();
  99381. this.onBeforeRenderMainTextureObservable.clear();
  99382. this.onBeforeComposeObservable.clear();
  99383. this.onAfterComposeObservable.clear();
  99384. this.onSizeChangedObservable.clear();
  99385. };
  99386. /**
  99387. * Gets the class name of the effect layer
  99388. * @returns the string with the class name of the effect layer
  99389. */
  99390. EffectLayer.prototype.getClassName = function () {
  99391. return "EffectLayer";
  99392. };
  99393. /**
  99394. * Creates an effect layer from parsed effect layer data
  99395. * @param parsedEffectLayer defines effect layer data
  99396. * @param scene defines the current scene
  99397. * @param rootUrl defines the root URL containing the effect layer information
  99398. * @returns a parsed effect Layer
  99399. */
  99400. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  99401. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  99402. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  99403. };
  99404. __decorate([
  99405. BABYLON.serialize()
  99406. ], EffectLayer.prototype, "name", void 0);
  99407. __decorate([
  99408. BABYLON.serializeAsColor4()
  99409. ], EffectLayer.prototype, "neutralColor", void 0);
  99410. __decorate([
  99411. BABYLON.serialize()
  99412. ], EffectLayer.prototype, "isEnabled", void 0);
  99413. __decorate([
  99414. BABYLON.serializeAsCameraReference()
  99415. ], EffectLayer.prototype, "camera", null);
  99416. __decorate([
  99417. BABYLON.serialize()
  99418. ], EffectLayer.prototype, "renderingGroupId", null);
  99419. return EffectLayer;
  99420. }());
  99421. BABYLON.EffectLayer = EffectLayer;
  99422. })(BABYLON || (BABYLON = {}));
  99423. //# sourceMappingURL=babylon.effectLayer.js.map
  99424. var BABYLON;
  99425. (function (BABYLON) {
  99426. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  99427. for (var index = 0; index < this.effectLayers.length; index++) {
  99428. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  99429. return this.effectLayers[index];
  99430. }
  99431. }
  99432. return null;
  99433. };
  99434. /**
  99435. * Special Glow Blur post process only blurring the alpha channel
  99436. * It enforces keeping the most luminous color in the color channel.
  99437. */
  99438. var GlowBlurPostProcess = /** @class */ (function (_super) {
  99439. __extends(GlowBlurPostProcess, _super);
  99440. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  99441. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  99442. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  99443. _this.direction = direction;
  99444. _this.kernel = kernel;
  99445. _this.onApplyObservable.add(function (effect) {
  99446. effect.setFloat2("screenSize", _this.width, _this.height);
  99447. effect.setVector2("direction", _this.direction);
  99448. effect.setFloat("blurWidth", _this.kernel);
  99449. });
  99450. return _this;
  99451. }
  99452. return GlowBlurPostProcess;
  99453. }(BABYLON.PostProcess));
  99454. /**
  99455. * The highlight layer Helps adding a glow effect around a mesh.
  99456. *
  99457. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  99458. * glowy meshes to your scene.
  99459. *
  99460. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  99461. */
  99462. var HighlightLayer = /** @class */ (function (_super) {
  99463. __extends(HighlightLayer, _super);
  99464. /**
  99465. * Instantiates a new highlight Layer and references it to the scene..
  99466. * @param name The name of the layer
  99467. * @param scene The scene to use the layer in
  99468. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  99469. */
  99470. function HighlightLayer(name, scene, options) {
  99471. var _this = _super.call(this, name, scene) || this;
  99472. _this.name = name;
  99473. /**
  99474. * Specifies whether or not the inner glow is ACTIVE in the layer.
  99475. */
  99476. _this.innerGlow = true;
  99477. /**
  99478. * Specifies whether or not the outer glow is ACTIVE in the layer.
  99479. */
  99480. _this.outerGlow = true;
  99481. /**
  99482. * An event triggered when the highlight layer is being blurred.
  99483. */
  99484. _this.onBeforeBlurObservable = new BABYLON.Observable();
  99485. /**
  99486. * An event triggered when the highlight layer has been blurred.
  99487. */
  99488. _this.onAfterBlurObservable = new BABYLON.Observable();
  99489. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  99490. _this._meshes = {};
  99491. _this._excludedMeshes = {};
  99492. _this.neutralColor = HighlightLayer.NeutralColor;
  99493. // Warn on stencil
  99494. if (!_this._engine.isStencilEnable) {
  99495. 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 }");
  99496. }
  99497. // Adapt options
  99498. _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);
  99499. // Initialize the layer
  99500. _this._init({
  99501. alphaBlendingMode: _this._options.alphaBlendingMode,
  99502. camera: _this._options.camera,
  99503. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  99504. mainTextureRatio: _this._options.mainTextureRatio,
  99505. renderingGroupId: _this._options.renderingGroupId
  99506. });
  99507. // Do not render as long as no meshes have been added
  99508. _this._shouldRender = false;
  99509. return _this;
  99510. }
  99511. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  99512. /**
  99513. * Gets the horizontal size of the blur.
  99514. */
  99515. get: function () {
  99516. return this._horizontalBlurPostprocess.kernel;
  99517. },
  99518. /**
  99519. * Specifies the horizontal size of the blur.
  99520. */
  99521. set: function (value) {
  99522. this._horizontalBlurPostprocess.kernel = value;
  99523. },
  99524. enumerable: true,
  99525. configurable: true
  99526. });
  99527. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  99528. /**
  99529. * Gets the vertical size of the blur.
  99530. */
  99531. get: function () {
  99532. return this._verticalBlurPostprocess.kernel;
  99533. },
  99534. /**
  99535. * Specifies the vertical size of the blur.
  99536. */
  99537. set: function (value) {
  99538. this._verticalBlurPostprocess.kernel = value;
  99539. },
  99540. enumerable: true,
  99541. configurable: true
  99542. });
  99543. /**
  99544. * Get the effect name of the layer.
  99545. * @return The effect name
  99546. */
  99547. HighlightLayer.prototype.getEffectName = function () {
  99548. return HighlightLayer.EffectName;
  99549. };
  99550. /**
  99551. * Create the merge effect. This is the shader use to blit the information back
  99552. * to the main canvas at the end of the scene rendering.
  99553. */
  99554. HighlightLayer.prototype._createMergeEffect = function () {
  99555. // Effect
  99556. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  99557. };
  99558. /**
  99559. * Creates the render target textures and post processes used in the highlight layer.
  99560. */
  99561. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  99562. var _this = this;
  99563. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  99564. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  99565. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  99566. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  99567. var textureType = 0;
  99568. if (this._engine.getCaps().textureHalfFloatRender) {
  99569. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  99570. }
  99571. else {
  99572. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  99573. }
  99574. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  99575. width: blurTextureWidth,
  99576. height: blurTextureHeight
  99577. }, this._scene, false, true, textureType);
  99578. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99579. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99580. this._blurTexture.anisotropicFilteringLevel = 16;
  99581. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  99582. this._blurTexture.renderParticles = false;
  99583. this._blurTexture.ignoreCameraViewport = true;
  99584. this._textures = [this._blurTexture];
  99585. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  99586. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  99587. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  99588. effect.setTexture("textureSampler", _this._mainTexture);
  99589. });
  99590. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  99591. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  99592. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  99593. });
  99594. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  99595. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  99596. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  99597. });
  99598. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  99599. }
  99600. else {
  99601. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  99602. width: blurTextureWidth,
  99603. height: blurTextureHeight
  99604. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  99605. this._horizontalBlurPostprocess.width = blurTextureWidth;
  99606. this._horizontalBlurPostprocess.height = blurTextureHeight;
  99607. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  99608. effect.setTexture("textureSampler", _this._mainTexture);
  99609. });
  99610. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  99611. width: blurTextureWidth,
  99612. height: blurTextureHeight
  99613. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  99614. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  99615. }
  99616. this._mainTexture.onAfterUnbindObservable.add(function () {
  99617. _this.onBeforeBlurObservable.notifyObservers(_this);
  99618. var internalTexture = _this._blurTexture.getInternalTexture();
  99619. if (internalTexture) {
  99620. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  99621. }
  99622. _this.onAfterBlurObservable.notifyObservers(_this);
  99623. });
  99624. // Prevent autoClear.
  99625. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  99626. };
  99627. /**
  99628. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  99629. */
  99630. HighlightLayer.prototype.needStencil = function () {
  99631. return true;
  99632. };
  99633. /**
  99634. * Checks for the readiness of the element composing the layer.
  99635. * @param subMesh the mesh to check for
  99636. * @param useInstances specify wether or not to use instances to render the mesh
  99637. * @param emissiveTexture the associated emissive texture used to generate the glow
  99638. * @return true if ready otherwise, false
  99639. */
  99640. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  99641. var material = subMesh.getMaterial();
  99642. var mesh = subMesh.getRenderingMesh();
  99643. if (!material || !mesh || !this._meshes) {
  99644. return false;
  99645. }
  99646. var emissiveTexture = null;
  99647. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  99648. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  99649. emissiveTexture = material.emissiveTexture;
  99650. }
  99651. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  99652. };
  99653. /**
  99654. * Implementation specific of rendering the generating effect on the main canvas.
  99655. * @param effect The effect used to render through
  99656. */
  99657. HighlightLayer.prototype._internalRender = function (effect) {
  99658. // Texture
  99659. effect.setTexture("textureSampler", this._blurTexture);
  99660. // Cache
  99661. var engine = this._engine;
  99662. var previousStencilBuffer = engine.getStencilBuffer();
  99663. var previousStencilFunction = engine.getStencilFunction();
  99664. var previousStencilMask = engine.getStencilMask();
  99665. var previousStencilOperationPass = engine.getStencilOperationPass();
  99666. var previousStencilOperationFail = engine.getStencilOperationFail();
  99667. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  99668. var previousStencilReference = engine.getStencilFunctionReference();
  99669. // Stencil operations
  99670. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  99671. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  99672. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  99673. // Draw order
  99674. engine.setStencilMask(0x00);
  99675. engine.setStencilBuffer(true);
  99676. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  99677. // 2 passes inner outer
  99678. if (this.outerGlow) {
  99679. effect.setFloat("offset", 0);
  99680. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  99681. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  99682. }
  99683. if (this.innerGlow) {
  99684. effect.setFloat("offset", 1);
  99685. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  99686. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  99687. }
  99688. // Restore Cache
  99689. engine.setStencilFunction(previousStencilFunction);
  99690. engine.setStencilMask(previousStencilMask);
  99691. engine.setStencilBuffer(previousStencilBuffer);
  99692. engine.setStencilOperationPass(previousStencilOperationPass);
  99693. engine.setStencilOperationFail(previousStencilOperationFail);
  99694. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  99695. engine.setStencilFunctionReference(previousStencilReference);
  99696. };
  99697. /**
  99698. * Returns true if the layer contains information to display, otherwise false.
  99699. */
  99700. HighlightLayer.prototype.shouldRender = function () {
  99701. if (_super.prototype.shouldRender.call(this)) {
  99702. return this._meshes ? true : false;
  99703. }
  99704. return false;
  99705. };
  99706. /**
  99707. * Returns true if the mesh should render, otherwise false.
  99708. * @param mesh The mesh to render
  99709. * @returns true if it should render otherwise false
  99710. */
  99711. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  99712. // Excluded Mesh
  99713. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  99714. return false;
  99715. }
  99716. ;
  99717. if (!_super.prototype.hasMesh.call(this, mesh)) {
  99718. return false;
  99719. }
  99720. return true;
  99721. };
  99722. /**
  99723. * Sets the required values for both the emissive texture and and the main color.
  99724. */
  99725. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  99726. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  99727. if (highlightLayerMesh) {
  99728. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  99729. }
  99730. else {
  99731. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  99732. }
  99733. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  99734. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  99735. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  99736. }
  99737. else {
  99738. this._emissiveTextureAndColor.texture = null;
  99739. }
  99740. };
  99741. /**
  99742. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  99743. * @param mesh The mesh to exclude from the highlight layer
  99744. */
  99745. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  99746. if (!this._excludedMeshes) {
  99747. return;
  99748. }
  99749. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  99750. if (!meshExcluded) {
  99751. this._excludedMeshes[mesh.uniqueId] = {
  99752. mesh: mesh,
  99753. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  99754. mesh.getEngine().setStencilBuffer(false);
  99755. }),
  99756. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  99757. mesh.getEngine().setStencilBuffer(true);
  99758. }),
  99759. };
  99760. }
  99761. };
  99762. /**
  99763. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  99764. * @param mesh The mesh to highlight
  99765. */
  99766. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  99767. if (!this._excludedMeshes) {
  99768. return;
  99769. }
  99770. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  99771. if (meshExcluded) {
  99772. if (meshExcluded.beforeRender) {
  99773. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  99774. }
  99775. if (meshExcluded.afterRender) {
  99776. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  99777. }
  99778. }
  99779. this._excludedMeshes[mesh.uniqueId] = null;
  99780. };
  99781. /**
  99782. * Determine if a given mesh will be highlighted by the current HighlightLayer
  99783. * @param mesh mesh to test
  99784. * @returns true if the mesh will be highlighted by the current HighlightLayer
  99785. */
  99786. HighlightLayer.prototype.hasMesh = function (mesh) {
  99787. if (!this._meshes) {
  99788. return false;
  99789. }
  99790. if (!_super.prototype.hasMesh.call(this, mesh)) {
  99791. return false;
  99792. }
  99793. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  99794. };
  99795. /**
  99796. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  99797. * @param mesh The mesh to highlight
  99798. * @param color The color of the highlight
  99799. * @param glowEmissiveOnly Extract the glow from the emissive texture
  99800. */
  99801. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  99802. var _this = this;
  99803. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  99804. if (!this._meshes) {
  99805. return;
  99806. }
  99807. var meshHighlight = this._meshes[mesh.uniqueId];
  99808. if (meshHighlight) {
  99809. meshHighlight.color = color;
  99810. }
  99811. else {
  99812. this._meshes[mesh.uniqueId] = {
  99813. mesh: mesh,
  99814. color: color,
  99815. // Lambda required for capture due to Observable this context
  99816. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  99817. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  99818. _this._defaultStencilReference(mesh);
  99819. }
  99820. else {
  99821. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  99822. }
  99823. }),
  99824. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  99825. glowEmissiveOnly: glowEmissiveOnly
  99826. };
  99827. mesh.onDisposeObservable.add(function () {
  99828. _this._disposeMesh(mesh);
  99829. });
  99830. }
  99831. this._shouldRender = true;
  99832. };
  99833. /**
  99834. * Remove a mesh from the highlight layer in order to make it stop glowing.
  99835. * @param mesh The mesh to highlight
  99836. */
  99837. HighlightLayer.prototype.removeMesh = function (mesh) {
  99838. if (!this._meshes) {
  99839. return;
  99840. }
  99841. var meshHighlight = this._meshes[mesh.uniqueId];
  99842. if (meshHighlight) {
  99843. if (meshHighlight.observerHighlight) {
  99844. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  99845. }
  99846. if (meshHighlight.observerDefault) {
  99847. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  99848. }
  99849. delete this._meshes[mesh.uniqueId];
  99850. }
  99851. this._shouldRender = false;
  99852. for (var meshHighlightToCheck in this._meshes) {
  99853. if (this._meshes[meshHighlightToCheck]) {
  99854. this._shouldRender = true;
  99855. break;
  99856. }
  99857. }
  99858. };
  99859. /**
  99860. * Force the stencil to the normal expected value for none glowing parts
  99861. */
  99862. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  99863. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  99864. };
  99865. /**
  99866. * Free any resources and references associated to a mesh.
  99867. * Internal use
  99868. * @param mesh The mesh to free.
  99869. * @hidden
  99870. */
  99871. HighlightLayer.prototype._disposeMesh = function (mesh) {
  99872. this.removeMesh(mesh);
  99873. this.removeExcludedMesh(mesh);
  99874. };
  99875. /**
  99876. * Dispose the highlight layer and free resources.
  99877. */
  99878. HighlightLayer.prototype.dispose = function () {
  99879. if (this._meshes) {
  99880. // Clean mesh references
  99881. for (var id in this._meshes) {
  99882. var meshHighlight = this._meshes[id];
  99883. if (meshHighlight && meshHighlight.mesh) {
  99884. if (meshHighlight.observerHighlight) {
  99885. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  99886. }
  99887. if (meshHighlight.observerDefault) {
  99888. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  99889. }
  99890. }
  99891. }
  99892. this._meshes = null;
  99893. }
  99894. if (this._excludedMeshes) {
  99895. for (var id in this._excludedMeshes) {
  99896. var meshHighlight = this._excludedMeshes[id];
  99897. if (meshHighlight) {
  99898. if (meshHighlight.beforeRender) {
  99899. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  99900. }
  99901. if (meshHighlight.afterRender) {
  99902. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  99903. }
  99904. }
  99905. }
  99906. this._excludedMeshes = null;
  99907. }
  99908. _super.prototype.dispose.call(this);
  99909. };
  99910. /**
  99911. * Gets the class name of the effect layer
  99912. * @returns the string with the class name of the effect layer
  99913. */
  99914. HighlightLayer.prototype.getClassName = function () {
  99915. return "HighlightLayer";
  99916. };
  99917. /**
  99918. * Serializes this Highlight layer
  99919. * @returns a serialized Highlight layer object
  99920. */
  99921. HighlightLayer.prototype.serialize = function () {
  99922. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  99923. serializationObject.customType = "BABYLON.HighlightLayer";
  99924. // Highlighted meshes
  99925. serializationObject.meshes = [];
  99926. if (this._meshes) {
  99927. for (var m in this._meshes) {
  99928. var mesh = this._meshes[m];
  99929. if (mesh) {
  99930. serializationObject.meshes.push({
  99931. glowEmissiveOnly: mesh.glowEmissiveOnly,
  99932. color: mesh.color.asArray(),
  99933. meshId: mesh.mesh.id
  99934. });
  99935. }
  99936. }
  99937. }
  99938. // Excluded meshes
  99939. serializationObject.excludedMeshes = [];
  99940. if (this._excludedMeshes) {
  99941. for (var e in this._excludedMeshes) {
  99942. var excludedMesh = this._excludedMeshes[e];
  99943. if (excludedMesh) {
  99944. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  99945. }
  99946. }
  99947. }
  99948. return serializationObject;
  99949. };
  99950. /**
  99951. * Creates a Highlight layer from parsed Highlight layer data
  99952. * @param parsedHightlightLayer defines the Highlight layer data
  99953. * @param scene defines the current scene
  99954. * @param rootUrl defines the root URL containing the Highlight layer information
  99955. * @returns a parsed Highlight layer
  99956. */
  99957. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  99958. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  99959. var index;
  99960. // Excluded meshes
  99961. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  99962. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  99963. if (mesh) {
  99964. hl.addExcludedMesh(mesh);
  99965. }
  99966. }
  99967. // Included meshes
  99968. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  99969. var highlightedMesh = parsedHightlightLayer.meshes[index];
  99970. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  99971. if (mesh) {
  99972. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  99973. }
  99974. }
  99975. return hl;
  99976. };
  99977. /**
  99978. * Effect Name of the highlight layer.
  99979. */
  99980. HighlightLayer.EffectName = "HighlightLayer";
  99981. /**
  99982. * The neutral color used during the preparation of the glow effect.
  99983. * This is black by default as the blend operation is a blend operation.
  99984. */
  99985. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  99986. /**
  99987. * Stencil value used for glowing meshes.
  99988. */
  99989. HighlightLayer.GlowingMeshStencilReference = 0x02;
  99990. /**
  99991. * Stencil value used for the other meshes in the scene.
  99992. */
  99993. HighlightLayer.NormalMeshStencilReference = 0x01;
  99994. __decorate([
  99995. BABYLON.serialize()
  99996. ], HighlightLayer.prototype, "innerGlow", void 0);
  99997. __decorate([
  99998. BABYLON.serialize()
  99999. ], HighlightLayer.prototype, "outerGlow", void 0);
  100000. __decorate([
  100001. BABYLON.serialize()
  100002. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  100003. __decorate([
  100004. BABYLON.serialize()
  100005. ], HighlightLayer.prototype, "blurVerticalSize", null);
  100006. __decorate([
  100007. BABYLON.serialize("options")
  100008. ], HighlightLayer.prototype, "_options", void 0);
  100009. return HighlightLayer;
  100010. }(BABYLON.EffectLayer));
  100011. BABYLON.HighlightLayer = HighlightLayer;
  100012. })(BABYLON || (BABYLON = {}));
  100013. //# sourceMappingURL=babylon.highlightLayer.js.map
  100014. var BABYLON;
  100015. (function (BABYLON) {
  100016. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  100017. for (var index = 0; index < this.effectLayers.length; index++) {
  100018. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  100019. return this.effectLayers[index];
  100020. }
  100021. }
  100022. return null;
  100023. };
  100024. /**
  100025. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  100026. *
  100027. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  100028. * glowy meshes to your scene.
  100029. *
  100030. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  100031. */
  100032. var GlowLayer = /** @class */ (function (_super) {
  100033. __extends(GlowLayer, _super);
  100034. /**
  100035. * Instantiates a new glow Layer and references it to the scene.
  100036. * @param name The name of the layer
  100037. * @param scene The scene to use the layer in
  100038. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  100039. */
  100040. function GlowLayer(name, scene, options) {
  100041. var _this = _super.call(this, name, scene) || this;
  100042. _this._intensity = 1.0;
  100043. _this._includedOnlyMeshes = [];
  100044. _this._excludedMeshes = [];
  100045. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  100046. // Adapt options
  100047. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  100048. // Initialize the layer
  100049. _this._init({
  100050. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  100051. camera: _this._options.camera,
  100052. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  100053. mainTextureRatio: _this._options.mainTextureRatio,
  100054. renderingGroupId: _this._options.renderingGroupId
  100055. });
  100056. return _this;
  100057. }
  100058. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  100059. /**
  100060. * Gets the kernel size of the blur.
  100061. */
  100062. get: function () {
  100063. return this._horizontalBlurPostprocess1.kernel;
  100064. },
  100065. /**
  100066. * Sets the kernel size of the blur.
  100067. */
  100068. set: function (value) {
  100069. this._horizontalBlurPostprocess1.kernel = value;
  100070. this._verticalBlurPostprocess1.kernel = value;
  100071. this._horizontalBlurPostprocess2.kernel = value;
  100072. this._verticalBlurPostprocess2.kernel = value;
  100073. },
  100074. enumerable: true,
  100075. configurable: true
  100076. });
  100077. Object.defineProperty(GlowLayer.prototype, "intensity", {
  100078. /**
  100079. * Gets the glow intensity.
  100080. */
  100081. get: function () {
  100082. return this._intensity;
  100083. },
  100084. /**
  100085. * Sets the glow intensity.
  100086. */
  100087. set: function (value) {
  100088. this._intensity = value;
  100089. },
  100090. enumerable: true,
  100091. configurable: true
  100092. });
  100093. /**
  100094. * Get the effect name of the layer.
  100095. * @return The effect name
  100096. */
  100097. GlowLayer.prototype.getEffectName = function () {
  100098. return GlowLayer.EffectName;
  100099. };
  100100. /**
  100101. * Create the merge effect. This is the shader use to blit the information back
  100102. * to the main canvas at the end of the scene rendering.
  100103. */
  100104. GlowLayer.prototype._createMergeEffect = function () {
  100105. // Effect
  100106. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  100107. };
  100108. /**
  100109. * Creates the render target textures and post processes used in the glow layer.
  100110. */
  100111. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  100112. var _this = this;
  100113. var blurTextureWidth = this._mainTextureDesiredSize.width;
  100114. var blurTextureHeight = this._mainTextureDesiredSize.height;
  100115. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  100116. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  100117. var textureType = 0;
  100118. if (this._engine.getCaps().textureHalfFloatRender) {
  100119. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  100120. }
  100121. else {
  100122. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  100123. }
  100124. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  100125. width: blurTextureWidth,
  100126. height: blurTextureHeight
  100127. }, this._scene, false, true, textureType);
  100128. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100129. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100130. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  100131. this._blurTexture1.renderParticles = false;
  100132. this._blurTexture1.ignoreCameraViewport = true;
  100133. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  100134. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  100135. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  100136. width: blurTextureWidth2,
  100137. height: blurTextureHeight2
  100138. }, this._scene, false, true, textureType);
  100139. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100140. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100141. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  100142. this._blurTexture2.renderParticles = false;
  100143. this._blurTexture2.ignoreCameraViewport = true;
  100144. this._textures = [this._blurTexture1, this._blurTexture2];
  100145. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  100146. width: blurTextureWidth,
  100147. height: blurTextureHeight
  100148. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  100149. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  100150. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  100151. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  100152. effect.setTexture("textureSampler", _this._mainTexture);
  100153. });
  100154. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  100155. width: blurTextureWidth,
  100156. height: blurTextureHeight
  100157. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  100158. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  100159. width: blurTextureWidth2,
  100160. height: blurTextureHeight2
  100161. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  100162. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  100163. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  100164. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  100165. effect.setTexture("textureSampler", _this._blurTexture1);
  100166. });
  100167. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  100168. width: blurTextureWidth2,
  100169. height: blurTextureHeight2
  100170. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  100171. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  100172. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  100173. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  100174. this._mainTexture.samples = this._options.mainTextureSamples;
  100175. this._mainTexture.onAfterUnbindObservable.add(function () {
  100176. var internalTexture = _this._blurTexture1.getInternalTexture();
  100177. if (internalTexture) {
  100178. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  100179. internalTexture = _this._blurTexture2.getInternalTexture();
  100180. if (internalTexture) {
  100181. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  100182. }
  100183. }
  100184. });
  100185. // Prevent autoClear.
  100186. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  100187. };
  100188. /**
  100189. * Checks for the readiness of the element composing the layer.
  100190. * @param subMesh the mesh to check for
  100191. * @param useInstances specify wether or not to use instances to render the mesh
  100192. * @param emissiveTexture the associated emissive texture used to generate the glow
  100193. * @return true if ready otherwise, false
  100194. */
  100195. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  100196. var material = subMesh.getMaterial();
  100197. var mesh = subMesh.getRenderingMesh();
  100198. if (!material || !mesh) {
  100199. return false;
  100200. }
  100201. var emissiveTexture = material.emissiveTexture;
  100202. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  100203. };
  100204. /**
  100205. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  100206. */
  100207. GlowLayer.prototype.needStencil = function () {
  100208. return false;
  100209. };
  100210. /**
  100211. * Implementation specific of rendering the generating effect on the main canvas.
  100212. * @param effect The effect used to render through
  100213. */
  100214. GlowLayer.prototype._internalRender = function (effect) {
  100215. // Texture
  100216. effect.setTexture("textureSampler", this._blurTexture1);
  100217. effect.setTexture("textureSampler2", this._blurTexture2);
  100218. effect.setFloat("offset", this._intensity);
  100219. // Cache
  100220. var engine = this._engine;
  100221. var previousStencilBuffer = engine.getStencilBuffer();
  100222. // Draw order
  100223. engine.setStencilBuffer(false);
  100224. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  100225. // Draw order
  100226. engine.setStencilBuffer(previousStencilBuffer);
  100227. };
  100228. /**
  100229. * Sets the required values for both the emissive texture and and the main color.
  100230. */
  100231. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  100232. var textureLevel = 1.0;
  100233. if (this.customEmissiveTextureSelector) {
  100234. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  100235. }
  100236. else {
  100237. if (material) {
  100238. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  100239. if (this._emissiveTextureAndColor.texture) {
  100240. textureLevel = this._emissiveTextureAndColor.texture.level;
  100241. }
  100242. }
  100243. else {
  100244. this._emissiveTextureAndColor.texture = null;
  100245. }
  100246. }
  100247. if (this.customEmissiveColorSelector) {
  100248. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  100249. }
  100250. else {
  100251. if (material.emissiveColor) {
  100252. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  100253. }
  100254. else {
  100255. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  100256. }
  100257. }
  100258. };
  100259. /**
  100260. * Returns true if the mesh should render, otherwise false.
  100261. * @param mesh The mesh to render
  100262. * @returns true if it should render otherwise false
  100263. */
  100264. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  100265. return this.hasMesh(mesh);
  100266. };
  100267. /**
  100268. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  100269. * @param mesh The mesh to exclude from the glow layer
  100270. */
  100271. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  100272. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  100273. this._excludedMeshes.push(mesh.uniqueId);
  100274. }
  100275. };
  100276. /**
  100277. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  100278. * @param mesh The mesh to remove
  100279. */
  100280. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  100281. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  100282. if (index !== -1) {
  100283. this._excludedMeshes.splice(index, 1);
  100284. }
  100285. };
  100286. /**
  100287. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  100288. * @param mesh The mesh to include in the glow layer
  100289. */
  100290. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  100291. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  100292. this._includedOnlyMeshes.push(mesh.uniqueId);
  100293. }
  100294. };
  100295. /**
  100296. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  100297. * @param mesh The mesh to remove
  100298. */
  100299. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  100300. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  100301. if (index !== -1) {
  100302. this._includedOnlyMeshes.splice(index, 1);
  100303. }
  100304. };
  100305. /**
  100306. * Determine if a given mesh will be used in the glow layer
  100307. * @param mesh The mesh to test
  100308. * @returns true if the mesh will be highlighted by the current glow layer
  100309. */
  100310. GlowLayer.prototype.hasMesh = function (mesh) {
  100311. if (!_super.prototype.hasMesh.call(this, mesh)) {
  100312. return false;
  100313. }
  100314. // Included Mesh
  100315. if (this._includedOnlyMeshes.length) {
  100316. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  100317. }
  100318. ;
  100319. // Excluded Mesh
  100320. if (this._excludedMeshes.length) {
  100321. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  100322. }
  100323. ;
  100324. return true;
  100325. };
  100326. /**
  100327. * Free any resources and references associated to a mesh.
  100328. * Internal use
  100329. * @param mesh The mesh to free.
  100330. * @hidden
  100331. */
  100332. GlowLayer.prototype._disposeMesh = function (mesh) {
  100333. this.removeIncludedOnlyMesh(mesh);
  100334. this.removeExcludedMesh(mesh);
  100335. };
  100336. /**
  100337. * Gets the class name of the effect layer
  100338. * @returns the string with the class name of the effect layer
  100339. */
  100340. GlowLayer.prototype.getClassName = function () {
  100341. return "GlowLayer";
  100342. };
  100343. /**
  100344. * Serializes this glow layer
  100345. * @returns a serialized glow layer object
  100346. */
  100347. GlowLayer.prototype.serialize = function () {
  100348. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  100349. serializationObject.customType = "BABYLON.GlowLayer";
  100350. var index;
  100351. // Included meshes
  100352. serializationObject.includedMeshes = [];
  100353. if (this._includedOnlyMeshes.length) {
  100354. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  100355. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  100356. if (mesh) {
  100357. serializationObject.includedMeshes.push(mesh.id);
  100358. }
  100359. }
  100360. }
  100361. // Excluded meshes
  100362. serializationObject.excludedMeshes = [];
  100363. if (this._excludedMeshes.length) {
  100364. for (index = 0; index < this._excludedMeshes.length; index++) {
  100365. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  100366. if (mesh) {
  100367. serializationObject.excludedMeshes.push(mesh.id);
  100368. }
  100369. }
  100370. }
  100371. return serializationObject;
  100372. };
  100373. /**
  100374. * Creates a Glow Layer from parsed glow layer data
  100375. * @param parsedGlowLayer defines glow layer data
  100376. * @param scene defines the current scene
  100377. * @param rootUrl defines the root URL containing the glow layer information
  100378. * @returns a parsed Glow Layer
  100379. */
  100380. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  100381. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  100382. var index;
  100383. // Excluded meshes
  100384. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  100385. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  100386. if (mesh) {
  100387. gl.addExcludedMesh(mesh);
  100388. }
  100389. }
  100390. // Included meshes
  100391. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  100392. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  100393. if (mesh) {
  100394. gl.addIncludedOnlyMesh(mesh);
  100395. }
  100396. }
  100397. return gl;
  100398. };
  100399. /**
  100400. * Effect Name of the layer.
  100401. */
  100402. GlowLayer.EffectName = "GlowLayer";
  100403. /**
  100404. * The default blur kernel size used for the glow.
  100405. */
  100406. GlowLayer.DefaultBlurKernelSize = 32;
  100407. /**
  100408. * The default texture size ratio used for the glow.
  100409. */
  100410. GlowLayer.DefaultTextureRatio = 0.5;
  100411. __decorate([
  100412. BABYLON.serialize()
  100413. ], GlowLayer.prototype, "blurKernelSize", null);
  100414. __decorate([
  100415. BABYLON.serialize()
  100416. ], GlowLayer.prototype, "intensity", null);
  100417. __decorate([
  100418. BABYLON.serialize("options")
  100419. ], GlowLayer.prototype, "_options", void 0);
  100420. return GlowLayer;
  100421. }(BABYLON.EffectLayer));
  100422. BABYLON.GlowLayer = GlowLayer;
  100423. })(BABYLON || (BABYLON = {}));
  100424. //# sourceMappingURL=babylon.glowLayer.js.map
  100425. var BABYLON;
  100426. (function (BABYLON) {
  100427. /**
  100428. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  100429. */
  100430. var AssetTaskState;
  100431. (function (AssetTaskState) {
  100432. /**
  100433. * Initialization
  100434. */
  100435. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  100436. /**
  100437. * Running
  100438. */
  100439. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  100440. /**
  100441. * Done
  100442. */
  100443. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  100444. /**
  100445. * Error
  100446. */
  100447. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  100448. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  100449. /**
  100450. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  100451. */
  100452. var AbstractAssetTask = /** @class */ (function () {
  100453. /**
  100454. * Creates a new {BABYLON.AssetsManager}
  100455. * @param name defines the name of the task
  100456. */
  100457. function AbstractAssetTask(
  100458. /**
  100459. * Task name
  100460. */ name) {
  100461. this.name = name;
  100462. this._isCompleted = false;
  100463. this._taskState = AssetTaskState.INIT;
  100464. }
  100465. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  100466. /**
  100467. * Get if the task is completed
  100468. */
  100469. get: function () {
  100470. return this._isCompleted;
  100471. },
  100472. enumerable: true,
  100473. configurable: true
  100474. });
  100475. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  100476. /**
  100477. * Gets the current state of the task
  100478. */
  100479. get: function () {
  100480. return this._taskState;
  100481. },
  100482. enumerable: true,
  100483. configurable: true
  100484. });
  100485. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  100486. /**
  100487. * Gets the current error object (if task is in error)
  100488. */
  100489. get: function () {
  100490. return this._errorObject;
  100491. },
  100492. enumerable: true,
  100493. configurable: true
  100494. });
  100495. /**
  100496. * Internal only
  100497. * @hidden
  100498. */
  100499. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  100500. if (this._errorObject) {
  100501. return;
  100502. }
  100503. this._errorObject = {
  100504. message: message,
  100505. exception: exception
  100506. };
  100507. };
  100508. /**
  100509. * Execute the current task
  100510. * @param scene defines the scene where you want your assets to be loaded
  100511. * @param onSuccess is a callback called when the task is successfully executed
  100512. * @param onError is a callback called if an error occurs
  100513. */
  100514. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  100515. var _this = this;
  100516. this._taskState = AssetTaskState.RUNNING;
  100517. this.runTask(scene, function () {
  100518. _this.onDoneCallback(onSuccess, onError);
  100519. }, function (msg, exception) {
  100520. _this.onErrorCallback(onError, msg, exception);
  100521. });
  100522. };
  100523. /**
  100524. * Execute the current task
  100525. * @param scene defines the scene where you want your assets to be loaded
  100526. * @param onSuccess is a callback called when the task is successfully executed
  100527. * @param onError is a callback called if an error occurs
  100528. */
  100529. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  100530. throw new Error("runTask is not implemented");
  100531. };
  100532. /**
  100533. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  100534. * This can be used with failed tasks that have the reason for failure fixed.
  100535. */
  100536. AbstractAssetTask.prototype.reset = function () {
  100537. this._taskState = AssetTaskState.INIT;
  100538. };
  100539. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  100540. this._taskState = AssetTaskState.ERROR;
  100541. this._errorObject = {
  100542. message: message,
  100543. exception: exception
  100544. };
  100545. if (this.onError) {
  100546. this.onError(this, message, exception);
  100547. }
  100548. onError();
  100549. };
  100550. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  100551. try {
  100552. this._taskState = AssetTaskState.DONE;
  100553. this._isCompleted = true;
  100554. if (this.onSuccess) {
  100555. this.onSuccess(this);
  100556. }
  100557. onSuccess();
  100558. }
  100559. catch (e) {
  100560. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  100561. }
  100562. };
  100563. return AbstractAssetTask;
  100564. }());
  100565. BABYLON.AbstractAssetTask = AbstractAssetTask;
  100566. /**
  100567. * Class used to share progress information about assets loading
  100568. */
  100569. var AssetsProgressEvent = /** @class */ (function () {
  100570. /**
  100571. * Creates a {BABYLON.AssetsProgressEvent}
  100572. * @param remainingCount defines the number of remaining tasks to process
  100573. * @param totalCount defines the total number of tasks
  100574. * @param task defines the task that was just processed
  100575. */
  100576. function AssetsProgressEvent(remainingCount, totalCount, task) {
  100577. this.remainingCount = remainingCount;
  100578. this.totalCount = totalCount;
  100579. this.task = task;
  100580. }
  100581. return AssetsProgressEvent;
  100582. }());
  100583. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  100584. /**
  100585. * Define a task used by {BABYLON.AssetsManager} to load meshes
  100586. */
  100587. var MeshAssetTask = /** @class */ (function (_super) {
  100588. __extends(MeshAssetTask, _super);
  100589. /**
  100590. * Creates a new {BABYLON.MeshAssetTask}
  100591. * @param name defines the name of the task
  100592. * @param meshesNames defines the list of mesh's names you want to load
  100593. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  100594. * @param sceneFilename defines the filename of the scene to load from
  100595. */
  100596. function MeshAssetTask(
  100597. /**
  100598. * Defines the name of the task
  100599. */
  100600. name,
  100601. /**
  100602. * Defines the list of mesh's names you want to load
  100603. */
  100604. meshesNames,
  100605. /**
  100606. * Defines the root url to use as a base to load your meshes and associated resources
  100607. */
  100608. rootUrl,
  100609. /**
  100610. * Defines the filename of the scene to load from
  100611. */
  100612. sceneFilename) {
  100613. var _this = _super.call(this, name) || this;
  100614. _this.name = name;
  100615. _this.meshesNames = meshesNames;
  100616. _this.rootUrl = rootUrl;
  100617. _this.sceneFilename = sceneFilename;
  100618. return _this;
  100619. }
  100620. /**
  100621. * Execute the current task
  100622. * @param scene defines the scene where you want your assets to be loaded
  100623. * @param onSuccess is a callback called when the task is successfully executed
  100624. * @param onError is a callback called if an error occurs
  100625. */
  100626. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  100627. var _this = this;
  100628. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  100629. _this.loadedMeshes = meshes;
  100630. _this.loadedParticleSystems = particleSystems;
  100631. _this.loadedSkeletons = skeletons;
  100632. onSuccess();
  100633. }, null, function (scene, message, exception) {
  100634. onError(message, exception);
  100635. });
  100636. };
  100637. return MeshAssetTask;
  100638. }(AbstractAssetTask));
  100639. BABYLON.MeshAssetTask = MeshAssetTask;
  100640. /**
  100641. * Define a task used by {BABYLON.AssetsManager} to load text content
  100642. */
  100643. var TextFileAssetTask = /** @class */ (function (_super) {
  100644. __extends(TextFileAssetTask, _super);
  100645. /**
  100646. * Creates a new TextFileAssetTask object
  100647. * @param name defines the name of the task
  100648. * @param url defines the location of the file to load
  100649. */
  100650. function TextFileAssetTask(
  100651. /**
  100652. * Defines the name of the task
  100653. */
  100654. name,
  100655. /**
  100656. * Defines the location of the file to load
  100657. */
  100658. url) {
  100659. var _this = _super.call(this, name) || this;
  100660. _this.name = name;
  100661. _this.url = url;
  100662. return _this;
  100663. }
  100664. /**
  100665. * Execute the current task
  100666. * @param scene defines the scene where you want your assets to be loaded
  100667. * @param onSuccess is a callback called when the task is successfully executed
  100668. * @param onError is a callback called if an error occurs
  100669. */
  100670. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  100671. var _this = this;
  100672. scene._loadFile(this.url, function (data) {
  100673. _this.text = data;
  100674. onSuccess();
  100675. }, undefined, false, false, function (request, exception) {
  100676. if (request) {
  100677. onError(request.status + " " + request.statusText, exception);
  100678. }
  100679. });
  100680. };
  100681. return TextFileAssetTask;
  100682. }(AbstractAssetTask));
  100683. BABYLON.TextFileAssetTask = TextFileAssetTask;
  100684. /**
  100685. * Define a task used by {BABYLON.AssetsManager} to load binary data
  100686. */
  100687. var BinaryFileAssetTask = /** @class */ (function (_super) {
  100688. __extends(BinaryFileAssetTask, _super);
  100689. /**
  100690. * Creates a new BinaryFileAssetTask object
  100691. * @param name defines the name of the new task
  100692. * @param url defines the location of the file to load
  100693. */
  100694. function BinaryFileAssetTask(
  100695. /**
  100696. * Defines the name of the task
  100697. */
  100698. name,
  100699. /**
  100700. * Defines the location of the file to load
  100701. */
  100702. url) {
  100703. var _this = _super.call(this, name) || this;
  100704. _this.name = name;
  100705. _this.url = url;
  100706. return _this;
  100707. }
  100708. /**
  100709. * Execute the current task
  100710. * @param scene defines the scene where you want your assets to be loaded
  100711. * @param onSuccess is a callback called when the task is successfully executed
  100712. * @param onError is a callback called if an error occurs
  100713. */
  100714. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  100715. var _this = this;
  100716. scene._loadFile(this.url, function (data) {
  100717. _this.data = data;
  100718. onSuccess();
  100719. }, undefined, true, true, function (request, exception) {
  100720. if (request) {
  100721. onError(request.status + " " + request.statusText, exception);
  100722. }
  100723. });
  100724. };
  100725. return BinaryFileAssetTask;
  100726. }(AbstractAssetTask));
  100727. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  100728. /**
  100729. * Define a task used by {BABYLON.AssetsManager} to load images
  100730. */
  100731. var ImageAssetTask = /** @class */ (function (_super) {
  100732. __extends(ImageAssetTask, _super);
  100733. /**
  100734. * Creates a new ImageAssetTask
  100735. * @param name defines the name of the task
  100736. * @param url defines the location of the image to load
  100737. */
  100738. function ImageAssetTask(
  100739. /**
  100740. * Defines the name of the task
  100741. */
  100742. name,
  100743. /**
  100744. * Defines the location of the image to load
  100745. */
  100746. url) {
  100747. var _this = _super.call(this, name) || this;
  100748. _this.name = name;
  100749. _this.url = url;
  100750. return _this;
  100751. }
  100752. /**
  100753. * Execute the current task
  100754. * @param scene defines the scene where you want your assets to be loaded
  100755. * @param onSuccess is a callback called when the task is successfully executed
  100756. * @param onError is a callback called if an error occurs
  100757. */
  100758. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  100759. var _this = this;
  100760. var img = new Image();
  100761. BABYLON.Tools.SetCorsBehavior(this.url, img);
  100762. img.onload = function () {
  100763. _this.image = img;
  100764. onSuccess();
  100765. };
  100766. img.onerror = function (err) {
  100767. onError("Error loading image", err);
  100768. };
  100769. img.src = this.url;
  100770. };
  100771. return ImageAssetTask;
  100772. }(AbstractAssetTask));
  100773. BABYLON.ImageAssetTask = ImageAssetTask;
  100774. /**
  100775. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  100776. */
  100777. var TextureAssetTask = /** @class */ (function (_super) {
  100778. __extends(TextureAssetTask, _super);
  100779. /**
  100780. * Creates a new TextureAssetTask object
  100781. * @param name defines the name of the task
  100782. * @param url defines the location of the file to load
  100783. * @param noMipmap defines if mipmap should not be generated (default is false)
  100784. * @param invertY defines if texture must be inverted on Y axis (default is false)
  100785. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  100786. */
  100787. function TextureAssetTask(
  100788. /**
  100789. * Defines the name of the task
  100790. */
  100791. name,
  100792. /**
  100793. * Defines the location of the file to load
  100794. */
  100795. url,
  100796. /**
  100797. * Defines if mipmap should not be generated (default is false)
  100798. */
  100799. noMipmap,
  100800. /**
  100801. * Defines if texture must be inverted on Y axis (default is false)
  100802. */
  100803. invertY,
  100804. /**
  100805. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  100806. */
  100807. samplingMode) {
  100808. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  100809. var _this = _super.call(this, name) || this;
  100810. _this.name = name;
  100811. _this.url = url;
  100812. _this.noMipmap = noMipmap;
  100813. _this.invertY = invertY;
  100814. _this.samplingMode = samplingMode;
  100815. return _this;
  100816. }
  100817. /**
  100818. * Execute the current task
  100819. * @param scene defines the scene where you want your assets to be loaded
  100820. * @param onSuccess is a callback called when the task is successfully executed
  100821. * @param onError is a callback called if an error occurs
  100822. */
  100823. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  100824. var onload = function () {
  100825. onSuccess();
  100826. };
  100827. var onerror = function (message, exception) {
  100828. onError(message, exception);
  100829. };
  100830. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  100831. };
  100832. return TextureAssetTask;
  100833. }(AbstractAssetTask));
  100834. BABYLON.TextureAssetTask = TextureAssetTask;
  100835. /**
  100836. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  100837. */
  100838. var CubeTextureAssetTask = /** @class */ (function (_super) {
  100839. __extends(CubeTextureAssetTask, _super);
  100840. /**
  100841. * Creates a new CubeTextureAssetTask
  100842. * @param name defines the name of the task
  100843. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  100844. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  100845. * @param noMipmap defines if mipmaps should not be generated (default is false)
  100846. * @param files defines the explicit list of files (undefined by default)
  100847. */
  100848. function CubeTextureAssetTask(
  100849. /**
  100850. * Defines the name of the task
  100851. */
  100852. name,
  100853. /**
  100854. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  100855. */
  100856. url,
  100857. /**
  100858. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  100859. */
  100860. extensions,
  100861. /**
  100862. * Defines if mipmaps should not be generated (default is false)
  100863. */
  100864. noMipmap,
  100865. /**
  100866. * Defines the explicit list of files (undefined by default)
  100867. */
  100868. files) {
  100869. var _this = _super.call(this, name) || this;
  100870. _this.name = name;
  100871. _this.url = url;
  100872. _this.extensions = extensions;
  100873. _this.noMipmap = noMipmap;
  100874. _this.files = files;
  100875. return _this;
  100876. }
  100877. /**
  100878. * Execute the current task
  100879. * @param scene defines the scene where you want your assets to be loaded
  100880. * @param onSuccess is a callback called when the task is successfully executed
  100881. * @param onError is a callback called if an error occurs
  100882. */
  100883. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  100884. var onload = function () {
  100885. onSuccess();
  100886. };
  100887. var onerror = function (message, exception) {
  100888. onError(message, exception);
  100889. };
  100890. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  100891. };
  100892. return CubeTextureAssetTask;
  100893. }(AbstractAssetTask));
  100894. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  100895. /**
  100896. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  100897. */
  100898. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  100899. __extends(HDRCubeTextureAssetTask, _super);
  100900. /**
  100901. * Creates a new HDRCubeTextureAssetTask object
  100902. * @param name defines the name of the task
  100903. * @param url defines the location of the file to load
  100904. * @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.
  100905. * @param noMipmap defines if mipmaps should not be generated (default is false)
  100906. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  100907. * @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)
  100908. * @param reserved Internal use only
  100909. */
  100910. function HDRCubeTextureAssetTask(
  100911. /**
  100912. * Defines the name of the task
  100913. */
  100914. name,
  100915. /**
  100916. * Defines the location of the file to load
  100917. */
  100918. url,
  100919. /**
  100920. * Defines the desired size (the more it increases the longer the generation will be)
  100921. */
  100922. size,
  100923. /**
  100924. * Defines if mipmaps should not be generated (default is false)
  100925. */
  100926. noMipmap,
  100927. /**
  100928. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  100929. */
  100930. generateHarmonics,
  100931. /**
  100932. * 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)
  100933. */
  100934. gammaSpace,
  100935. /**
  100936. * Internal Use Only
  100937. */
  100938. reserved) {
  100939. if (noMipmap === void 0) { noMipmap = false; }
  100940. if (generateHarmonics === void 0) { generateHarmonics = true; }
  100941. if (gammaSpace === void 0) { gammaSpace = false; }
  100942. if (reserved === void 0) { reserved = false; }
  100943. var _this = _super.call(this, name) || this;
  100944. _this.name = name;
  100945. _this.url = url;
  100946. _this.size = size;
  100947. _this.noMipmap = noMipmap;
  100948. _this.generateHarmonics = generateHarmonics;
  100949. _this.gammaSpace = gammaSpace;
  100950. _this.reserved = reserved;
  100951. return _this;
  100952. }
  100953. /**
  100954. * Execute the current task
  100955. * @param scene defines the scene where you want your assets to be loaded
  100956. * @param onSuccess is a callback called when the task is successfully executed
  100957. * @param onError is a callback called if an error occurs
  100958. */
  100959. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  100960. var onload = function () {
  100961. onSuccess();
  100962. };
  100963. var onerror = function (message, exception) {
  100964. onError(message, exception);
  100965. };
  100966. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  100967. };
  100968. return HDRCubeTextureAssetTask;
  100969. }(AbstractAssetTask));
  100970. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  100971. /**
  100972. * This class can be used to easily import assets into a scene
  100973. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  100974. */
  100975. var AssetsManager = /** @class */ (function () {
  100976. /**
  100977. * Creates a new AssetsManager
  100978. * @param scene defines the scene to work on
  100979. */
  100980. function AssetsManager(scene) {
  100981. this._isLoading = false;
  100982. this._tasks = new Array();
  100983. this._waitingTasksCount = 0;
  100984. this._totalTasksCount = 0;
  100985. /**
  100986. * Observable called when all tasks are processed
  100987. */
  100988. this.onTaskSuccessObservable = new BABYLON.Observable();
  100989. /**
  100990. * Observable called when a task had an error
  100991. */
  100992. this.onTaskErrorObservable = new BABYLON.Observable();
  100993. /**
  100994. * Observable called when a task is successful
  100995. */
  100996. this.onTasksDoneObservable = new BABYLON.Observable();
  100997. /**
  100998. * Observable called when a task is done (whatever the result is)
  100999. */
  101000. this.onProgressObservable = new BABYLON.Observable();
  101001. /**
  101002. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  101003. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  101004. */
  101005. this.useDefaultLoadingScreen = true;
  101006. this._scene = scene;
  101007. }
  101008. /**
  101009. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  101010. * @param taskName defines the name of the new task
  101011. * @param meshesNames defines the name of meshes to load
  101012. * @param rootUrl defines the root url to use to locate files
  101013. * @param sceneFilename defines the filename of the scene file
  101014. * @returns a new {BABYLON.MeshAssetTask} object
  101015. */
  101016. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  101017. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  101018. this._tasks.push(task);
  101019. return task;
  101020. };
  101021. /**
  101022. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  101023. * @param taskName defines the name of the new task
  101024. * @param url defines the url of the file to load
  101025. * @returns a new {BABYLON.TextFileAssetTask} object
  101026. */
  101027. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  101028. var task = new TextFileAssetTask(taskName, url);
  101029. this._tasks.push(task);
  101030. return task;
  101031. };
  101032. /**
  101033. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  101034. * @param taskName defines the name of the new task
  101035. * @param url defines the url of the file to load
  101036. * @returns a new {BABYLON.BinaryFileAssetTask} object
  101037. */
  101038. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  101039. var task = new BinaryFileAssetTask(taskName, url);
  101040. this._tasks.push(task);
  101041. return task;
  101042. };
  101043. /**
  101044. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  101045. * @param taskName defines the name of the new task
  101046. * @param url defines the url of the file to load
  101047. * @returns a new {BABYLON.ImageAssetTask} object
  101048. */
  101049. AssetsManager.prototype.addImageTask = function (taskName, url) {
  101050. var task = new ImageAssetTask(taskName, url);
  101051. this._tasks.push(task);
  101052. return task;
  101053. };
  101054. /**
  101055. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  101056. * @param taskName defines the name of the new task
  101057. * @param url defines the url of the file to load
  101058. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  101059. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  101060. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  101061. * @returns a new {BABYLON.TextureAssetTask} object
  101062. */
  101063. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  101064. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  101065. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  101066. this._tasks.push(task);
  101067. return task;
  101068. };
  101069. /**
  101070. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  101071. * @param taskName defines the name of the new task
  101072. * @param url defines the url of the file to load
  101073. * @param extensions defines the extension to use to load the cube map (can be null)
  101074. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  101075. * @param files defines the list of files to load (can be null)
  101076. * @returns a new {BABYLON.CubeTextureAssetTask} object
  101077. */
  101078. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  101079. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  101080. this._tasks.push(task);
  101081. return task;
  101082. };
  101083. /**
  101084. *
  101085. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  101086. * @param taskName defines the name of the new task
  101087. * @param url defines the url of the file to load
  101088. * @param size defines the size you want for the cubemap (can be null)
  101089. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  101090. * @param generateHarmonics defines if you want to automatically generate (true by default)
  101091. * @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)
  101092. * @param reserved Internal use only
  101093. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  101094. */
  101095. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  101096. if (noMipmap === void 0) { noMipmap = false; }
  101097. if (generateHarmonics === void 0) { generateHarmonics = true; }
  101098. if (gammaSpace === void 0) { gammaSpace = false; }
  101099. if (reserved === void 0) { reserved = false; }
  101100. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  101101. this._tasks.push(task);
  101102. return task;
  101103. };
  101104. /**
  101105. * Remove a task from the assets manager.
  101106. * @param task the task to remove
  101107. */
  101108. AssetsManager.prototype.removeTask = function (task) {
  101109. var index = this._tasks.indexOf(task);
  101110. if (index > -1) {
  101111. this._tasks.splice(index, 1);
  101112. }
  101113. };
  101114. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  101115. this._waitingTasksCount--;
  101116. try {
  101117. if (this.onProgress) {
  101118. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  101119. }
  101120. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  101121. }
  101122. catch (e) {
  101123. BABYLON.Tools.Error("Error running progress callbacks.");
  101124. console.log(e);
  101125. }
  101126. if (this._waitingTasksCount === 0) {
  101127. try {
  101128. if (this.onFinish) {
  101129. this.onFinish(this._tasks);
  101130. }
  101131. // Let's remove successfull tasks
  101132. var currentTasks = this._tasks.slice();
  101133. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  101134. var task = currentTasks_1[_i];
  101135. if (task.taskState === AssetTaskState.DONE) {
  101136. var index = this._tasks.indexOf(task);
  101137. if (index > -1) {
  101138. this._tasks.splice(index, 1);
  101139. }
  101140. }
  101141. }
  101142. this.onTasksDoneObservable.notifyObservers(this._tasks);
  101143. }
  101144. catch (e) {
  101145. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  101146. console.log(e);
  101147. }
  101148. this._isLoading = false;
  101149. this._scene.getEngine().hideLoadingUI();
  101150. }
  101151. };
  101152. AssetsManager.prototype._runTask = function (task) {
  101153. var _this = this;
  101154. var done = function () {
  101155. try {
  101156. if (_this.onTaskSuccess) {
  101157. _this.onTaskSuccess(task);
  101158. }
  101159. _this.onTaskSuccessObservable.notifyObservers(task);
  101160. _this._decreaseWaitingTasksCount(task);
  101161. }
  101162. catch (e) {
  101163. error("Error executing task success callbacks", e);
  101164. }
  101165. };
  101166. var error = function (message, exception) {
  101167. task._setErrorObject(message, exception);
  101168. if (_this.onTaskError) {
  101169. _this.onTaskError(task);
  101170. }
  101171. _this.onTaskErrorObservable.notifyObservers(task);
  101172. _this._decreaseWaitingTasksCount(task);
  101173. };
  101174. task.run(this._scene, done, error);
  101175. };
  101176. /**
  101177. * Reset the {BABYLON.AssetsManager} and remove all tasks
  101178. * @return the current instance of the {BABYLON.AssetsManager}
  101179. */
  101180. AssetsManager.prototype.reset = function () {
  101181. this._isLoading = false;
  101182. this._tasks = new Array();
  101183. return this;
  101184. };
  101185. /**
  101186. * Start the loading process
  101187. * @return the current instance of the {BABYLON.AssetsManager}
  101188. */
  101189. AssetsManager.prototype.load = function () {
  101190. if (this._isLoading) {
  101191. return this;
  101192. }
  101193. this._isLoading = true;
  101194. this._waitingTasksCount = this._tasks.length;
  101195. this._totalTasksCount = this._tasks.length;
  101196. if (this._waitingTasksCount === 0) {
  101197. this._isLoading = false;
  101198. if (this.onFinish) {
  101199. this.onFinish(this._tasks);
  101200. }
  101201. this.onTasksDoneObservable.notifyObservers(this._tasks);
  101202. return this;
  101203. }
  101204. if (this.useDefaultLoadingScreen) {
  101205. this._scene.getEngine().displayLoadingUI();
  101206. }
  101207. for (var index = 0; index < this._tasks.length; index++) {
  101208. var task = this._tasks[index];
  101209. if (task.taskState === AssetTaskState.INIT) {
  101210. this._runTask(task);
  101211. }
  101212. }
  101213. return this;
  101214. };
  101215. return AssetsManager;
  101216. }());
  101217. BABYLON.AssetsManager = AssetsManager;
  101218. })(BABYLON || (BABYLON = {}));
  101219. //# sourceMappingURL=babylon.assetsManager.js.map
  101220. var BABYLON;
  101221. (function (BABYLON) {
  101222. var serializedGeometries = [];
  101223. var serializeGeometry = function (geometry, serializationGeometries) {
  101224. if (serializedGeometries[geometry.id]) {
  101225. return;
  101226. }
  101227. if (geometry.doNotSerialize) {
  101228. return;
  101229. }
  101230. if (geometry instanceof BABYLON.BoxGeometry) {
  101231. serializationGeometries.boxes.push(geometry.serialize());
  101232. }
  101233. else if (geometry instanceof BABYLON.SphereGeometry) {
  101234. serializationGeometries.spheres.push(geometry.serialize());
  101235. }
  101236. else if (geometry instanceof BABYLON.CylinderGeometry) {
  101237. serializationGeometries.cylinders.push(geometry.serialize());
  101238. }
  101239. else if (geometry instanceof BABYLON.TorusGeometry) {
  101240. serializationGeometries.toruses.push(geometry.serialize());
  101241. }
  101242. else if (geometry instanceof BABYLON.GroundGeometry) {
  101243. serializationGeometries.grounds.push(geometry.serialize());
  101244. }
  101245. else if (geometry instanceof BABYLON.Plane) {
  101246. serializationGeometries.planes.push(geometry.serialize());
  101247. }
  101248. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  101249. serializationGeometries.torusKnots.push(geometry.serialize());
  101250. }
  101251. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  101252. throw new Error("Unknown primitive type");
  101253. }
  101254. else {
  101255. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  101256. }
  101257. serializedGeometries[geometry.id] = true;
  101258. };
  101259. var serializeMesh = function (mesh, serializationScene) {
  101260. var serializationObject = {};
  101261. // Geometry
  101262. var geometry = mesh._geometry;
  101263. if (geometry) {
  101264. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  101265. // 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
  101266. serializeGeometry(geometry, serializationScene.geometries);
  101267. }
  101268. }
  101269. // Custom
  101270. if (mesh.serialize) {
  101271. mesh.serialize(serializationObject);
  101272. }
  101273. return serializationObject;
  101274. };
  101275. var finalizeSingleMesh = function (mesh, serializationObject) {
  101276. //only works if the mesh is already loaded
  101277. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  101278. //serialize material
  101279. if (mesh.material) {
  101280. if (mesh.material instanceof BABYLON.MultiMaterial) {
  101281. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  101282. serializationObject.materials = serializationObject.materials || [];
  101283. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  101284. serializationObject.multiMaterials.push(mesh.material.serialize());
  101285. var _loop_1 = function (submaterial) {
  101286. if (submaterial) {
  101287. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  101288. serializationObject.materials.push(submaterial.serialize());
  101289. }
  101290. }
  101291. };
  101292. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  101293. var submaterial = _a[_i];
  101294. _loop_1(submaterial);
  101295. }
  101296. }
  101297. }
  101298. else {
  101299. serializationObject.materials = serializationObject.materials || [];
  101300. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  101301. serializationObject.materials.push(mesh.material.serialize());
  101302. }
  101303. }
  101304. }
  101305. //serialize geometry
  101306. var geometry = mesh._geometry;
  101307. if (geometry) {
  101308. if (!serializationObject.geometries) {
  101309. serializationObject.geometries = {};
  101310. serializationObject.geometries.boxes = [];
  101311. serializationObject.geometries.spheres = [];
  101312. serializationObject.geometries.cylinders = [];
  101313. serializationObject.geometries.toruses = [];
  101314. serializationObject.geometries.grounds = [];
  101315. serializationObject.geometries.planes = [];
  101316. serializationObject.geometries.torusKnots = [];
  101317. serializationObject.geometries.vertexData = [];
  101318. }
  101319. serializeGeometry(geometry, serializationObject.geometries);
  101320. }
  101321. // Skeletons
  101322. if (mesh.skeleton) {
  101323. serializationObject.skeletons = serializationObject.skeletons || [];
  101324. serializationObject.skeletons.push(mesh.skeleton.serialize());
  101325. }
  101326. //serialize the actual mesh
  101327. serializationObject.meshes = serializationObject.meshes || [];
  101328. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  101329. }
  101330. };
  101331. var SceneSerializer = /** @class */ (function () {
  101332. function SceneSerializer() {
  101333. }
  101334. SceneSerializer.ClearCache = function () {
  101335. serializedGeometries = [];
  101336. };
  101337. SceneSerializer.Serialize = function (scene) {
  101338. var serializationObject = {};
  101339. SceneSerializer.ClearCache();
  101340. // Scene
  101341. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  101342. serializationObject.autoClear = scene.autoClear;
  101343. serializationObject.clearColor = scene.clearColor.asArray();
  101344. serializationObject.ambientColor = scene.ambientColor.asArray();
  101345. serializationObject.gravity = scene.gravity.asArray();
  101346. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  101347. serializationObject.workerCollisions = scene.workerCollisions;
  101348. // Fog
  101349. if (scene.fogMode && scene.fogMode !== 0) {
  101350. serializationObject.fogMode = scene.fogMode;
  101351. serializationObject.fogColor = scene.fogColor.asArray();
  101352. serializationObject.fogStart = scene.fogStart;
  101353. serializationObject.fogEnd = scene.fogEnd;
  101354. serializationObject.fogDensity = scene.fogDensity;
  101355. }
  101356. //Physics
  101357. if (scene.isPhysicsEnabled()) {
  101358. var physicEngine = scene.getPhysicsEngine();
  101359. if (physicEngine) {
  101360. serializationObject.physicsEnabled = true;
  101361. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  101362. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  101363. }
  101364. }
  101365. // Metadata
  101366. if (scene.metadata) {
  101367. serializationObject.metadata = scene.metadata;
  101368. }
  101369. // Morph targets
  101370. serializationObject.morphTargetManagers = [];
  101371. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  101372. var abstractMesh = _a[_i];
  101373. var manager = abstractMesh.morphTargetManager;
  101374. if (manager) {
  101375. serializationObject.morphTargetManagers.push(manager.serialize());
  101376. }
  101377. }
  101378. // Lights
  101379. serializationObject.lights = [];
  101380. var index;
  101381. var light;
  101382. for (index = 0; index < scene.lights.length; index++) {
  101383. light = scene.lights[index];
  101384. if (!light.doNotSerialize) {
  101385. serializationObject.lights.push(light.serialize());
  101386. }
  101387. }
  101388. // Cameras
  101389. serializationObject.cameras = [];
  101390. for (index = 0; index < scene.cameras.length; index++) {
  101391. var camera = scene.cameras[index];
  101392. if (!camera.doNotSerialize) {
  101393. serializationObject.cameras.push(camera.serialize());
  101394. }
  101395. }
  101396. if (scene.activeCamera) {
  101397. serializationObject.activeCameraID = scene.activeCamera.id;
  101398. }
  101399. // Animations
  101400. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  101401. // Materials
  101402. serializationObject.materials = [];
  101403. serializationObject.multiMaterials = [];
  101404. var material;
  101405. for (index = 0; index < scene.materials.length; index++) {
  101406. material = scene.materials[index];
  101407. if (!material.doNotSerialize) {
  101408. serializationObject.materials.push(material.serialize());
  101409. }
  101410. }
  101411. // MultiMaterials
  101412. serializationObject.multiMaterials = [];
  101413. for (index = 0; index < scene.multiMaterials.length; index++) {
  101414. var multiMaterial = scene.multiMaterials[index];
  101415. serializationObject.multiMaterials.push(multiMaterial.serialize());
  101416. }
  101417. // Environment texture
  101418. if (scene.environmentTexture) {
  101419. serializationObject.environmentTexture = scene.environmentTexture.name;
  101420. }
  101421. // Skeletons
  101422. serializationObject.skeletons = [];
  101423. for (index = 0; index < scene.skeletons.length; index++) {
  101424. var skeleton = scene.skeletons[index];
  101425. if (!skeleton.doNotSerialize) {
  101426. serializationObject.skeletons.push(skeleton.serialize());
  101427. }
  101428. }
  101429. // Transform nodes
  101430. serializationObject.transformNodes = [];
  101431. for (index = 0; index < scene.transformNodes.length; index++) {
  101432. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  101433. }
  101434. // Geometries
  101435. serializationObject.geometries = {};
  101436. serializationObject.geometries.boxes = [];
  101437. serializationObject.geometries.spheres = [];
  101438. serializationObject.geometries.cylinders = [];
  101439. serializationObject.geometries.toruses = [];
  101440. serializationObject.geometries.grounds = [];
  101441. serializationObject.geometries.planes = [];
  101442. serializationObject.geometries.torusKnots = [];
  101443. serializationObject.geometries.vertexData = [];
  101444. serializedGeometries = [];
  101445. var geometries = scene.getGeometries();
  101446. for (index = 0; index < geometries.length; index++) {
  101447. var geometry = geometries[index];
  101448. if (geometry.isReady()) {
  101449. serializeGeometry(geometry, serializationObject.geometries);
  101450. }
  101451. }
  101452. // Meshes
  101453. serializationObject.meshes = [];
  101454. for (index = 0; index < scene.meshes.length; index++) {
  101455. var abstractMesh = scene.meshes[index];
  101456. if (abstractMesh instanceof BABYLON.Mesh) {
  101457. var mesh = abstractMesh;
  101458. if (!mesh.doNotSerialize) {
  101459. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  101460. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  101461. }
  101462. }
  101463. }
  101464. }
  101465. // Particles Systems
  101466. serializationObject.particleSystems = [];
  101467. for (index = 0; index < scene.particleSystems.length; index++) {
  101468. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  101469. }
  101470. // Shadows
  101471. serializationObject.shadowGenerators = [];
  101472. for (index = 0; index < scene.lights.length; index++) {
  101473. light = scene.lights[index];
  101474. var shadowGenerator = light.getShadowGenerator();
  101475. if (shadowGenerator) {
  101476. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  101477. }
  101478. }
  101479. // Action Manager
  101480. if (scene.actionManager) {
  101481. serializationObject.actions = scene.actionManager.serialize("scene");
  101482. }
  101483. // Audio
  101484. serializationObject.sounds = [];
  101485. for (index = 0; index < scene.soundTracks.length; index++) {
  101486. var soundtrack = scene.soundTracks[index];
  101487. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  101488. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  101489. }
  101490. }
  101491. // Components
  101492. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  101493. var component = _c[_b];
  101494. component.serialize(serializationObject);
  101495. }
  101496. return serializationObject;
  101497. };
  101498. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  101499. if (withParents === void 0) { withParents = false; }
  101500. if (withChildren === void 0) { withChildren = false; }
  101501. var serializationObject = {};
  101502. SceneSerializer.ClearCache();
  101503. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  101504. if (withParents || withChildren) {
  101505. //deliberate for loop! not for each, appended should be processed as well.
  101506. for (var i = 0; i < toSerialize.length; ++i) {
  101507. if (withChildren) {
  101508. toSerialize[i].getDescendants().forEach(function (node) {
  101509. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  101510. toSerialize.push(node);
  101511. }
  101512. });
  101513. }
  101514. //make sure the array doesn't contain the object already
  101515. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  101516. toSerialize.push(toSerialize[i].parent);
  101517. }
  101518. }
  101519. }
  101520. toSerialize.forEach(function (mesh) {
  101521. finalizeSingleMesh(mesh, serializationObject);
  101522. });
  101523. return serializationObject;
  101524. };
  101525. return SceneSerializer;
  101526. }());
  101527. BABYLON.SceneSerializer = SceneSerializer;
  101528. })(BABYLON || (BABYLON = {}));
  101529. //# sourceMappingURL=babylon.sceneSerializer.js.map
  101530. var BABYLON;
  101531. (function (BABYLON) {
  101532. /**
  101533. * Class used to generate realtime reflection / refraction cube textures
  101534. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  101535. */
  101536. var ReflectionProbe = /** @class */ (function () {
  101537. /**
  101538. * Creates a new reflection probe
  101539. * @param name defines the name of the probe
  101540. * @param size defines the texture resolution (for each face)
  101541. * @param scene defines the hosting scene
  101542. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  101543. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  101544. */
  101545. function ReflectionProbe(
  101546. /** defines the name of the probe */
  101547. name, size, scene, generateMipMaps, useFloat) {
  101548. if (generateMipMaps === void 0) { generateMipMaps = true; }
  101549. if (useFloat === void 0) { useFloat = false; }
  101550. var _this = this;
  101551. this.name = name;
  101552. this._viewMatrix = BABYLON.Matrix.Identity();
  101553. this._target = BABYLON.Vector3.Zero();
  101554. this._add = BABYLON.Vector3.Zero();
  101555. this._invertYAxis = false;
  101556. /** Gets or sets probe position (center of the cube map) */
  101557. this.position = BABYLON.Vector3.Zero();
  101558. this._scene = scene;
  101559. this._scene.reflectionProbes.push(this);
  101560. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  101561. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  101562. switch (faceIndex) {
  101563. case 0:
  101564. _this._add.copyFromFloats(1, 0, 0);
  101565. break;
  101566. case 1:
  101567. _this._add.copyFromFloats(-1, 0, 0);
  101568. break;
  101569. case 2:
  101570. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  101571. break;
  101572. case 3:
  101573. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  101574. break;
  101575. case 4:
  101576. _this._add.copyFromFloats(0, 0, 1);
  101577. break;
  101578. case 5:
  101579. _this._add.copyFromFloats(0, 0, -1);
  101580. break;
  101581. }
  101582. if (_this._attachedMesh) {
  101583. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  101584. }
  101585. _this.position.addToRef(_this._add, _this._target);
  101586. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  101587. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  101588. scene._forcedViewPosition = _this.position;
  101589. });
  101590. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  101591. scene._forcedViewPosition = null;
  101592. scene.updateTransformMatrix(true);
  101593. });
  101594. if (scene.activeCamera) {
  101595. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  101596. }
  101597. }
  101598. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  101599. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  101600. get: function () {
  101601. return this._renderTargetTexture.samples;
  101602. },
  101603. set: function (value) {
  101604. this._renderTargetTexture.samples = value;
  101605. },
  101606. enumerable: true,
  101607. configurable: true
  101608. });
  101609. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  101610. /** Gets or sets the refresh rate to use (on every frame by default) */
  101611. get: function () {
  101612. return this._renderTargetTexture.refreshRate;
  101613. },
  101614. set: function (value) {
  101615. this._renderTargetTexture.refreshRate = value;
  101616. },
  101617. enumerable: true,
  101618. configurable: true
  101619. });
  101620. /**
  101621. * Gets the hosting scene
  101622. * @returns a Scene
  101623. */
  101624. ReflectionProbe.prototype.getScene = function () {
  101625. return this._scene;
  101626. };
  101627. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  101628. /** Gets the internal CubeTexture used to render to */
  101629. get: function () {
  101630. return this._renderTargetTexture;
  101631. },
  101632. enumerable: true,
  101633. configurable: true
  101634. });
  101635. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  101636. /** Gets the list of meshes to render */
  101637. get: function () {
  101638. return this._renderTargetTexture.renderList;
  101639. },
  101640. enumerable: true,
  101641. configurable: true
  101642. });
  101643. /**
  101644. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  101645. * @param mesh defines the mesh to attach to
  101646. */
  101647. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  101648. this._attachedMesh = mesh;
  101649. };
  101650. /**
  101651. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  101652. * @param renderingGroupId The rendering group id corresponding to its index
  101653. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  101654. */
  101655. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  101656. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  101657. };
  101658. /**
  101659. * Clean all associated resources
  101660. */
  101661. ReflectionProbe.prototype.dispose = function () {
  101662. var index = this._scene.reflectionProbes.indexOf(this);
  101663. if (index !== -1) {
  101664. // Remove from the scene if found
  101665. this._scene.reflectionProbes.splice(index, 1);
  101666. }
  101667. if (this._renderTargetTexture) {
  101668. this._renderTargetTexture.dispose();
  101669. this._renderTargetTexture = null;
  101670. }
  101671. };
  101672. return ReflectionProbe;
  101673. }());
  101674. BABYLON.ReflectionProbe = ReflectionProbe;
  101675. })(BABYLON || (BABYLON = {}));
  101676. //# sourceMappingURL=babylon.reflectionProbe.js.map
  101677. var BABYLON;
  101678. (function (BABYLON) {
  101679. /**
  101680. * Defines the layer scene component responsible to manage any layers
  101681. * in a given scene.
  101682. */
  101683. var LayerSceneComponent = /** @class */ (function () {
  101684. /**
  101685. * Creates a new instance of the component for the given scene
  101686. * @param scene Defines the scene to register the component in
  101687. */
  101688. function LayerSceneComponent(scene) {
  101689. /**
  101690. * The component name helpfull to identify the component in the list of scene components.
  101691. */
  101692. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  101693. this.scene = scene;
  101694. this._engine = scene.getEngine();
  101695. scene.layers = new Array();
  101696. }
  101697. /**
  101698. * Registers the component in a given scene
  101699. */
  101700. LayerSceneComponent.prototype.register = function () {
  101701. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  101702. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  101703. };
  101704. /**
  101705. * Rebuilds the elements related to this component in case of
  101706. * context lost for instance.
  101707. */
  101708. LayerSceneComponent.prototype.rebuild = function () {
  101709. var layers = this.scene.layers;
  101710. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  101711. var layer = layers_1[_i];
  101712. layer._rebuild();
  101713. }
  101714. };
  101715. /**
  101716. * Disposes the component and the associated ressources.
  101717. */
  101718. LayerSceneComponent.prototype.dispose = function () {
  101719. var layers = this.scene.layers;
  101720. while (layers.length) {
  101721. layers[0].dispose();
  101722. }
  101723. };
  101724. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  101725. var layers = this.scene.layers;
  101726. if (layers.length) {
  101727. this._engine.setDepthBuffer(false);
  101728. var cameraLayerMask = camera.layerMask;
  101729. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  101730. var layer = layers_2[_i];
  101731. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  101732. layer.render();
  101733. }
  101734. }
  101735. this._engine.setDepthBuffer(true);
  101736. }
  101737. };
  101738. LayerSceneComponent.prototype._drawBackground = function (camera) {
  101739. this._draw(camera, true);
  101740. };
  101741. LayerSceneComponent.prototype._drawForeground = function (camera) {
  101742. this._draw(camera, false);
  101743. };
  101744. return LayerSceneComponent;
  101745. }());
  101746. BABYLON.LayerSceneComponent = LayerSceneComponent;
  101747. })(BABYLON || (BABYLON = {}));
  101748. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  101749. var BABYLON;
  101750. (function (BABYLON) {
  101751. var Layer = /** @class */ (function () {
  101752. function Layer(name, imgUrl, scene, isBackground, color) {
  101753. this.name = name;
  101754. this.scale = new BABYLON.Vector2(1, 1);
  101755. this.offset = new BABYLON.Vector2(0, 0);
  101756. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  101757. this.layerMask = 0x0FFFFFFF;
  101758. this._vertexBuffers = {};
  101759. // Events
  101760. /**
  101761. * An event triggered when the layer is disposed.
  101762. */
  101763. this.onDisposeObservable = new BABYLON.Observable();
  101764. /**
  101765. * An event triggered before rendering the scene
  101766. */
  101767. this.onBeforeRenderObservable = new BABYLON.Observable();
  101768. /**
  101769. * An event triggered after rendering the scene
  101770. */
  101771. this.onAfterRenderObservable = new BABYLON.Observable();
  101772. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  101773. this.isBackground = isBackground === undefined ? true : isBackground;
  101774. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  101775. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  101776. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  101777. if (!layerComponent) {
  101778. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  101779. this._scene._addComponent(layerComponent);
  101780. }
  101781. this._scene.layers.push(this);
  101782. var engine = this._scene.getEngine();
  101783. // VBO
  101784. var vertices = [];
  101785. vertices.push(1, 1);
  101786. vertices.push(-1, 1);
  101787. vertices.push(-1, -1);
  101788. vertices.push(1, -1);
  101789. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  101790. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  101791. this._createIndexBuffer();
  101792. // Effects
  101793. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  101794. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  101795. }
  101796. Object.defineProperty(Layer.prototype, "onDispose", {
  101797. set: function (callback) {
  101798. if (this._onDisposeObserver) {
  101799. this.onDisposeObservable.remove(this._onDisposeObserver);
  101800. }
  101801. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  101802. },
  101803. enumerable: true,
  101804. configurable: true
  101805. });
  101806. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  101807. set: function (callback) {
  101808. if (this._onBeforeRenderObserver) {
  101809. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  101810. }
  101811. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  101812. },
  101813. enumerable: true,
  101814. configurable: true
  101815. });
  101816. Object.defineProperty(Layer.prototype, "onAfterRender", {
  101817. set: function (callback) {
  101818. if (this._onAfterRenderObserver) {
  101819. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  101820. }
  101821. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  101822. },
  101823. enumerable: true,
  101824. configurable: true
  101825. });
  101826. Layer.prototype._createIndexBuffer = function () {
  101827. var engine = this._scene.getEngine();
  101828. // Indices
  101829. var indices = [];
  101830. indices.push(0);
  101831. indices.push(1);
  101832. indices.push(2);
  101833. indices.push(0);
  101834. indices.push(2);
  101835. indices.push(3);
  101836. this._indexBuffer = engine.createIndexBuffer(indices);
  101837. };
  101838. /** @hidden */
  101839. Layer.prototype._rebuild = function () {
  101840. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  101841. if (vb) {
  101842. vb._rebuild();
  101843. }
  101844. this._createIndexBuffer();
  101845. };
  101846. Layer.prototype.render = function () {
  101847. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  101848. // Check
  101849. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  101850. return;
  101851. var engine = this._scene.getEngine();
  101852. this.onBeforeRenderObservable.notifyObservers(this);
  101853. // Render
  101854. engine.enableEffect(currentEffect);
  101855. engine.setState(false);
  101856. // Texture
  101857. currentEffect.setTexture("textureSampler", this.texture);
  101858. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  101859. // Color
  101860. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  101861. // Scale / offset
  101862. currentEffect.setVector2("offset", this.offset);
  101863. currentEffect.setVector2("scale", this.scale);
  101864. // VBOs
  101865. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  101866. // Draw order
  101867. if (!this.alphaTest) {
  101868. engine.setAlphaMode(this.alphaBlendingMode);
  101869. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  101870. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  101871. }
  101872. else {
  101873. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  101874. }
  101875. this.onAfterRenderObservable.notifyObservers(this);
  101876. };
  101877. Layer.prototype.dispose = function () {
  101878. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  101879. if (vertexBuffer) {
  101880. vertexBuffer.dispose();
  101881. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  101882. }
  101883. if (this._indexBuffer) {
  101884. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  101885. this._indexBuffer = null;
  101886. }
  101887. if (this.texture) {
  101888. this.texture.dispose();
  101889. this.texture = null;
  101890. }
  101891. // Remove from scene
  101892. var index = this._scene.layers.indexOf(this);
  101893. this._scene.layers.splice(index, 1);
  101894. // Callback
  101895. this.onDisposeObservable.notifyObservers(this);
  101896. this.onDisposeObservable.clear();
  101897. this.onAfterRenderObservable.clear();
  101898. this.onBeforeRenderObservable.clear();
  101899. };
  101900. return Layer;
  101901. }());
  101902. BABYLON.Layer = Layer;
  101903. })(BABYLON || (BABYLON = {}));
  101904. //# sourceMappingURL=babylon.layer.js.map
  101905. var BABYLON;
  101906. (function (BABYLON) {
  101907. var TextureTools = /** @class */ (function () {
  101908. function TextureTools() {
  101909. }
  101910. /**
  101911. * Uses the GPU to create a copy texture rescaled at a given size
  101912. * @param texture Texture to copy from
  101913. * @param width Desired width
  101914. * @param height Desired height
  101915. * @return Generated texture
  101916. */
  101917. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  101918. if (useBilinearMode === void 0) { useBilinearMode = true; }
  101919. var scene = texture.getScene();
  101920. var engine = scene.getEngine();
  101921. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  101922. rtt.wrapU = texture.wrapU;
  101923. rtt.wrapV = texture.wrapV;
  101924. rtt.uOffset = texture.uOffset;
  101925. rtt.vOffset = texture.vOffset;
  101926. rtt.uScale = texture.uScale;
  101927. rtt.vScale = texture.vScale;
  101928. rtt.uAng = texture.uAng;
  101929. rtt.vAng = texture.vAng;
  101930. rtt.wAng = texture.wAng;
  101931. rtt.coordinatesIndex = texture.coordinatesIndex;
  101932. rtt.level = texture.level;
  101933. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  101934. rtt._texture.isReady = false;
  101935. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101936. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101937. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  101938. passPostProcess.getEffect().executeWhenCompiled(function () {
  101939. passPostProcess.onApply = function (effect) {
  101940. effect.setTexture("textureSampler", texture);
  101941. };
  101942. var internalTexture = rtt.getInternalTexture();
  101943. if (internalTexture) {
  101944. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  101945. engine.unBindFramebuffer(internalTexture);
  101946. rtt.disposeFramebufferObjects();
  101947. passPostProcess.dispose();
  101948. internalTexture.isReady = true;
  101949. }
  101950. });
  101951. return rtt;
  101952. };
  101953. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  101954. if (!scene._environmentBRDFTexture) {
  101955. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  101956. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101957. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101958. scene._environmentBRDFTexture = texture;
  101959. }
  101960. return scene._environmentBRDFTexture;
  101961. };
  101962. 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=";
  101963. return TextureTools;
  101964. }());
  101965. BABYLON.TextureTools = TextureTools;
  101966. })(BABYLON || (BABYLON = {}));
  101967. //# sourceMappingURL=babylon.textureTools.js.map
  101968. var BABYLON;
  101969. (function (BABYLON) {
  101970. var FramingBehavior = /** @class */ (function () {
  101971. function FramingBehavior() {
  101972. this._mode = FramingBehavior.FitFrustumSidesMode;
  101973. this._radiusScale = 1.0;
  101974. this._positionScale = 0.5;
  101975. this._defaultElevation = 0.3;
  101976. this._elevationReturnTime = 1500;
  101977. this._elevationReturnWaitTime = 1000;
  101978. this._zoomStopsAnimation = false;
  101979. this._framingTime = 1500;
  101980. this._isPointerDown = false;
  101981. this._lastInteractionTime = -Infinity;
  101982. // Framing control
  101983. this._animatables = new Array();
  101984. this._betaIsAnimating = false;
  101985. }
  101986. Object.defineProperty(FramingBehavior.prototype, "name", {
  101987. get: function () {
  101988. return "Framing";
  101989. },
  101990. enumerable: true,
  101991. configurable: true
  101992. });
  101993. Object.defineProperty(FramingBehavior.prototype, "mode", {
  101994. /**
  101995. * Gets current mode used by the behavior.
  101996. */
  101997. get: function () {
  101998. return this._mode;
  101999. },
  102000. /**
  102001. * Sets the current mode used by the behavior
  102002. */
  102003. set: function (mode) {
  102004. this._mode = mode;
  102005. },
  102006. enumerable: true,
  102007. configurable: true
  102008. });
  102009. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  102010. /**
  102011. * Gets the scale applied to the radius
  102012. */
  102013. get: function () {
  102014. return this._radiusScale;
  102015. },
  102016. /**
  102017. * Sets the scale applied to the radius (1 by default)
  102018. */
  102019. set: function (radius) {
  102020. this._radiusScale = radius;
  102021. },
  102022. enumerable: true,
  102023. configurable: true
  102024. });
  102025. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  102026. /**
  102027. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  102028. */
  102029. get: function () {
  102030. return this._positionScale;
  102031. },
  102032. /**
  102033. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  102034. */
  102035. set: function (scale) {
  102036. this._positionScale = scale;
  102037. },
  102038. enumerable: true,
  102039. configurable: true
  102040. });
  102041. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  102042. /**
  102043. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  102044. * behaviour is triggered, in radians.
  102045. */
  102046. get: function () {
  102047. return this._defaultElevation;
  102048. },
  102049. /**
  102050. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  102051. * behaviour is triggered, in radians.
  102052. */
  102053. set: function (elevation) {
  102054. this._defaultElevation = elevation;
  102055. },
  102056. enumerable: true,
  102057. configurable: true
  102058. });
  102059. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  102060. /**
  102061. * Gets the time (in milliseconds) taken to return to the default beta position.
  102062. * Negative value indicates camera should not return to default.
  102063. */
  102064. get: function () {
  102065. return this._elevationReturnTime;
  102066. },
  102067. /**
  102068. * Sets the time (in milliseconds) taken to return to the default beta position.
  102069. * Negative value indicates camera should not return to default.
  102070. */
  102071. set: function (speed) {
  102072. this._elevationReturnTime = speed;
  102073. },
  102074. enumerable: true,
  102075. configurable: true
  102076. });
  102077. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  102078. /**
  102079. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  102080. */
  102081. get: function () {
  102082. return this._elevationReturnWaitTime;
  102083. },
  102084. /**
  102085. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  102086. */
  102087. set: function (time) {
  102088. this._elevationReturnWaitTime = time;
  102089. },
  102090. enumerable: true,
  102091. configurable: true
  102092. });
  102093. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  102094. /**
  102095. * Gets the flag that indicates if user zooming should stop animation.
  102096. */
  102097. get: function () {
  102098. return this._zoomStopsAnimation;
  102099. },
  102100. /**
  102101. * Sets the flag that indicates if user zooming should stop animation.
  102102. */
  102103. set: function (flag) {
  102104. this._zoomStopsAnimation = flag;
  102105. },
  102106. enumerable: true,
  102107. configurable: true
  102108. });
  102109. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  102110. /**
  102111. * Gets the transition time when framing the mesh, in milliseconds
  102112. */
  102113. get: function () {
  102114. return this._framingTime;
  102115. },
  102116. /**
  102117. * Sets the transition time when framing the mesh, in milliseconds
  102118. */
  102119. set: function (time) {
  102120. this._framingTime = time;
  102121. },
  102122. enumerable: true,
  102123. configurable: true
  102124. });
  102125. FramingBehavior.prototype.init = function () {
  102126. // Do notihng
  102127. };
  102128. FramingBehavior.prototype.attach = function (camera) {
  102129. var _this = this;
  102130. this._attachedCamera = camera;
  102131. var scene = this._attachedCamera.getScene();
  102132. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  102133. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  102134. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  102135. _this._isPointerDown = true;
  102136. return;
  102137. }
  102138. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  102139. _this._isPointerDown = false;
  102140. }
  102141. });
  102142. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  102143. if (mesh) {
  102144. _this.zoomOnMesh(mesh);
  102145. }
  102146. });
  102147. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  102148. // Stop the animation if there is user interaction and the animation should stop for this interaction
  102149. _this._applyUserInteraction();
  102150. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  102151. // back to the default position after a given timeout
  102152. _this._maintainCameraAboveGround();
  102153. });
  102154. };
  102155. FramingBehavior.prototype.detach = function () {
  102156. if (!this._attachedCamera) {
  102157. return;
  102158. }
  102159. var scene = this._attachedCamera.getScene();
  102160. if (this._onPrePointerObservableObserver) {
  102161. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  102162. }
  102163. if (this._onAfterCheckInputsObserver) {
  102164. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  102165. }
  102166. if (this._onMeshTargetChangedObserver) {
  102167. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  102168. }
  102169. this._attachedCamera = null;
  102170. };
  102171. /**
  102172. * Targets the given mesh and updates zoom level accordingly.
  102173. * @param mesh The mesh to target.
  102174. * @param radius Optional. If a cached radius position already exists, overrides default.
  102175. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  102176. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  102177. * @param onAnimationEnd Callback triggered at the end of the framing animation
  102178. */
  102179. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  102180. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  102181. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  102182. mesh.computeWorldMatrix(true);
  102183. var boundingBox = mesh.getBoundingInfo().boundingBox;
  102184. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  102185. };
  102186. /**
  102187. * Targets the given mesh with its children and updates zoom level accordingly.
  102188. * @param mesh The mesh to target.
  102189. * @param radius Optional. If a cached radius position already exists, overrides default.
  102190. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  102191. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  102192. * @param onAnimationEnd Callback triggered at the end of the framing animation
  102193. */
  102194. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  102195. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  102196. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  102197. mesh.computeWorldMatrix(true);
  102198. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  102199. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  102200. };
  102201. /**
  102202. * Targets the given meshes with their children and updates zoom level accordingly.
  102203. * @param meshes The mesh to target.
  102204. * @param radius Optional. If a cached radius position already exists, overrides default.
  102205. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  102206. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  102207. * @param onAnimationEnd Callback triggered at the end of the framing animation
  102208. */
  102209. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  102210. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  102211. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  102212. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  102213. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  102214. for (var i = 0; i < meshes.length; i++) {
  102215. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  102216. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  102217. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  102218. }
  102219. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  102220. };
  102221. /**
  102222. * Targets the given mesh and updates zoom level accordingly.
  102223. * @param mesh The mesh to target.
  102224. * @param radius Optional. If a cached radius position already exists, overrides default.
  102225. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  102226. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  102227. * @param onAnimationEnd Callback triggered at the end of the framing animation
  102228. */
  102229. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  102230. var _this = this;
  102231. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  102232. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  102233. var zoomTarget;
  102234. if (!this._attachedCamera) {
  102235. return;
  102236. }
  102237. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  102238. var bottom = minimumWorld.y;
  102239. var top = maximumWorld.y;
  102240. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  102241. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  102242. if (focusOnOriginXZ) {
  102243. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  102244. }
  102245. else {
  102246. var centerWorld = minimumWorld.add(radiusWorld);
  102247. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  102248. }
  102249. if (!this._vectorTransition) {
  102250. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  102251. }
  102252. this._betaIsAnimating = true;
  102253. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  102254. if (animatable) {
  102255. this._animatables.push(animatable);
  102256. }
  102257. // sets the radius and lower radius bounds
  102258. // Small delta ensures camera is not always at lower zoom limit.
  102259. var radius = 0;
  102260. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  102261. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  102262. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  102263. radius = position;
  102264. }
  102265. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  102266. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  102267. if (this._attachedCamera.lowerRadiusLimit === null) {
  102268. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  102269. }
  102270. }
  102271. // Set sensibilities
  102272. var extend = maximumWorld.subtract(minimumWorld).length();
  102273. this._attachedCamera.panningSensibility = 5000 / extend;
  102274. this._attachedCamera.wheelPrecision = 100 / radius;
  102275. // transition to new radius
  102276. if (!this._radiusTransition) {
  102277. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  102278. }
  102279. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  102280. _this.stopAllAnimations();
  102281. if (onAnimationEnd) {
  102282. onAnimationEnd();
  102283. }
  102284. if (_this._attachedCamera) {
  102285. _this._attachedCamera.storeState();
  102286. }
  102287. });
  102288. if (animatable) {
  102289. this._animatables.push(animatable);
  102290. }
  102291. };
  102292. /**
  102293. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  102294. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  102295. * frustum width.
  102296. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  102297. * to fully enclose the mesh in the viewing frustum.
  102298. */
  102299. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  102300. var size = maximumWorld.subtract(minimumWorld);
  102301. var boxVectorGlobalDiagonal = size.length();
  102302. var frustumSlope = this._getFrustumSlope();
  102303. // Formula for setting distance
  102304. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  102305. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  102306. // Horizon distance
  102307. var radius = radiusWithoutFraming * this._radiusScale;
  102308. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  102309. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  102310. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  102311. var camera = this._attachedCamera;
  102312. if (!camera) {
  102313. return 0;
  102314. }
  102315. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  102316. // Don't exceed the requested limit
  102317. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  102318. }
  102319. // Don't exceed the upper radius limit
  102320. if (camera.upperRadiusLimit) {
  102321. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  102322. }
  102323. return distance;
  102324. };
  102325. /**
  102326. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  102327. * is automatically returned to its default position (expected to be above ground plane).
  102328. */
  102329. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  102330. var _this = this;
  102331. if (this._elevationReturnTime < 0) {
  102332. return;
  102333. }
  102334. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  102335. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  102336. var limitBeta = Math.PI * 0.5;
  102337. // Bring the camera back up if below the ground plane
  102338. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  102339. this._betaIsAnimating = true;
  102340. //Transition to new position
  102341. this.stopAllAnimations();
  102342. if (!this._betaTransition) {
  102343. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  102344. }
  102345. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  102346. _this._clearAnimationLocks();
  102347. _this.stopAllAnimations();
  102348. });
  102349. if (animatabe) {
  102350. this._animatables.push(animatabe);
  102351. }
  102352. }
  102353. };
  102354. /**
  102355. * Returns the frustum slope based on the canvas ratio and camera FOV
  102356. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  102357. */
  102358. FramingBehavior.prototype._getFrustumSlope = function () {
  102359. // Calculate the viewport ratio
  102360. // Aspect Ratio is Height/Width.
  102361. var camera = this._attachedCamera;
  102362. if (!camera) {
  102363. return BABYLON.Vector2.Zero();
  102364. }
  102365. var engine = camera.getScene().getEngine();
  102366. var aspectRatio = engine.getAspectRatio(camera);
  102367. // Camera FOV is the vertical field of view (top-bottom) in radians.
  102368. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  102369. var frustumSlopeY = Math.tan(camera.fov / 2);
  102370. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  102371. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  102372. // along the forward vector.
  102373. var frustumSlopeX = frustumSlopeY * aspectRatio;
  102374. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  102375. };
  102376. /**
  102377. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  102378. */
  102379. FramingBehavior.prototype._clearAnimationLocks = function () {
  102380. this._betaIsAnimating = false;
  102381. };
  102382. /**
  102383. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  102384. */
  102385. FramingBehavior.prototype._applyUserInteraction = function () {
  102386. if (this.isUserIsMoving) {
  102387. this._lastInteractionTime = BABYLON.Tools.Now;
  102388. this.stopAllAnimations();
  102389. this._clearAnimationLocks();
  102390. }
  102391. };
  102392. /**
  102393. * Stops and removes all animations that have been applied to the camera
  102394. */
  102395. FramingBehavior.prototype.stopAllAnimations = function () {
  102396. if (this._attachedCamera) {
  102397. this._attachedCamera.animations = [];
  102398. }
  102399. while (this._animatables.length) {
  102400. if (this._animatables[0]) {
  102401. this._animatables[0].onAnimationEnd = null;
  102402. this._animatables[0].stop();
  102403. }
  102404. this._animatables.shift();
  102405. }
  102406. };
  102407. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  102408. /**
  102409. * Gets a value indicating if the user is moving the camera
  102410. */
  102411. get: function () {
  102412. if (!this._attachedCamera) {
  102413. return false;
  102414. }
  102415. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  102416. this._attachedCamera.inertialBetaOffset !== 0 ||
  102417. this._attachedCamera.inertialRadiusOffset !== 0 ||
  102418. this._attachedCamera.inertialPanningX !== 0 ||
  102419. this._attachedCamera.inertialPanningY !== 0 ||
  102420. this._isPointerDown;
  102421. },
  102422. enumerable: true,
  102423. configurable: true
  102424. });
  102425. /**
  102426. * The easing function used by animations
  102427. */
  102428. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  102429. /**
  102430. * The easing mode used by animations
  102431. */
  102432. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  102433. // Statics
  102434. /**
  102435. * The camera can move all the way towards the mesh.
  102436. */
  102437. FramingBehavior.IgnoreBoundsSizeMode = 0;
  102438. /**
  102439. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  102440. */
  102441. FramingBehavior.FitFrustumSidesMode = 1;
  102442. return FramingBehavior;
  102443. }());
  102444. BABYLON.FramingBehavior = FramingBehavior;
  102445. })(BABYLON || (BABYLON = {}));
  102446. //# sourceMappingURL=babylon.framingBehavior.js.map
  102447. var BABYLON;
  102448. (function (BABYLON) {
  102449. /**
  102450. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  102451. */
  102452. var BouncingBehavior = /** @class */ (function () {
  102453. function BouncingBehavior() {
  102454. /**
  102455. * The duration of the animation, in milliseconds
  102456. */
  102457. this.transitionDuration = 450;
  102458. /**
  102459. * Length of the distance animated by the transition when lower radius is reached
  102460. */
  102461. this.lowerRadiusTransitionRange = 2;
  102462. /**
  102463. * Length of the distance animated by the transition when upper radius is reached
  102464. */
  102465. this.upperRadiusTransitionRange = -2;
  102466. this._autoTransitionRange = false;
  102467. // Animations
  102468. this._radiusIsAnimating = false;
  102469. this._radiusBounceTransition = null;
  102470. this._animatables = new Array();
  102471. }
  102472. Object.defineProperty(BouncingBehavior.prototype, "name", {
  102473. get: function () {
  102474. return "Bouncing";
  102475. },
  102476. enumerable: true,
  102477. configurable: true
  102478. });
  102479. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  102480. /**
  102481. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  102482. */
  102483. get: function () {
  102484. return this._autoTransitionRange;
  102485. },
  102486. /**
  102487. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  102488. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  102489. */
  102490. set: function (value) {
  102491. var _this = this;
  102492. if (this._autoTransitionRange === value) {
  102493. return;
  102494. }
  102495. this._autoTransitionRange = value;
  102496. var camera = this._attachedCamera;
  102497. if (!camera) {
  102498. return;
  102499. }
  102500. if (value) {
  102501. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  102502. if (!mesh) {
  102503. return;
  102504. }
  102505. mesh.computeWorldMatrix(true);
  102506. var diagonal = mesh.getBoundingInfo().diagonalLength;
  102507. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  102508. _this.upperRadiusTransitionRange = diagonal * 0.05;
  102509. });
  102510. }
  102511. else if (this._onMeshTargetChangedObserver) {
  102512. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  102513. }
  102514. },
  102515. enumerable: true,
  102516. configurable: true
  102517. });
  102518. BouncingBehavior.prototype.init = function () {
  102519. // Do notihng
  102520. };
  102521. BouncingBehavior.prototype.attach = function (camera) {
  102522. var _this = this;
  102523. this._attachedCamera = camera;
  102524. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  102525. if (!_this._attachedCamera) {
  102526. return;
  102527. }
  102528. // Add the bounce animation to the lower radius limit
  102529. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  102530. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  102531. }
  102532. // Add the bounce animation to the upper radius limit
  102533. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  102534. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  102535. }
  102536. });
  102537. };
  102538. BouncingBehavior.prototype.detach = function () {
  102539. if (!this._attachedCamera) {
  102540. return;
  102541. }
  102542. if (this._onAfterCheckInputsObserver) {
  102543. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  102544. }
  102545. if (this._onMeshTargetChangedObserver) {
  102546. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  102547. }
  102548. this._attachedCamera = null;
  102549. };
  102550. /**
  102551. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  102552. * @param radiusLimit The limit to check against.
  102553. * @return Bool to indicate if at limit.
  102554. */
  102555. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  102556. if (!this._attachedCamera) {
  102557. return false;
  102558. }
  102559. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  102560. return true;
  102561. }
  102562. return false;
  102563. };
  102564. /**
  102565. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  102566. * @param radiusDelta The delta by which to animate to. Can be negative.
  102567. */
  102568. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  102569. var _this = this;
  102570. if (!this._attachedCamera) {
  102571. return;
  102572. }
  102573. if (!this._radiusBounceTransition) {
  102574. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  102575. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  102576. }
  102577. // Prevent zoom until bounce has completed
  102578. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  102579. this._attachedCamera.wheelPrecision = Infinity;
  102580. this._attachedCamera.inertialRadiusOffset = 0;
  102581. // Animate to the radius limit
  102582. this.stopAllAnimations();
  102583. this._radiusIsAnimating = true;
  102584. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  102585. if (animatable) {
  102586. this._animatables.push(animatable);
  102587. }
  102588. };
  102589. /**
  102590. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  102591. */
  102592. BouncingBehavior.prototype._clearAnimationLocks = function () {
  102593. this._radiusIsAnimating = false;
  102594. if (this._attachedCamera) {
  102595. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  102596. }
  102597. };
  102598. /**
  102599. * Stops and removes all animations that have been applied to the camera
  102600. */
  102601. BouncingBehavior.prototype.stopAllAnimations = function () {
  102602. if (this._attachedCamera) {
  102603. this._attachedCamera.animations = [];
  102604. }
  102605. while (this._animatables.length) {
  102606. this._animatables[0].onAnimationEnd = null;
  102607. this._animatables[0].stop();
  102608. this._animatables.shift();
  102609. }
  102610. };
  102611. /**
  102612. * The easing function used by animations
  102613. */
  102614. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  102615. /**
  102616. * The easing mode used by animations
  102617. */
  102618. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  102619. return BouncingBehavior;
  102620. }());
  102621. BABYLON.BouncingBehavior = BouncingBehavior;
  102622. })(BABYLON || (BABYLON = {}));
  102623. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  102624. var BABYLON;
  102625. (function (BABYLON) {
  102626. var AutoRotationBehavior = /** @class */ (function () {
  102627. function AutoRotationBehavior() {
  102628. this._zoomStopsAnimation = false;
  102629. this._idleRotationSpeed = 0.05;
  102630. this._idleRotationWaitTime = 2000;
  102631. this._idleRotationSpinupTime = 2000;
  102632. this._isPointerDown = false;
  102633. this._lastFrameTime = null;
  102634. this._lastInteractionTime = -Infinity;
  102635. this._cameraRotationSpeed = 0;
  102636. this._lastFrameRadius = 0;
  102637. }
  102638. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  102639. get: function () {
  102640. return "AutoRotation";
  102641. },
  102642. enumerable: true,
  102643. configurable: true
  102644. });
  102645. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  102646. /**
  102647. * Gets the flag that indicates if user zooming should stop animation.
  102648. */
  102649. get: function () {
  102650. return this._zoomStopsAnimation;
  102651. },
  102652. /**
  102653. * Sets the flag that indicates if user zooming should stop animation.
  102654. */
  102655. set: function (flag) {
  102656. this._zoomStopsAnimation = flag;
  102657. },
  102658. enumerable: true,
  102659. configurable: true
  102660. });
  102661. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  102662. /**
  102663. * Gets the default speed at which the camera rotates around the model.
  102664. */
  102665. get: function () {
  102666. return this._idleRotationSpeed;
  102667. },
  102668. /**
  102669. * Sets the default speed at which the camera rotates around the model.
  102670. */
  102671. set: function (speed) {
  102672. this._idleRotationSpeed = speed;
  102673. },
  102674. enumerable: true,
  102675. configurable: true
  102676. });
  102677. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  102678. /**
  102679. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  102680. */
  102681. get: function () {
  102682. return this._idleRotationWaitTime;
  102683. },
  102684. /**
  102685. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  102686. */
  102687. set: function (time) {
  102688. this._idleRotationWaitTime = time;
  102689. },
  102690. enumerable: true,
  102691. configurable: true
  102692. });
  102693. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  102694. /**
  102695. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  102696. */
  102697. get: function () {
  102698. return this._idleRotationSpinupTime;
  102699. },
  102700. /**
  102701. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  102702. */
  102703. set: function (time) {
  102704. this._idleRotationSpinupTime = time;
  102705. },
  102706. enumerable: true,
  102707. configurable: true
  102708. });
  102709. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  102710. /**
  102711. * Gets a value indicating if the camera is currently rotating because of this behavior
  102712. */
  102713. get: function () {
  102714. return Math.abs(this._cameraRotationSpeed) > 0;
  102715. },
  102716. enumerable: true,
  102717. configurable: true
  102718. });
  102719. AutoRotationBehavior.prototype.init = function () {
  102720. // Do notihng
  102721. };
  102722. AutoRotationBehavior.prototype.attach = function (camera) {
  102723. var _this = this;
  102724. this._attachedCamera = camera;
  102725. var scene = this._attachedCamera.getScene();
  102726. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  102727. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  102728. _this._isPointerDown = true;
  102729. return;
  102730. }
  102731. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  102732. _this._isPointerDown = false;
  102733. }
  102734. });
  102735. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  102736. var now = BABYLON.Tools.Now;
  102737. var dt = 0;
  102738. if (_this._lastFrameTime != null) {
  102739. dt = now - _this._lastFrameTime;
  102740. }
  102741. _this._lastFrameTime = now;
  102742. // Stop the animation if there is user interaction and the animation should stop for this interaction
  102743. _this._applyUserInteraction();
  102744. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  102745. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  102746. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  102747. // Step camera rotation by rotation speed
  102748. if (_this._attachedCamera) {
  102749. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  102750. }
  102751. });
  102752. };
  102753. AutoRotationBehavior.prototype.detach = function () {
  102754. if (!this._attachedCamera) {
  102755. return;
  102756. }
  102757. var scene = this._attachedCamera.getScene();
  102758. if (this._onPrePointerObservableObserver) {
  102759. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  102760. }
  102761. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  102762. this._attachedCamera = null;
  102763. };
  102764. /**
  102765. * Returns true if user is scrolling.
  102766. * @return true if user is scrolling.
  102767. */
  102768. AutoRotationBehavior.prototype._userIsZooming = function () {
  102769. if (!this._attachedCamera) {
  102770. return false;
  102771. }
  102772. return this._attachedCamera.inertialRadiusOffset !== 0;
  102773. };
  102774. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  102775. if (!this._attachedCamera) {
  102776. return false;
  102777. }
  102778. var zoomHasHitLimit = false;
  102779. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  102780. zoomHasHitLimit = true;
  102781. }
  102782. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  102783. this._lastFrameRadius = this._attachedCamera.radius;
  102784. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  102785. };
  102786. /**
  102787. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  102788. */
  102789. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  102790. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  102791. this._lastInteractionTime = BABYLON.Tools.Now;
  102792. }
  102793. };
  102794. // Tools
  102795. AutoRotationBehavior.prototype._userIsMoving = function () {
  102796. if (!this._attachedCamera) {
  102797. return false;
  102798. }
  102799. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  102800. this._attachedCamera.inertialBetaOffset !== 0 ||
  102801. this._attachedCamera.inertialRadiusOffset !== 0 ||
  102802. this._attachedCamera.inertialPanningX !== 0 ||
  102803. this._attachedCamera.inertialPanningY !== 0 ||
  102804. this._isPointerDown;
  102805. };
  102806. return AutoRotationBehavior;
  102807. }());
  102808. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  102809. })(BABYLON || (BABYLON = {}));
  102810. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  102811. var BABYLON;
  102812. (function (BABYLON) {
  102813. var NullEngineOptions = /** @class */ (function () {
  102814. function NullEngineOptions() {
  102815. this.renderWidth = 512;
  102816. this.renderHeight = 256;
  102817. this.textureSize = 512;
  102818. this.deterministicLockstep = false;
  102819. this.lockstepMaxSteps = 4;
  102820. }
  102821. return NullEngineOptions;
  102822. }());
  102823. BABYLON.NullEngineOptions = NullEngineOptions;
  102824. /**
  102825. * The null engine class provides support for headless version of babylon.js.
  102826. * This can be used in server side scenario or for testing purposes
  102827. */
  102828. var NullEngine = /** @class */ (function (_super) {
  102829. __extends(NullEngine, _super);
  102830. function NullEngine(options) {
  102831. if (options === void 0) { options = new NullEngineOptions(); }
  102832. var _this = _super.call(this, null) || this;
  102833. if (options.deterministicLockstep === undefined) {
  102834. options.deterministicLockstep = false;
  102835. }
  102836. if (options.lockstepMaxSteps === undefined) {
  102837. options.lockstepMaxSteps = 4;
  102838. }
  102839. _this._options = options;
  102840. // Init caps
  102841. // We consider we are on a webgl1 capable device
  102842. _this._caps = new BABYLON.EngineCapabilities();
  102843. _this._caps.maxTexturesImageUnits = 16;
  102844. _this._caps.maxVertexTextureImageUnits = 16;
  102845. _this._caps.maxTextureSize = 512;
  102846. _this._caps.maxCubemapTextureSize = 512;
  102847. _this._caps.maxRenderTextureSize = 512;
  102848. _this._caps.maxVertexAttribs = 16;
  102849. _this._caps.maxVaryingVectors = 16;
  102850. _this._caps.maxFragmentUniformVectors = 16;
  102851. _this._caps.maxVertexUniformVectors = 16;
  102852. // Extensions
  102853. _this._caps.standardDerivatives = false;
  102854. _this._caps.astc = null;
  102855. _this._caps.s3tc = null;
  102856. _this._caps.pvrtc = null;
  102857. _this._caps.etc1 = null;
  102858. _this._caps.etc2 = null;
  102859. _this._caps.textureAnisotropicFilterExtension = null;
  102860. _this._caps.maxAnisotropy = 0;
  102861. _this._caps.uintIndices = false;
  102862. _this._caps.fragmentDepthSupported = false;
  102863. _this._caps.highPrecisionShaderSupported = true;
  102864. _this._caps.colorBufferFloat = false;
  102865. _this._caps.textureFloat = false;
  102866. _this._caps.textureFloatLinearFiltering = false;
  102867. _this._caps.textureFloatRender = false;
  102868. _this._caps.textureHalfFloat = false;
  102869. _this._caps.textureHalfFloatLinearFiltering = false;
  102870. _this._caps.textureHalfFloatRender = false;
  102871. _this._caps.textureLOD = false;
  102872. _this._caps.drawBuffersExtension = false;
  102873. _this._caps.depthTextureExtension = false;
  102874. _this._caps.vertexArrayObject = false;
  102875. _this._caps.instancedArrays = false;
  102876. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  102877. // Wrappers
  102878. if (typeof URL === "undefined") {
  102879. URL = {
  102880. createObjectURL: function () { },
  102881. revokeObjectURL: function () { }
  102882. };
  102883. }
  102884. if (typeof Blob === "undefined") {
  102885. Blob = function () { };
  102886. }
  102887. return _this;
  102888. }
  102889. NullEngine.prototype.isDeterministicLockStep = function () {
  102890. return this._options.deterministicLockstep;
  102891. };
  102892. NullEngine.prototype.getLockstepMaxSteps = function () {
  102893. return this._options.lockstepMaxSteps;
  102894. };
  102895. NullEngine.prototype.getHardwareScalingLevel = function () {
  102896. return 1.0;
  102897. };
  102898. NullEngine.prototype.createVertexBuffer = function (vertices) {
  102899. return {
  102900. capacity: 0,
  102901. references: 1,
  102902. is32Bits: false
  102903. };
  102904. };
  102905. NullEngine.prototype.createIndexBuffer = function (indices) {
  102906. return {
  102907. capacity: 0,
  102908. references: 1,
  102909. is32Bits: false
  102910. };
  102911. };
  102912. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  102913. if (stencil === void 0) { stencil = false; }
  102914. };
  102915. NullEngine.prototype.getRenderWidth = function (useScreen) {
  102916. if (useScreen === void 0) { useScreen = false; }
  102917. if (!useScreen && this._currentRenderTarget) {
  102918. return this._currentRenderTarget.width;
  102919. }
  102920. return this._options.renderWidth;
  102921. };
  102922. NullEngine.prototype.getRenderHeight = function (useScreen) {
  102923. if (useScreen === void 0) { useScreen = false; }
  102924. if (!useScreen && this._currentRenderTarget) {
  102925. return this._currentRenderTarget.height;
  102926. }
  102927. return this._options.renderHeight;
  102928. };
  102929. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  102930. this._cachedViewport = viewport;
  102931. };
  102932. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  102933. return {
  102934. transformFeedback: null,
  102935. __SPECTOR_rebuildProgram: null
  102936. };
  102937. };
  102938. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  102939. return [];
  102940. };
  102941. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  102942. return [];
  102943. };
  102944. NullEngine.prototype.bindSamplers = function (effect) {
  102945. this._currentEffect = null;
  102946. };
  102947. NullEngine.prototype.enableEffect = function (effect) {
  102948. this._currentEffect = effect;
  102949. if (effect.onBind) {
  102950. effect.onBind(effect);
  102951. }
  102952. if (effect._onBindObservable) {
  102953. effect._onBindObservable.notifyObservers(effect);
  102954. }
  102955. };
  102956. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  102957. if (zOffset === void 0) { zOffset = 0; }
  102958. if (reverseSide === void 0) { reverseSide = false; }
  102959. };
  102960. NullEngine.prototype.setIntArray = function (uniform, array) {
  102961. };
  102962. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  102963. };
  102964. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  102965. };
  102966. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  102967. };
  102968. NullEngine.prototype.setFloatArray = function (uniform, array) {
  102969. };
  102970. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  102971. };
  102972. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  102973. };
  102974. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  102975. };
  102976. NullEngine.prototype.setArray = function (uniform, array) {
  102977. };
  102978. NullEngine.prototype.setArray2 = function (uniform, array) {
  102979. };
  102980. NullEngine.prototype.setArray3 = function (uniform, array) {
  102981. };
  102982. NullEngine.prototype.setArray4 = function (uniform, array) {
  102983. };
  102984. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  102985. };
  102986. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  102987. };
  102988. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  102989. };
  102990. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  102991. };
  102992. NullEngine.prototype.setFloat = function (uniform, value) {
  102993. };
  102994. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  102995. };
  102996. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  102997. };
  102998. NullEngine.prototype.setBool = function (uniform, bool) {
  102999. };
  103000. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  103001. };
  103002. NullEngine.prototype.setColor3 = function (uniform, color3) {
  103003. };
  103004. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  103005. };
  103006. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  103007. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  103008. if (this._alphaMode === mode) {
  103009. return;
  103010. }
  103011. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  103012. if (!noDepthWriteChange) {
  103013. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  103014. }
  103015. this._alphaMode = mode;
  103016. };
  103017. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  103018. };
  103019. NullEngine.prototype.wipeCaches = function (bruteForce) {
  103020. if (this.preventCacheWipeBetweenFrames) {
  103021. return;
  103022. }
  103023. this.resetTextureCache();
  103024. this._currentEffect = null;
  103025. if (bruteForce) {
  103026. this._currentProgram = null;
  103027. this._stencilState.reset();
  103028. this._depthCullingState.reset();
  103029. this._alphaState.reset();
  103030. }
  103031. this._cachedVertexBuffers = null;
  103032. this._cachedIndexBuffer = null;
  103033. this._cachedEffectForVertexBuffers = null;
  103034. };
  103035. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  103036. };
  103037. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  103038. };
  103039. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  103040. };
  103041. /** @hidden */
  103042. NullEngine.prototype._createTexture = function () {
  103043. return {};
  103044. };
  103045. /** @hidden */
  103046. NullEngine.prototype._releaseTexture = function (texture) {
  103047. };
  103048. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  103049. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  103050. if (onLoad === void 0) { onLoad = null; }
  103051. if (onError === void 0) { onError = null; }
  103052. if (buffer === void 0) { buffer = null; }
  103053. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  103054. var url = String(urlArg);
  103055. texture.url = url;
  103056. texture.generateMipMaps = !noMipmap;
  103057. texture.samplingMode = samplingMode;
  103058. texture.invertY = invertY;
  103059. texture.baseWidth = this._options.textureSize;
  103060. texture.baseHeight = this._options.textureSize;
  103061. texture.width = this._options.textureSize;
  103062. texture.height = this._options.textureSize;
  103063. if (format) {
  103064. texture.format = format;
  103065. }
  103066. texture.isReady = true;
  103067. if (onLoad) {
  103068. onLoad();
  103069. }
  103070. this._internalTexturesCache.push(texture);
  103071. return texture;
  103072. };
  103073. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  103074. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  103075. if (options !== undefined && typeof options === "object") {
  103076. fullOptions.generateMipMaps = options.generateMipMaps;
  103077. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  103078. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  103079. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  103080. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  103081. }
  103082. else {
  103083. fullOptions.generateMipMaps = options;
  103084. fullOptions.generateDepthBuffer = true;
  103085. fullOptions.generateStencilBuffer = false;
  103086. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  103087. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  103088. }
  103089. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  103090. var width = size.width || size;
  103091. var height = size.height || size;
  103092. texture._depthStencilBuffer = {};
  103093. texture._framebuffer = {};
  103094. texture.baseWidth = width;
  103095. texture.baseHeight = height;
  103096. texture.width = width;
  103097. texture.height = height;
  103098. texture.isReady = true;
  103099. texture.samples = 1;
  103100. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  103101. texture.samplingMode = fullOptions.samplingMode;
  103102. texture.type = fullOptions.type;
  103103. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  103104. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  103105. this._internalTexturesCache.push(texture);
  103106. return texture;
  103107. };
  103108. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  103109. texture.samplingMode = samplingMode;
  103110. };
  103111. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  103112. if (this._currentRenderTarget) {
  103113. this.unBindFramebuffer(this._currentRenderTarget);
  103114. }
  103115. this._currentRenderTarget = texture;
  103116. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  103117. if (this._cachedViewport && !forceFullscreenViewport) {
  103118. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  103119. }
  103120. };
  103121. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  103122. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  103123. this._currentRenderTarget = null;
  103124. if (onBeforeUnbind) {
  103125. if (texture._MSAAFramebuffer) {
  103126. this._currentFramebuffer = texture._framebuffer;
  103127. }
  103128. onBeforeUnbind();
  103129. }
  103130. this._currentFramebuffer = null;
  103131. };
  103132. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  103133. var vbo = {
  103134. capacity: 1,
  103135. references: 1,
  103136. is32Bits: false
  103137. };
  103138. return vbo;
  103139. };
  103140. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  103141. if (premulAlpha === void 0) { premulAlpha = false; }
  103142. };
  103143. /**
  103144. * @hidden
  103145. * Get the current error code of the webGL context
  103146. * @returns the error code
  103147. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  103148. */
  103149. NullEngine.prototype.getError = function () {
  103150. return 0;
  103151. };
  103152. /** @hidden */
  103153. NullEngine.prototype._getUnpackAlignement = function () {
  103154. return 1;
  103155. };
  103156. /** @hidden */
  103157. NullEngine.prototype._unpackFlipY = function (value) {
  103158. };
  103159. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  103160. if (offset === void 0) { offset = 0; }
  103161. };
  103162. /**
  103163. * Updates a dynamic vertex buffer.
  103164. * @param vertexBuffer the vertex buffer to update
  103165. * @param data the data used to update the vertex buffer
  103166. * @param byteOffset the byte offset of the data (optional)
  103167. * @param byteLength the byte length of the data (optional)
  103168. */
  103169. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  103170. };
  103171. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  103172. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  103173. this._boundTexturesCache[this._activeChannel] = texture;
  103174. return true;
  103175. }
  103176. return false;
  103177. };
  103178. /** @hidden */
  103179. NullEngine.prototype._bindTexture = function (channel, texture) {
  103180. if (channel < 0) {
  103181. return;
  103182. }
  103183. this._bindTextureDirectly(0, texture);
  103184. };
  103185. /** @hidden */
  103186. NullEngine.prototype._releaseBuffer = function (buffer) {
  103187. buffer.references--;
  103188. if (buffer.references === 0) {
  103189. return true;
  103190. }
  103191. return false;
  103192. };
  103193. NullEngine.prototype.releaseEffects = function () {
  103194. };
  103195. NullEngine.prototype.displayLoadingUI = function () {
  103196. };
  103197. NullEngine.prototype.hideLoadingUI = function () {
  103198. };
  103199. /** @hidden */
  103200. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  103201. if (faceIndex === void 0) { faceIndex = 0; }
  103202. if (lod === void 0) { lod = 0; }
  103203. };
  103204. /** @hidden */
  103205. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  103206. if (faceIndex === void 0) { faceIndex = 0; }
  103207. if (lod === void 0) { lod = 0; }
  103208. };
  103209. /** @hidden */
  103210. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  103211. if (faceIndex === void 0) { faceIndex = 0; }
  103212. if (lod === void 0) { lod = 0; }
  103213. };
  103214. /** @hidden */
  103215. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  103216. if (faceIndex === void 0) { faceIndex = 0; }
  103217. if (lod === void 0) { lod = 0; }
  103218. };
  103219. return NullEngine;
  103220. }(BABYLON.Engine));
  103221. BABYLON.NullEngine = NullEngine;
  103222. })(BABYLON || (BABYLON = {}));
  103223. //# sourceMappingURL=babylon.nullEngine.js.map
  103224. var BABYLON;
  103225. (function (BABYLON) {
  103226. /**
  103227. * This class can be used to get instrumentation data from a Babylon engine
  103228. */
  103229. var EngineInstrumentation = /** @class */ (function () {
  103230. function EngineInstrumentation(engine) {
  103231. this.engine = engine;
  103232. this._captureGPUFrameTime = false;
  103233. this._gpuFrameTime = new BABYLON.PerfCounter();
  103234. this._captureShaderCompilationTime = false;
  103235. this._shaderCompilationTime = new BABYLON.PerfCounter();
  103236. // Observers
  103237. this._onBeginFrameObserver = null;
  103238. this._onEndFrameObserver = null;
  103239. this._onBeforeShaderCompilationObserver = null;
  103240. this._onAfterShaderCompilationObserver = null;
  103241. }
  103242. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  103243. // Properties
  103244. /**
  103245. * Gets the perf counter used for GPU frame time
  103246. */
  103247. get: function () {
  103248. return this._gpuFrameTime;
  103249. },
  103250. enumerable: true,
  103251. configurable: true
  103252. });
  103253. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  103254. /**
  103255. * Gets the GPU frame time capture status
  103256. */
  103257. get: function () {
  103258. return this._captureGPUFrameTime;
  103259. },
  103260. /**
  103261. * Enable or disable the GPU frame time capture
  103262. */
  103263. set: function (value) {
  103264. var _this = this;
  103265. if (value === this._captureGPUFrameTime) {
  103266. return;
  103267. }
  103268. this._captureGPUFrameTime = value;
  103269. if (value) {
  103270. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  103271. if (!_this._gpuFrameTimeToken) {
  103272. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  103273. }
  103274. });
  103275. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  103276. if (!_this._gpuFrameTimeToken) {
  103277. return;
  103278. }
  103279. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  103280. if (time > -1) {
  103281. _this._gpuFrameTimeToken = null;
  103282. _this._gpuFrameTime.fetchNewFrame();
  103283. _this._gpuFrameTime.addCount(time, true);
  103284. }
  103285. });
  103286. }
  103287. else {
  103288. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  103289. this._onBeginFrameObserver = null;
  103290. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  103291. this._onEndFrameObserver = null;
  103292. }
  103293. },
  103294. enumerable: true,
  103295. configurable: true
  103296. });
  103297. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  103298. /**
  103299. * Gets the perf counter used for shader compilation time
  103300. */
  103301. get: function () {
  103302. return this._shaderCompilationTime;
  103303. },
  103304. enumerable: true,
  103305. configurable: true
  103306. });
  103307. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  103308. /**
  103309. * Gets the shader compilation time capture status
  103310. */
  103311. get: function () {
  103312. return this._captureShaderCompilationTime;
  103313. },
  103314. /**
  103315. * Enable or disable the shader compilation time capture
  103316. */
  103317. set: function (value) {
  103318. var _this = this;
  103319. if (value === this._captureShaderCompilationTime) {
  103320. return;
  103321. }
  103322. this._captureShaderCompilationTime = value;
  103323. if (value) {
  103324. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  103325. _this._shaderCompilationTime.fetchNewFrame();
  103326. _this._shaderCompilationTime.beginMonitoring();
  103327. });
  103328. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  103329. _this._shaderCompilationTime.endMonitoring();
  103330. });
  103331. }
  103332. else {
  103333. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  103334. this._onBeforeShaderCompilationObserver = null;
  103335. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  103336. this._onAfterShaderCompilationObserver = null;
  103337. }
  103338. },
  103339. enumerable: true,
  103340. configurable: true
  103341. });
  103342. EngineInstrumentation.prototype.dispose = function () {
  103343. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  103344. this._onBeginFrameObserver = null;
  103345. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  103346. this._onEndFrameObserver = null;
  103347. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  103348. this._onBeforeShaderCompilationObserver = null;
  103349. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  103350. this._onAfterShaderCompilationObserver = null;
  103351. this.engine = null;
  103352. };
  103353. return EngineInstrumentation;
  103354. }());
  103355. BABYLON.EngineInstrumentation = EngineInstrumentation;
  103356. })(BABYLON || (BABYLON = {}));
  103357. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  103358. var BABYLON;
  103359. (function (BABYLON) {
  103360. /**
  103361. * This class can be used to get instrumentation data from a Babylon engine
  103362. */
  103363. var SceneInstrumentation = /** @class */ (function () {
  103364. function SceneInstrumentation(scene) {
  103365. var _this = this;
  103366. this.scene = scene;
  103367. this._captureActiveMeshesEvaluationTime = false;
  103368. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  103369. this._captureRenderTargetsRenderTime = false;
  103370. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  103371. this._captureFrameTime = false;
  103372. this._frameTime = new BABYLON.PerfCounter();
  103373. this._captureRenderTime = false;
  103374. this._renderTime = new BABYLON.PerfCounter();
  103375. this._captureInterFrameTime = false;
  103376. this._interFrameTime = new BABYLON.PerfCounter();
  103377. this._captureParticlesRenderTime = false;
  103378. this._particlesRenderTime = new BABYLON.PerfCounter();
  103379. this._captureSpritesRenderTime = false;
  103380. this._spritesRenderTime = new BABYLON.PerfCounter();
  103381. this._capturePhysicsTime = false;
  103382. this._physicsTime = new BABYLON.PerfCounter();
  103383. this._captureAnimationsTime = false;
  103384. this._animationsTime = new BABYLON.PerfCounter();
  103385. this._captureCameraRenderTime = false;
  103386. this._cameraRenderTime = new BABYLON.PerfCounter();
  103387. // Observers
  103388. this._onBeforeActiveMeshesEvaluationObserver = null;
  103389. this._onAfterActiveMeshesEvaluationObserver = null;
  103390. this._onBeforeRenderTargetsRenderObserver = null;
  103391. this._onAfterRenderTargetsRenderObserver = null;
  103392. this._onAfterRenderObserver = null;
  103393. this._onBeforeDrawPhaseObserver = null;
  103394. this._onAfterDrawPhaseObserver = null;
  103395. this._onBeforeAnimationsObserver = null;
  103396. this._onBeforeParticlesRenderingObserver = null;
  103397. this._onAfterParticlesRenderingObserver = null;
  103398. this._onBeforeSpritesRenderingObserver = null;
  103399. this._onAfterSpritesRenderingObserver = null;
  103400. this._onBeforePhysicsObserver = null;
  103401. this._onAfterPhysicsObserver = null;
  103402. this._onAfterAnimationsObserver = null;
  103403. this._onBeforeCameraRenderObserver = null;
  103404. this._onAfterCameraRenderObserver = null;
  103405. // Before render
  103406. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  103407. if (_this._captureActiveMeshesEvaluationTime) {
  103408. _this._activeMeshesEvaluationTime.fetchNewFrame();
  103409. }
  103410. if (_this._captureRenderTargetsRenderTime) {
  103411. _this._renderTargetsRenderTime.fetchNewFrame();
  103412. }
  103413. if (_this._captureFrameTime) {
  103414. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  103415. _this._frameTime.beginMonitoring();
  103416. }
  103417. if (_this._captureInterFrameTime) {
  103418. _this._interFrameTime.endMonitoring();
  103419. }
  103420. if (_this._captureParticlesRenderTime) {
  103421. _this._particlesRenderTime.fetchNewFrame();
  103422. }
  103423. if (_this._captureSpritesRenderTime) {
  103424. _this._spritesRenderTime.fetchNewFrame();
  103425. }
  103426. if (_this._captureAnimationsTime) {
  103427. _this._animationsTime.beginMonitoring();
  103428. }
  103429. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  103430. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  103431. });
  103432. // After render
  103433. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  103434. if (_this._captureFrameTime) {
  103435. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  103436. _this._frameTime.endMonitoring();
  103437. }
  103438. if (_this._captureRenderTime) {
  103439. _this._renderTime.endMonitoring(false);
  103440. }
  103441. if (_this._captureInterFrameTime) {
  103442. _this._interFrameTime.beginMonitoring();
  103443. }
  103444. });
  103445. }
  103446. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  103447. // Properties
  103448. /**
  103449. * Gets the perf counter used for active meshes evaluation time
  103450. */
  103451. get: function () {
  103452. return this._activeMeshesEvaluationTime;
  103453. },
  103454. enumerable: true,
  103455. configurable: true
  103456. });
  103457. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  103458. /**
  103459. * Gets the active meshes evaluation time capture status
  103460. */
  103461. get: function () {
  103462. return this._captureActiveMeshesEvaluationTime;
  103463. },
  103464. /**
  103465. * Enable or disable the active meshes evaluation time capture
  103466. */
  103467. set: function (value) {
  103468. var _this = this;
  103469. if (value === this._captureActiveMeshesEvaluationTime) {
  103470. return;
  103471. }
  103472. this._captureActiveMeshesEvaluationTime = value;
  103473. if (value) {
  103474. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  103475. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  103476. _this._activeMeshesEvaluationTime.beginMonitoring();
  103477. });
  103478. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  103479. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  103480. _this._activeMeshesEvaluationTime.endMonitoring();
  103481. });
  103482. }
  103483. else {
  103484. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  103485. this._onBeforeActiveMeshesEvaluationObserver = null;
  103486. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  103487. this._onAfterActiveMeshesEvaluationObserver = null;
  103488. }
  103489. },
  103490. enumerable: true,
  103491. configurable: true
  103492. });
  103493. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  103494. /**
  103495. * Gets the perf counter used for render targets render time
  103496. */
  103497. get: function () {
  103498. return this._renderTargetsRenderTime;
  103499. },
  103500. enumerable: true,
  103501. configurable: true
  103502. });
  103503. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  103504. /**
  103505. * Gets the render targets render time capture status
  103506. */
  103507. get: function () {
  103508. return this._captureRenderTargetsRenderTime;
  103509. },
  103510. /**
  103511. * Enable or disable the render targets render time capture
  103512. */
  103513. set: function (value) {
  103514. var _this = this;
  103515. if (value === this._captureRenderTargetsRenderTime) {
  103516. return;
  103517. }
  103518. this._captureRenderTargetsRenderTime = value;
  103519. if (value) {
  103520. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  103521. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  103522. _this._renderTargetsRenderTime.beginMonitoring();
  103523. });
  103524. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  103525. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  103526. _this._renderTargetsRenderTime.endMonitoring(false);
  103527. });
  103528. }
  103529. else {
  103530. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  103531. this._onBeforeRenderTargetsRenderObserver = null;
  103532. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  103533. this._onAfterRenderTargetsRenderObserver = null;
  103534. }
  103535. },
  103536. enumerable: true,
  103537. configurable: true
  103538. });
  103539. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  103540. /**
  103541. * Gets the perf counter used for particles render time
  103542. */
  103543. get: function () {
  103544. return this._particlesRenderTime;
  103545. },
  103546. enumerable: true,
  103547. configurable: true
  103548. });
  103549. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  103550. /**
  103551. * Gets the particles render time capture status
  103552. */
  103553. get: function () {
  103554. return this._captureParticlesRenderTime;
  103555. },
  103556. /**
  103557. * Enable or disable the particles render time capture
  103558. */
  103559. set: function (value) {
  103560. var _this = this;
  103561. if (value === this._captureParticlesRenderTime) {
  103562. return;
  103563. }
  103564. this._captureParticlesRenderTime = value;
  103565. if (value) {
  103566. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  103567. BABYLON.Tools.StartPerformanceCounter("Particles");
  103568. _this._particlesRenderTime.beginMonitoring();
  103569. });
  103570. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  103571. BABYLON.Tools.EndPerformanceCounter("Particles");
  103572. _this._particlesRenderTime.endMonitoring(false);
  103573. });
  103574. }
  103575. else {
  103576. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  103577. this._onBeforeParticlesRenderingObserver = null;
  103578. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  103579. this._onAfterParticlesRenderingObserver = null;
  103580. }
  103581. },
  103582. enumerable: true,
  103583. configurable: true
  103584. });
  103585. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  103586. /**
  103587. * Gets the perf counter used for sprites render time
  103588. */
  103589. get: function () {
  103590. return this._spritesRenderTime;
  103591. },
  103592. enumerable: true,
  103593. configurable: true
  103594. });
  103595. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  103596. /**
  103597. * Gets the sprites render time capture status
  103598. */
  103599. get: function () {
  103600. return this._captureSpritesRenderTime;
  103601. },
  103602. /**
  103603. * Enable or disable the sprites render time capture
  103604. */
  103605. set: function (value) {
  103606. var _this = this;
  103607. if (value === this._captureSpritesRenderTime) {
  103608. return;
  103609. }
  103610. this._captureSpritesRenderTime = value;
  103611. if (value) {
  103612. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  103613. BABYLON.Tools.StartPerformanceCounter("Sprites");
  103614. _this._spritesRenderTime.beginMonitoring();
  103615. });
  103616. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  103617. BABYLON.Tools.EndPerformanceCounter("Sprites");
  103618. _this._spritesRenderTime.endMonitoring(false);
  103619. });
  103620. }
  103621. else {
  103622. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  103623. this._onBeforeSpritesRenderingObserver = null;
  103624. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  103625. this._onAfterSpritesRenderingObserver = null;
  103626. }
  103627. },
  103628. enumerable: true,
  103629. configurable: true
  103630. });
  103631. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  103632. /**
  103633. * Gets the perf counter used for physics time
  103634. */
  103635. get: function () {
  103636. return this._physicsTime;
  103637. },
  103638. enumerable: true,
  103639. configurable: true
  103640. });
  103641. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  103642. /**
  103643. * Gets the physics time capture status
  103644. */
  103645. get: function () {
  103646. return this._capturePhysicsTime;
  103647. },
  103648. /**
  103649. * Enable or disable the physics time capture
  103650. */
  103651. set: function (value) {
  103652. var _this = this;
  103653. if (value === this._capturePhysicsTime) {
  103654. return;
  103655. }
  103656. this._capturePhysicsTime = value;
  103657. if (value) {
  103658. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  103659. BABYLON.Tools.StartPerformanceCounter("Physics");
  103660. _this._physicsTime.beginMonitoring();
  103661. });
  103662. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  103663. BABYLON.Tools.EndPerformanceCounter("Physics");
  103664. _this._physicsTime.endMonitoring();
  103665. });
  103666. }
  103667. else {
  103668. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  103669. this._onBeforePhysicsObserver = null;
  103670. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  103671. this._onAfterPhysicsObserver = null;
  103672. }
  103673. },
  103674. enumerable: true,
  103675. configurable: true
  103676. });
  103677. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  103678. /**
  103679. * Gets the perf counter used for animations time
  103680. */
  103681. get: function () {
  103682. return this._animationsTime;
  103683. },
  103684. enumerable: true,
  103685. configurable: true
  103686. });
  103687. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  103688. /**
  103689. * Gets the animations time capture status
  103690. */
  103691. get: function () {
  103692. return this._captureAnimationsTime;
  103693. },
  103694. /**
  103695. * Enable or disable the animations time capture
  103696. */
  103697. set: function (value) {
  103698. var _this = this;
  103699. if (value === this._captureAnimationsTime) {
  103700. return;
  103701. }
  103702. this._captureAnimationsTime = value;
  103703. if (value) {
  103704. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  103705. _this._animationsTime.endMonitoring();
  103706. });
  103707. }
  103708. else {
  103709. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  103710. this._onAfterAnimationsObserver = null;
  103711. }
  103712. },
  103713. enumerable: true,
  103714. configurable: true
  103715. });
  103716. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  103717. /**
  103718. * Gets the perf counter used for frame time capture
  103719. */
  103720. get: function () {
  103721. return this._frameTime;
  103722. },
  103723. enumerable: true,
  103724. configurable: true
  103725. });
  103726. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  103727. /**
  103728. * Gets the frame time capture status
  103729. */
  103730. get: function () {
  103731. return this._captureFrameTime;
  103732. },
  103733. /**
  103734. * Enable or disable the frame time capture
  103735. */
  103736. set: function (value) {
  103737. this._captureFrameTime = value;
  103738. },
  103739. enumerable: true,
  103740. configurable: true
  103741. });
  103742. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  103743. /**
  103744. * Gets the perf counter used for inter-frames time capture
  103745. */
  103746. get: function () {
  103747. return this._interFrameTime;
  103748. },
  103749. enumerable: true,
  103750. configurable: true
  103751. });
  103752. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  103753. /**
  103754. * Gets the inter-frames time capture status
  103755. */
  103756. get: function () {
  103757. return this._captureInterFrameTime;
  103758. },
  103759. /**
  103760. * Enable or disable the inter-frames time capture
  103761. */
  103762. set: function (value) {
  103763. this._captureInterFrameTime = value;
  103764. },
  103765. enumerable: true,
  103766. configurable: true
  103767. });
  103768. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  103769. /**
  103770. * Gets the perf counter used for render time capture
  103771. */
  103772. get: function () {
  103773. return this._renderTime;
  103774. },
  103775. enumerable: true,
  103776. configurable: true
  103777. });
  103778. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  103779. /**
  103780. * Gets the render time capture status
  103781. */
  103782. get: function () {
  103783. return this._captureRenderTime;
  103784. },
  103785. /**
  103786. * Enable or disable the render time capture
  103787. */
  103788. set: function (value) {
  103789. var _this = this;
  103790. if (value === this._captureRenderTime) {
  103791. return;
  103792. }
  103793. this._captureRenderTime = value;
  103794. if (value) {
  103795. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  103796. _this._renderTime.beginMonitoring();
  103797. BABYLON.Tools.StartPerformanceCounter("Main render");
  103798. });
  103799. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  103800. _this._renderTime.endMonitoring(false);
  103801. BABYLON.Tools.EndPerformanceCounter("Main render");
  103802. });
  103803. }
  103804. else {
  103805. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  103806. this._onBeforeDrawPhaseObserver = null;
  103807. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  103808. this._onAfterDrawPhaseObserver = null;
  103809. }
  103810. },
  103811. enumerable: true,
  103812. configurable: true
  103813. });
  103814. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  103815. /**
  103816. * Gets the perf counter used for camera render time capture
  103817. */
  103818. get: function () {
  103819. return this._cameraRenderTime;
  103820. },
  103821. enumerable: true,
  103822. configurable: true
  103823. });
  103824. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  103825. /**
  103826. * Gets the camera render time capture status
  103827. */
  103828. get: function () {
  103829. return this._captureCameraRenderTime;
  103830. },
  103831. /**
  103832. * Enable or disable the camera render time capture
  103833. */
  103834. set: function (value) {
  103835. var _this = this;
  103836. if (value === this._captureCameraRenderTime) {
  103837. return;
  103838. }
  103839. this._captureCameraRenderTime = value;
  103840. if (value) {
  103841. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  103842. _this._cameraRenderTime.beginMonitoring();
  103843. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  103844. });
  103845. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  103846. _this._cameraRenderTime.endMonitoring(false);
  103847. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  103848. });
  103849. }
  103850. else {
  103851. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  103852. this._onBeforeCameraRenderObserver = null;
  103853. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  103854. this._onAfterCameraRenderObserver = null;
  103855. }
  103856. },
  103857. enumerable: true,
  103858. configurable: true
  103859. });
  103860. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  103861. /**
  103862. * Gets the perf counter used for draw calls
  103863. */
  103864. get: function () {
  103865. return this.scene.getEngine()._drawCalls;
  103866. },
  103867. enumerable: true,
  103868. configurable: true
  103869. });
  103870. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  103871. /**
  103872. * Gets the perf counter used for texture collisions
  103873. */
  103874. get: function () {
  103875. return this.scene.getEngine()._textureCollisions;
  103876. },
  103877. enumerable: true,
  103878. configurable: true
  103879. });
  103880. SceneInstrumentation.prototype.dispose = function () {
  103881. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  103882. this._onAfterRenderObserver = null;
  103883. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  103884. this._onBeforeActiveMeshesEvaluationObserver = null;
  103885. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  103886. this._onAfterActiveMeshesEvaluationObserver = null;
  103887. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  103888. this._onBeforeRenderTargetsRenderObserver = null;
  103889. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  103890. this._onAfterRenderTargetsRenderObserver = null;
  103891. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  103892. this._onBeforeAnimationsObserver = null;
  103893. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  103894. this._onBeforeParticlesRenderingObserver = null;
  103895. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  103896. this._onAfterParticlesRenderingObserver = null;
  103897. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  103898. this._onBeforeSpritesRenderingObserver = null;
  103899. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  103900. this._onAfterSpritesRenderingObserver = null;
  103901. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  103902. this._onBeforeDrawPhaseObserver = null;
  103903. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  103904. this._onAfterDrawPhaseObserver = null;
  103905. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  103906. this._onBeforePhysicsObserver = null;
  103907. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  103908. this._onAfterPhysicsObserver = null;
  103909. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  103910. this._onAfterAnimationsObserver = null;
  103911. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  103912. this._onBeforeCameraRenderObserver = null;
  103913. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  103914. this._onAfterCameraRenderObserver = null;
  103915. this.scene = null;
  103916. };
  103917. return SceneInstrumentation;
  103918. }());
  103919. BABYLON.SceneInstrumentation = SceneInstrumentation;
  103920. })(BABYLON || (BABYLON = {}));
  103921. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  103922. var BABYLON;
  103923. (function (BABYLON) {
  103924. /**
  103925. * @hidden
  103926. **/
  103927. var _TimeToken = /** @class */ (function () {
  103928. function _TimeToken() {
  103929. this._timeElapsedQueryEnded = false;
  103930. }
  103931. return _TimeToken;
  103932. }());
  103933. BABYLON._TimeToken = _TimeToken;
  103934. })(BABYLON || (BABYLON = {}));
  103935. //# sourceMappingURL=babylon.timeToken.js.map
  103936. var BABYLON;
  103937. (function (BABYLON) {
  103938. /**
  103939. * Background material defines definition.
  103940. * @hidden Mainly internal Use
  103941. */
  103942. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  103943. __extends(BackgroundMaterialDefines, _super);
  103944. /**
  103945. * Constructor of the defines.
  103946. */
  103947. function BackgroundMaterialDefines() {
  103948. var _this = _super.call(this) || this;
  103949. /**
  103950. * True if the diffuse texture is in use.
  103951. */
  103952. _this.DIFFUSE = false;
  103953. /**
  103954. * The direct UV channel to use.
  103955. */
  103956. _this.DIFFUSEDIRECTUV = 0;
  103957. /**
  103958. * True if the diffuse texture is in gamma space.
  103959. */
  103960. _this.GAMMADIFFUSE = false;
  103961. /**
  103962. * True if the diffuse texture has opacity in the alpha channel.
  103963. */
  103964. _this.DIFFUSEHASALPHA = false;
  103965. /**
  103966. * True if you want the material to fade to transparent at grazing angle.
  103967. */
  103968. _this.OPACITYFRESNEL = false;
  103969. /**
  103970. * True if an extra blur needs to be added in the reflection.
  103971. */
  103972. _this.REFLECTIONBLUR = false;
  103973. /**
  103974. * True if you want the material to fade to reflection at grazing angle.
  103975. */
  103976. _this.REFLECTIONFRESNEL = false;
  103977. /**
  103978. * True if you want the material to falloff as far as you move away from the scene center.
  103979. */
  103980. _this.REFLECTIONFALLOFF = false;
  103981. /**
  103982. * False if the current Webgl implementation does not support the texture lod extension.
  103983. */
  103984. _this.TEXTURELODSUPPORT = false;
  103985. /**
  103986. * True to ensure the data are premultiplied.
  103987. */
  103988. _this.PREMULTIPLYALPHA = false;
  103989. /**
  103990. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  103991. */
  103992. _this.USERGBCOLOR = false;
  103993. /**
  103994. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  103995. * stays aligned with the desired configuration.
  103996. */
  103997. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  103998. /**
  103999. * True to add noise in order to reduce the banding effect.
  104000. */
  104001. _this.NOISE = false;
  104002. /**
  104003. * is the reflection texture in BGR color scheme?
  104004. * Mainly used to solve a bug in ios10 video tag
  104005. */
  104006. _this.REFLECTIONBGR = false;
  104007. _this.IMAGEPROCESSING = false;
  104008. _this.VIGNETTE = false;
  104009. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  104010. _this.VIGNETTEBLENDMODEOPAQUE = false;
  104011. _this.TONEMAPPING = false;
  104012. _this.TONEMAPPING_ACES = false;
  104013. _this.CONTRAST = false;
  104014. _this.COLORCURVES = false;
  104015. _this.COLORGRADING = false;
  104016. _this.COLORGRADING3D = false;
  104017. _this.SAMPLER3DGREENDEPTH = false;
  104018. _this.SAMPLER3DBGRMAP = false;
  104019. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  104020. _this.EXPOSURE = false;
  104021. // Reflection.
  104022. _this.REFLECTION = false;
  104023. _this.REFLECTIONMAP_3D = false;
  104024. _this.REFLECTIONMAP_SPHERICAL = false;
  104025. _this.REFLECTIONMAP_PLANAR = false;
  104026. _this.REFLECTIONMAP_CUBIC = false;
  104027. _this.REFLECTIONMAP_PROJECTION = false;
  104028. _this.REFLECTIONMAP_SKYBOX = false;
  104029. _this.REFLECTIONMAP_EXPLICIT = false;
  104030. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  104031. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  104032. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  104033. _this.INVERTCUBICMAP = false;
  104034. _this.REFLECTIONMAP_OPPOSITEZ = false;
  104035. _this.LODINREFLECTIONALPHA = false;
  104036. _this.GAMMAREFLECTION = false;
  104037. _this.RGBDREFLECTION = false;
  104038. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  104039. // Default BJS.
  104040. _this.MAINUV1 = false;
  104041. _this.MAINUV2 = false;
  104042. _this.UV1 = false;
  104043. _this.UV2 = false;
  104044. _this.CLIPPLANE = false;
  104045. _this.CLIPPLANE2 = false;
  104046. _this.CLIPPLANE3 = false;
  104047. _this.CLIPPLANE4 = false;
  104048. _this.POINTSIZE = false;
  104049. _this.FOG = false;
  104050. _this.NORMAL = false;
  104051. _this.NUM_BONE_INFLUENCERS = 0;
  104052. _this.BonesPerMesh = 0;
  104053. _this.INSTANCES = false;
  104054. _this.SHADOWFLOAT = false;
  104055. _this.rebuild();
  104056. return _this;
  104057. }
  104058. return BackgroundMaterialDefines;
  104059. }(BABYLON.MaterialDefines));
  104060. /**
  104061. * Background material used to create an efficient environement around your scene.
  104062. */
  104063. var BackgroundMaterial = /** @class */ (function (_super) {
  104064. __extends(BackgroundMaterial, _super);
  104065. /**
  104066. * Instantiates a Background Material in the given scene
  104067. * @param name The friendly name of the material
  104068. * @param scene The scene to add the material to
  104069. */
  104070. function BackgroundMaterial(name, scene) {
  104071. var _this = _super.call(this, name, scene) || this;
  104072. /**
  104073. * Key light Color (multiply against the environement texture)
  104074. */
  104075. _this.primaryColor = BABYLON.Color3.White();
  104076. _this._primaryColorShadowLevel = 0;
  104077. _this._primaryColorHighlightLevel = 0;
  104078. /**
  104079. * Reflection Texture used in the material.
  104080. * Should be author in a specific way for the best result (refer to the documentation).
  104081. */
  104082. _this.reflectionTexture = null;
  104083. /**
  104084. * Reflection Texture level of blur.
  104085. *
  104086. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  104087. * texture twice.
  104088. */
  104089. _this.reflectionBlur = 0;
  104090. /**
  104091. * Diffuse Texture used in the material.
  104092. * Should be author in a specific way for the best result (refer to the documentation).
  104093. */
  104094. _this.diffuseTexture = null;
  104095. _this._shadowLights = null;
  104096. /**
  104097. * Specify the list of lights casting shadow on the material.
  104098. * All scene shadow lights will be included if null.
  104099. */
  104100. _this.shadowLights = null;
  104101. /**
  104102. * Helps adjusting the shadow to a softer level if required.
  104103. * 0 means black shadows and 1 means no shadows.
  104104. */
  104105. _this.shadowLevel = 0;
  104106. /**
  104107. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  104108. * It is usually zero but might be interesting to modify according to your setup.
  104109. */
  104110. _this.sceneCenter = BABYLON.Vector3.Zero();
  104111. /**
  104112. * This helps specifying that the material is falling off to the sky box at grazing angle.
  104113. * This helps ensuring a nice transition when the camera goes under the ground.
  104114. */
  104115. _this.opacityFresnel = true;
  104116. /**
  104117. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  104118. * This helps adding a mirror texture on the ground.
  104119. */
  104120. _this.reflectionFresnel = false;
  104121. /**
  104122. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  104123. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  104124. */
  104125. _this.reflectionFalloffDistance = 0.0;
  104126. /**
  104127. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  104128. */
  104129. _this.reflectionAmount = 1.0;
  104130. /**
  104131. * This specifies the weight of the reflection at grazing angle.
  104132. */
  104133. _this.reflectionReflectance0 = 0.05;
  104134. /**
  104135. * This specifies the weight of the reflection at a perpendicular point of view.
  104136. */
  104137. _this.reflectionReflectance90 = 0.5;
  104138. /**
  104139. * Helps to directly use the maps channels instead of their level.
  104140. */
  104141. _this.useRGBColor = true;
  104142. /**
  104143. * This helps reducing the banding effect that could occur on the background.
  104144. */
  104145. _this.enableNoise = false;
  104146. _this._fovMultiplier = 1.0;
  104147. /**
  104148. * Enable the FOV adjustment feature controlled by fovMultiplier.
  104149. */
  104150. _this.useEquirectangularFOV = false;
  104151. _this._maxSimultaneousLights = 4;
  104152. /**
  104153. * Number of Simultaneous lights allowed on the material.
  104154. */
  104155. _this.maxSimultaneousLights = 4;
  104156. /**
  104157. * Keep track of the image processing observer to allow dispose and replace.
  104158. */
  104159. _this._imageProcessingObserver = null;
  104160. /**
  104161. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  104162. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  104163. */
  104164. _this.switchToBGR = false;
  104165. // Temp values kept as cache in the material.
  104166. _this._renderTargets = new BABYLON.SmartArray(16);
  104167. _this._reflectionControls = BABYLON.Vector4.Zero();
  104168. _this._white = BABYLON.Color3.White();
  104169. _this._primaryShadowColor = BABYLON.Color3.Black();
  104170. _this._primaryHighlightColor = BABYLON.Color3.Black();
  104171. // Setup the default processing configuration to the scene.
  104172. _this._attachImageProcessingConfiguration(null);
  104173. _this.getRenderTargetTextures = function () {
  104174. _this._renderTargets.reset();
  104175. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  104176. _this._renderTargets.push(_this._diffuseTexture);
  104177. }
  104178. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  104179. _this._renderTargets.push(_this._reflectionTexture);
  104180. }
  104181. return _this._renderTargets;
  104182. };
  104183. return _this;
  104184. }
  104185. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  104186. /**
  104187. * Experimental Internal Use Only.
  104188. *
  104189. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  104190. * This acts as a helper to set the primary color to a more "human friendly" value.
  104191. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  104192. * output color as close as possible from the chosen value.
  104193. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  104194. * part of lighting setup.)
  104195. */
  104196. get: function () {
  104197. return this.__perceptualColor;
  104198. },
  104199. set: function (value) {
  104200. this.__perceptualColor = value;
  104201. this._computePrimaryColorFromPerceptualColor();
  104202. this._markAllSubMeshesAsLightsDirty();
  104203. },
  104204. enumerable: true,
  104205. configurable: true
  104206. });
  104207. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  104208. /**
  104209. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  104210. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  104211. */
  104212. get: function () {
  104213. return this._primaryColorShadowLevel;
  104214. },
  104215. set: function (value) {
  104216. this._primaryColorShadowLevel = value;
  104217. this._computePrimaryColors();
  104218. this._markAllSubMeshesAsLightsDirty();
  104219. },
  104220. enumerable: true,
  104221. configurable: true
  104222. });
  104223. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  104224. /**
  104225. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  104226. * The primary color is used at the level chosen to define what the white area would look.
  104227. */
  104228. get: function () {
  104229. return this._primaryColorHighlightLevel;
  104230. },
  104231. set: function (value) {
  104232. this._primaryColorHighlightLevel = value;
  104233. this._computePrimaryColors();
  104234. this._markAllSubMeshesAsLightsDirty();
  104235. },
  104236. enumerable: true,
  104237. configurable: true
  104238. });
  104239. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  104240. /**
  104241. * Sets the reflection reflectance fresnel values according to the default standard
  104242. * empirically know to work well :-)
  104243. */
  104244. set: function (value) {
  104245. var reflectionWeight = value;
  104246. if (reflectionWeight < 0.5) {
  104247. reflectionWeight = reflectionWeight * 2.0;
  104248. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  104249. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  104250. }
  104251. else {
  104252. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  104253. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  104254. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  104255. }
  104256. },
  104257. enumerable: true,
  104258. configurable: true
  104259. });
  104260. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  104261. /**
  104262. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  104263. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  104264. * Recommended to be keep at 1.0 except for special cases.
  104265. */
  104266. get: function () {
  104267. return this._fovMultiplier;
  104268. },
  104269. set: function (value) {
  104270. if (isNaN(value)) {
  104271. value = 1.0;
  104272. }
  104273. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  104274. },
  104275. enumerable: true,
  104276. configurable: true
  104277. });
  104278. /**
  104279. * Attaches a new image processing configuration to the PBR Material.
  104280. * @param configuration (if null the scene configuration will be use)
  104281. */
  104282. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  104283. var _this = this;
  104284. if (configuration === this._imageProcessingConfiguration) {
  104285. return;
  104286. }
  104287. // Detaches observer.
  104288. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  104289. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  104290. }
  104291. // Pick the scene configuration if needed.
  104292. if (!configuration) {
  104293. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  104294. }
  104295. else {
  104296. this._imageProcessingConfiguration = configuration;
  104297. }
  104298. // Attaches observer.
  104299. if (this._imageProcessingConfiguration) {
  104300. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  104301. _this._computePrimaryColorFromPerceptualColor();
  104302. _this._markAllSubMeshesAsImageProcessingDirty();
  104303. });
  104304. }
  104305. };
  104306. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  104307. /**
  104308. * Gets the image processing configuration used either in this material.
  104309. */
  104310. get: function () {
  104311. return this._imageProcessingConfiguration;
  104312. },
  104313. /**
  104314. * Sets the Default image processing configuration used either in the this material.
  104315. *
  104316. * If sets to null, the scene one is in use.
  104317. */
  104318. set: function (value) {
  104319. this._attachImageProcessingConfiguration(value);
  104320. // Ensure the effect will be rebuilt.
  104321. this._markAllSubMeshesAsTexturesDirty();
  104322. },
  104323. enumerable: true,
  104324. configurable: true
  104325. });
  104326. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  104327. /**
  104328. * Gets wether the color curves effect is enabled.
  104329. */
  104330. get: function () {
  104331. return this.imageProcessingConfiguration.colorCurvesEnabled;
  104332. },
  104333. /**
  104334. * Sets wether the color curves effect is enabled.
  104335. */
  104336. set: function (value) {
  104337. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  104338. },
  104339. enumerable: true,
  104340. configurable: true
  104341. });
  104342. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  104343. /**
  104344. * Gets wether the color grading effect is enabled.
  104345. */
  104346. get: function () {
  104347. return this.imageProcessingConfiguration.colorGradingEnabled;
  104348. },
  104349. /**
  104350. * Gets wether the color grading effect is enabled.
  104351. */
  104352. set: function (value) {
  104353. this.imageProcessingConfiguration.colorGradingEnabled = value;
  104354. },
  104355. enumerable: true,
  104356. configurable: true
  104357. });
  104358. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  104359. /**
  104360. * Gets wether tonemapping is enabled or not.
  104361. */
  104362. get: function () {
  104363. return this._imageProcessingConfiguration.toneMappingEnabled;
  104364. },
  104365. /**
  104366. * Sets wether tonemapping is enabled or not
  104367. */
  104368. set: function (value) {
  104369. this._imageProcessingConfiguration.toneMappingEnabled = value;
  104370. },
  104371. enumerable: true,
  104372. configurable: true
  104373. });
  104374. ;
  104375. ;
  104376. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  104377. /**
  104378. * The camera exposure used on this material.
  104379. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  104380. * This corresponds to a photographic exposure.
  104381. */
  104382. get: function () {
  104383. return this._imageProcessingConfiguration.exposure;
  104384. },
  104385. /**
  104386. * The camera exposure used on this material.
  104387. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  104388. * This corresponds to a photographic exposure.
  104389. */
  104390. set: function (value) {
  104391. this._imageProcessingConfiguration.exposure = value;
  104392. },
  104393. enumerable: true,
  104394. configurable: true
  104395. });
  104396. ;
  104397. ;
  104398. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  104399. /**
  104400. * Gets The camera contrast used on this material.
  104401. */
  104402. get: function () {
  104403. return this._imageProcessingConfiguration.contrast;
  104404. },
  104405. /**
  104406. * Sets The camera contrast used on this material.
  104407. */
  104408. set: function (value) {
  104409. this._imageProcessingConfiguration.contrast = value;
  104410. },
  104411. enumerable: true,
  104412. configurable: true
  104413. });
  104414. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  104415. /**
  104416. * Gets the Color Grading 2D Lookup Texture.
  104417. */
  104418. get: function () {
  104419. return this._imageProcessingConfiguration.colorGradingTexture;
  104420. },
  104421. /**
  104422. * Sets the Color Grading 2D Lookup Texture.
  104423. */
  104424. set: function (value) {
  104425. this.imageProcessingConfiguration.colorGradingTexture = value;
  104426. },
  104427. enumerable: true,
  104428. configurable: true
  104429. });
  104430. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  104431. /**
  104432. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  104433. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  104434. * 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;
  104435. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  104436. */
  104437. get: function () {
  104438. return this.imageProcessingConfiguration.colorCurves;
  104439. },
  104440. /**
  104441. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  104442. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  104443. * 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;
  104444. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  104445. */
  104446. set: function (value) {
  104447. this.imageProcessingConfiguration.colorCurves = value;
  104448. },
  104449. enumerable: true,
  104450. configurable: true
  104451. });
  104452. /**
  104453. * The entire material has been created in order to prevent overdraw.
  104454. * @returns false
  104455. */
  104456. BackgroundMaterial.prototype.needAlphaTesting = function () {
  104457. return true;
  104458. };
  104459. /**
  104460. * The entire material has been created in order to prevent overdraw.
  104461. * @returns true if blending is enable
  104462. */
  104463. BackgroundMaterial.prototype.needAlphaBlending = function () {
  104464. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  104465. };
  104466. /**
  104467. * Checks wether the material is ready to be rendered for a given mesh.
  104468. * @param mesh The mesh to render
  104469. * @param subMesh The submesh to check against
  104470. * @param useInstances Specify wether or not the material is used with instances
  104471. * @returns true if all the dependencies are ready (Textures, Effects...)
  104472. */
  104473. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  104474. var _this = this;
  104475. if (useInstances === void 0) { useInstances = false; }
  104476. if (subMesh.effect && this.isFrozen) {
  104477. if (this._wasPreviouslyReady) {
  104478. return true;
  104479. }
  104480. }
  104481. if (!subMesh._materialDefines) {
  104482. subMesh._materialDefines = new BackgroundMaterialDefines();
  104483. }
  104484. var scene = this.getScene();
  104485. var defines = subMesh._materialDefines;
  104486. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  104487. if (defines._renderId === scene.getRenderId()) {
  104488. return true;
  104489. }
  104490. }
  104491. var engine = scene.getEngine();
  104492. // Lights
  104493. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  104494. defines._needNormals = true;
  104495. // Textures
  104496. if (defines._areTexturesDirty) {
  104497. defines._needUVs = false;
  104498. if (scene.texturesEnabled) {
  104499. if (scene.getEngine().getCaps().textureLOD) {
  104500. defines.TEXTURELODSUPPORT = true;
  104501. }
  104502. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  104503. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  104504. return false;
  104505. }
  104506. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  104507. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  104508. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  104509. defines.OPACITYFRESNEL = this._opacityFresnel;
  104510. }
  104511. else {
  104512. defines.DIFFUSE = false;
  104513. defines.DIFFUSEHASALPHA = false;
  104514. defines.GAMMADIFFUSE = false;
  104515. defines.OPACITYFRESNEL = false;
  104516. }
  104517. var reflectionTexture = this._reflectionTexture;
  104518. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  104519. if (!reflectionTexture.isReadyOrNotBlocking()) {
  104520. return false;
  104521. }
  104522. defines.REFLECTION = true;
  104523. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  104524. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  104525. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  104526. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  104527. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  104528. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  104529. defines.REFLECTIONBGR = this.switchToBGR;
  104530. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  104531. defines.INVERTCUBICMAP = true;
  104532. }
  104533. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  104534. switch (reflectionTexture.coordinatesMode) {
  104535. case BABYLON.Texture.EXPLICIT_MODE:
  104536. defines.REFLECTIONMAP_EXPLICIT = true;
  104537. break;
  104538. case BABYLON.Texture.PLANAR_MODE:
  104539. defines.REFLECTIONMAP_PLANAR = true;
  104540. break;
  104541. case BABYLON.Texture.PROJECTION_MODE:
  104542. defines.REFLECTIONMAP_PROJECTION = true;
  104543. break;
  104544. case BABYLON.Texture.SKYBOX_MODE:
  104545. defines.REFLECTIONMAP_SKYBOX = true;
  104546. break;
  104547. case BABYLON.Texture.SPHERICAL_MODE:
  104548. defines.REFLECTIONMAP_SPHERICAL = true;
  104549. break;
  104550. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  104551. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  104552. break;
  104553. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  104554. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  104555. break;
  104556. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  104557. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  104558. break;
  104559. case BABYLON.Texture.CUBIC_MODE:
  104560. case BABYLON.Texture.INVCUBIC_MODE:
  104561. default:
  104562. defines.REFLECTIONMAP_CUBIC = true;
  104563. break;
  104564. }
  104565. if (this.reflectionFresnel) {
  104566. defines.REFLECTIONFRESNEL = true;
  104567. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  104568. this._reflectionControls.x = this.reflectionAmount;
  104569. this._reflectionControls.y = this.reflectionReflectance0;
  104570. this._reflectionControls.z = this.reflectionReflectance90;
  104571. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  104572. }
  104573. else {
  104574. defines.REFLECTIONFRESNEL = false;
  104575. defines.REFLECTIONFALLOFF = false;
  104576. }
  104577. }
  104578. else {
  104579. defines.REFLECTION = false;
  104580. defines.REFLECTIONFRESNEL = false;
  104581. defines.REFLECTIONFALLOFF = false;
  104582. defines.REFLECTIONBLUR = false;
  104583. defines.REFLECTIONMAP_3D = false;
  104584. defines.REFLECTIONMAP_SPHERICAL = false;
  104585. defines.REFLECTIONMAP_PLANAR = false;
  104586. defines.REFLECTIONMAP_CUBIC = false;
  104587. defines.REFLECTIONMAP_PROJECTION = false;
  104588. defines.REFLECTIONMAP_SKYBOX = false;
  104589. defines.REFLECTIONMAP_EXPLICIT = false;
  104590. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  104591. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  104592. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  104593. defines.INVERTCUBICMAP = false;
  104594. defines.REFLECTIONMAP_OPPOSITEZ = false;
  104595. defines.LODINREFLECTIONALPHA = false;
  104596. defines.GAMMAREFLECTION = false;
  104597. defines.RGBDREFLECTION = false;
  104598. }
  104599. }
  104600. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  104601. defines.USERGBCOLOR = this._useRGBColor;
  104602. defines.NOISE = this._enableNoise;
  104603. }
  104604. if (defines._areLightsDirty) {
  104605. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  104606. }
  104607. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  104608. if (!this._imageProcessingConfiguration.isReady()) {
  104609. return false;
  104610. }
  104611. this._imageProcessingConfiguration.prepareDefines(defines);
  104612. }
  104613. // Misc.
  104614. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  104615. // Values that need to be evaluated on every frame
  104616. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  104617. // Attribs
  104618. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  104619. if (mesh) {
  104620. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  104621. mesh.createNormals(true);
  104622. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  104623. }
  104624. }
  104625. }
  104626. // Get correct effect
  104627. if (defines.isDirty) {
  104628. defines.markAsProcessed();
  104629. scene.resetCachedMaterial();
  104630. // Fallbacks
  104631. var fallbacks = new BABYLON.EffectFallbacks();
  104632. if (defines.FOG) {
  104633. fallbacks.addFallback(0, "FOG");
  104634. }
  104635. if (defines.POINTSIZE) {
  104636. fallbacks.addFallback(1, "POINTSIZE");
  104637. }
  104638. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  104639. if (defines.NUM_BONE_INFLUENCERS > 0) {
  104640. fallbacks.addCPUSkinningFallback(0, mesh);
  104641. }
  104642. //Attributes
  104643. var attribs = [BABYLON.VertexBuffer.PositionKind];
  104644. if (defines.NORMAL) {
  104645. attribs.push(BABYLON.VertexBuffer.NormalKind);
  104646. }
  104647. if (defines.UV1) {
  104648. attribs.push(BABYLON.VertexBuffer.UVKind);
  104649. }
  104650. if (defines.UV2) {
  104651. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  104652. }
  104653. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  104654. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  104655. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  104656. "vFogInfos", "vFogColor", "pointSize",
  104657. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  104658. "vPrimaryColor", "vPrimaryColorShadow",
  104659. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  104660. "shadowLevel", "alpha",
  104661. "vBackgroundCenter", "vReflectionControl",
  104662. "vDiffuseInfos", "diffuseMatrix",
  104663. ];
  104664. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  104665. var uniformBuffers = ["Material", "Scene"];
  104666. if (BABYLON.ImageProcessingConfiguration) {
  104667. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  104668. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  104669. }
  104670. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  104671. uniformsNames: uniforms,
  104672. uniformBuffersNames: uniformBuffers,
  104673. samplers: samplers,
  104674. defines: defines,
  104675. maxSimultaneousLights: this._maxSimultaneousLights
  104676. });
  104677. var onCompiled = function (effect) {
  104678. if (_this.onCompiled) {
  104679. _this.onCompiled(effect);
  104680. }
  104681. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  104682. };
  104683. var join = defines.toString();
  104684. subMesh.setEffect(scene.getEngine().createEffect("background", {
  104685. attributes: attribs,
  104686. uniformsNames: uniforms,
  104687. uniformBuffersNames: uniformBuffers,
  104688. samplers: samplers,
  104689. defines: join,
  104690. fallbacks: fallbacks,
  104691. onCompiled: onCompiled,
  104692. onError: this.onError,
  104693. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  104694. }, engine), defines);
  104695. this.buildUniformLayout();
  104696. }
  104697. if (!subMesh.effect || !subMesh.effect.isReady()) {
  104698. return false;
  104699. }
  104700. defines._renderId = scene.getRenderId();
  104701. this._wasPreviouslyReady = true;
  104702. return true;
  104703. };
  104704. /**
  104705. * Compute the primary color according to the chosen perceptual color.
  104706. */
  104707. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  104708. if (!this.__perceptualColor) {
  104709. return;
  104710. }
  104711. this._primaryColor.copyFrom(this.__perceptualColor);
  104712. // Revert gamma space.
  104713. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  104714. // Revert image processing configuration.
  104715. if (this._imageProcessingConfiguration) {
  104716. // Revert Exposure.
  104717. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  104718. }
  104719. this._computePrimaryColors();
  104720. };
  104721. /**
  104722. * Compute the highlights and shadow colors according to their chosen levels.
  104723. */
  104724. BackgroundMaterial.prototype._computePrimaryColors = function () {
  104725. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  104726. return;
  104727. }
  104728. // Find the highlight color based on the configuration.
  104729. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  104730. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  104731. // Find the shadow color based on the configuration.
  104732. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  104733. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  104734. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  104735. };
  104736. /**
  104737. * Build the uniform buffer used in the material.
  104738. */
  104739. BackgroundMaterial.prototype.buildUniformLayout = function () {
  104740. // Order is important !
  104741. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  104742. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  104743. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  104744. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  104745. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  104746. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  104747. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  104748. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  104749. this._uniformBuffer.addUniform("pointSize", 1);
  104750. this._uniformBuffer.addUniform("shadowLevel", 1);
  104751. this._uniformBuffer.addUniform("alpha", 1);
  104752. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  104753. this._uniformBuffer.addUniform("vReflectionControl", 4);
  104754. this._uniformBuffer.create();
  104755. };
  104756. /**
  104757. * Unbind the material.
  104758. */
  104759. BackgroundMaterial.prototype.unbind = function () {
  104760. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  104761. this._uniformBuffer.setTexture("diffuseSampler", null);
  104762. }
  104763. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  104764. this._uniformBuffer.setTexture("reflectionSampler", null);
  104765. }
  104766. _super.prototype.unbind.call(this);
  104767. };
  104768. /**
  104769. * Bind only the world matrix to the material.
  104770. * @param world The world matrix to bind.
  104771. */
  104772. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  104773. this._activeEffect.setMatrix("world", world);
  104774. };
  104775. /**
  104776. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  104777. * @param world The world matrix to bind.
  104778. * @param subMesh The submesh to bind for.
  104779. */
  104780. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  104781. var scene = this.getScene();
  104782. var defines = subMesh._materialDefines;
  104783. if (!defines) {
  104784. return;
  104785. }
  104786. var effect = subMesh.effect;
  104787. if (!effect) {
  104788. return;
  104789. }
  104790. this._activeEffect = effect;
  104791. // Matrices
  104792. this.bindOnlyWorldMatrix(world);
  104793. // Bones
  104794. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  104795. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  104796. if (mustRebind) {
  104797. this._uniformBuffer.bindToEffect(effect, "Material");
  104798. this.bindViewProjection(effect);
  104799. var reflectionTexture = this._reflectionTexture;
  104800. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  104801. // Texture uniforms
  104802. if (scene.texturesEnabled) {
  104803. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  104804. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  104805. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  104806. }
  104807. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  104808. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  104809. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  104810. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  104811. }
  104812. }
  104813. if (this.shadowLevel > 0) {
  104814. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  104815. }
  104816. this._uniformBuffer.updateFloat("alpha", this.alpha);
  104817. // Point size
  104818. if (this.pointsCloud) {
  104819. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  104820. }
  104821. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  104822. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  104823. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  104824. }
  104825. else {
  104826. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  104827. }
  104828. }
  104829. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  104830. // Textures
  104831. if (scene.texturesEnabled) {
  104832. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  104833. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  104834. }
  104835. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  104836. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  104837. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  104838. }
  104839. else if (!defines.REFLECTIONBLUR) {
  104840. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  104841. }
  104842. else {
  104843. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  104844. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  104845. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  104846. }
  104847. if (defines.REFLECTIONFRESNEL) {
  104848. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  104849. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  104850. }
  104851. }
  104852. }
  104853. // Clip plane
  104854. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  104855. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  104856. }
  104857. if (mustRebind || !this.isFrozen) {
  104858. if (scene.lightsEnabled) {
  104859. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  104860. }
  104861. // View
  104862. this.bindView(effect);
  104863. // Fog
  104864. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  104865. // image processing
  104866. if (this._imageProcessingConfiguration) {
  104867. this._imageProcessingConfiguration.bind(this._activeEffect);
  104868. }
  104869. }
  104870. this._uniformBuffer.update();
  104871. this._afterBind(mesh, this._activeEffect);
  104872. };
  104873. /**
  104874. * Dispose the material.
  104875. * @param forceDisposeEffect Force disposal of the associated effect.
  104876. * @param forceDisposeTextures Force disposal of the associated textures.
  104877. */
  104878. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  104879. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  104880. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  104881. if (forceDisposeTextures) {
  104882. if (this.diffuseTexture) {
  104883. this.diffuseTexture.dispose();
  104884. }
  104885. if (this.reflectionTexture) {
  104886. this.reflectionTexture.dispose();
  104887. }
  104888. }
  104889. this._renderTargets.dispose();
  104890. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  104891. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  104892. }
  104893. _super.prototype.dispose.call(this, forceDisposeEffect);
  104894. };
  104895. /**
  104896. * Clones the material.
  104897. * @param name The cloned name.
  104898. * @returns The cloned material.
  104899. */
  104900. BackgroundMaterial.prototype.clone = function (name) {
  104901. var _this = this;
  104902. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  104903. };
  104904. /**
  104905. * Serializes the current material to its JSON representation.
  104906. * @returns The JSON representation.
  104907. */
  104908. BackgroundMaterial.prototype.serialize = function () {
  104909. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  104910. serializationObject.customType = "BABYLON.BackgroundMaterial";
  104911. return serializationObject;
  104912. };
  104913. /**
  104914. * Gets the class name of the material
  104915. * @returns "BackgroundMaterial"
  104916. */
  104917. BackgroundMaterial.prototype.getClassName = function () {
  104918. return "BackgroundMaterial";
  104919. };
  104920. /**
  104921. * Parse a JSON input to create back a background material.
  104922. * @param source The JSON data to parse
  104923. * @param scene The scene to create the parsed material in
  104924. * @param rootUrl The root url of the assets the material depends upon
  104925. * @returns the instantiated BackgroundMaterial.
  104926. */
  104927. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  104928. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  104929. };
  104930. /**
  104931. * Standard reflectance value at parallel view angle.
  104932. */
  104933. BackgroundMaterial.StandardReflectance0 = 0.05;
  104934. /**
  104935. * Standard reflectance value at grazing angle.
  104936. */
  104937. BackgroundMaterial.StandardReflectance90 = 0.5;
  104938. __decorate([
  104939. BABYLON.serializeAsColor3()
  104940. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  104941. __decorate([
  104942. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  104943. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  104944. __decorate([
  104945. BABYLON.serializeAsColor3()
  104946. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  104947. __decorate([
  104948. BABYLON.serialize()
  104949. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  104950. __decorate([
  104951. BABYLON.serialize()
  104952. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  104953. __decorate([
  104954. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  104955. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  104956. __decorate([
  104957. BABYLON.serializeAsTexture()
  104958. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  104959. __decorate([
  104960. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  104961. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  104962. __decorate([
  104963. BABYLON.serialize()
  104964. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  104965. __decorate([
  104966. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  104967. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  104968. __decorate([
  104969. BABYLON.serializeAsTexture()
  104970. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  104971. __decorate([
  104972. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  104973. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  104974. __decorate([
  104975. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  104976. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  104977. __decorate([
  104978. BABYLON.serialize()
  104979. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  104980. __decorate([
  104981. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  104982. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  104983. __decorate([
  104984. BABYLON.serializeAsVector3()
  104985. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  104986. __decorate([
  104987. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  104988. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  104989. __decorate([
  104990. BABYLON.serialize()
  104991. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  104992. __decorate([
  104993. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  104994. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  104995. __decorate([
  104996. BABYLON.serialize()
  104997. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  104998. __decorate([
  104999. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105000. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  105001. __decorate([
  105002. BABYLON.serialize()
  105003. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  105004. __decorate([
  105005. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105006. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  105007. __decorate([
  105008. BABYLON.serialize()
  105009. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  105010. __decorate([
  105011. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105012. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  105013. __decorate([
  105014. BABYLON.serialize()
  105015. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  105016. __decorate([
  105017. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105018. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  105019. __decorate([
  105020. BABYLON.serialize()
  105021. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  105022. __decorate([
  105023. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105024. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  105025. __decorate([
  105026. BABYLON.serialize()
  105027. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  105028. __decorate([
  105029. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105030. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  105031. __decorate([
  105032. BABYLON.serialize()
  105033. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  105034. __decorate([
  105035. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105036. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  105037. __decorate([
  105038. BABYLON.serialize()
  105039. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  105040. __decorate([
  105041. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  105042. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  105043. __decorate([
  105044. BABYLON.serializeAsImageProcessingConfiguration()
  105045. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  105046. return BackgroundMaterial;
  105047. }(BABYLON.PushMaterial));
  105048. BABYLON.BackgroundMaterial = BackgroundMaterial;
  105049. })(BABYLON || (BABYLON = {}));
  105050. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  105051. var __assign = (this && this.__assign) || function () {
  105052. __assign = Object.assign || function(t) {
  105053. for (var s, i = 1, n = arguments.length; i < n; i++) {
  105054. s = arguments[i];
  105055. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  105056. t[p] = s[p];
  105057. }
  105058. return t;
  105059. };
  105060. return __assign.apply(this, arguments);
  105061. };
  105062. var BABYLON;
  105063. (function (BABYLON) {
  105064. /**
  105065. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  105066. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  105067. * It also helps with the default setup of your imageProcessing configuration.
  105068. */
  105069. var EnvironmentHelper = /** @class */ (function () {
  105070. /**
  105071. * constructor
  105072. * @param options
  105073. * @param scene The scene to add the material to
  105074. */
  105075. function EnvironmentHelper(options, scene) {
  105076. var _this = this;
  105077. this._errorHandler = function (message, exception) {
  105078. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  105079. };
  105080. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  105081. this._scene = scene;
  105082. this.onErrorObservable = new BABYLON.Observable();
  105083. this._setupBackground();
  105084. this._setupImageProcessing();
  105085. }
  105086. /**
  105087. * Creates the default options for the helper.
  105088. */
  105089. EnvironmentHelper._getDefaultOptions = function () {
  105090. return {
  105091. createGround: true,
  105092. groundSize: 15,
  105093. groundTexture: this._groundTextureCDNUrl,
  105094. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  105095. groundOpacity: 0.9,
  105096. enableGroundShadow: true,
  105097. groundShadowLevel: 0.5,
  105098. enableGroundMirror: false,
  105099. groundMirrorSizeRatio: 0.3,
  105100. groundMirrorBlurKernel: 64,
  105101. groundMirrorAmount: 1,
  105102. groundMirrorFresnelWeight: 1,
  105103. groundMirrorFallOffDistance: 0,
  105104. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  105105. groundYBias: 0.00001,
  105106. createSkybox: true,
  105107. skyboxSize: 20,
  105108. skyboxTexture: this._skyboxTextureCDNUrl,
  105109. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  105110. backgroundYRotation: 0,
  105111. sizeAuto: true,
  105112. rootPosition: BABYLON.Vector3.Zero(),
  105113. setupImageProcessing: true,
  105114. environmentTexture: this._environmentTextureCDNUrl,
  105115. cameraExposure: 0.8,
  105116. cameraContrast: 1.2,
  105117. toneMappingEnabled: true,
  105118. };
  105119. };
  105120. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  105121. /**
  105122. * Gets the root mesh created by the helper.
  105123. */
  105124. get: function () {
  105125. return this._rootMesh;
  105126. },
  105127. enumerable: true,
  105128. configurable: true
  105129. });
  105130. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  105131. /**
  105132. * Gets the skybox created by the helper.
  105133. */
  105134. get: function () {
  105135. return this._skybox;
  105136. },
  105137. enumerable: true,
  105138. configurable: true
  105139. });
  105140. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  105141. /**
  105142. * Gets the skybox texture created by the helper.
  105143. */
  105144. get: function () {
  105145. return this._skyboxTexture;
  105146. },
  105147. enumerable: true,
  105148. configurable: true
  105149. });
  105150. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  105151. /**
  105152. * Gets the skybox material created by the helper.
  105153. */
  105154. get: function () {
  105155. return this._skyboxMaterial;
  105156. },
  105157. enumerable: true,
  105158. configurable: true
  105159. });
  105160. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  105161. /**
  105162. * Gets the ground mesh created by the helper.
  105163. */
  105164. get: function () {
  105165. return this._ground;
  105166. },
  105167. enumerable: true,
  105168. configurable: true
  105169. });
  105170. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  105171. /**
  105172. * Gets the ground texture created by the helper.
  105173. */
  105174. get: function () {
  105175. return this._groundTexture;
  105176. },
  105177. enumerable: true,
  105178. configurable: true
  105179. });
  105180. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  105181. /**
  105182. * Gets the ground mirror created by the helper.
  105183. */
  105184. get: function () {
  105185. return this._groundMirror;
  105186. },
  105187. enumerable: true,
  105188. configurable: true
  105189. });
  105190. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  105191. /**
  105192. * Gets the ground mirror render list to helps pushing the meshes
  105193. * you wish in the ground reflection.
  105194. */
  105195. get: function () {
  105196. if (this._groundMirror) {
  105197. return this._groundMirror.renderList;
  105198. }
  105199. return null;
  105200. },
  105201. enumerable: true,
  105202. configurable: true
  105203. });
  105204. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  105205. /**
  105206. * Gets the ground material created by the helper.
  105207. */
  105208. get: function () {
  105209. return this._groundMaterial;
  105210. },
  105211. enumerable: true,
  105212. configurable: true
  105213. });
  105214. /**
  105215. * Updates the background according to the new options
  105216. * @param options
  105217. */
  105218. EnvironmentHelper.prototype.updateOptions = function (options) {
  105219. var newOptions = __assign({}, this._options, options);
  105220. if (this._ground && !newOptions.createGround) {
  105221. this._ground.dispose();
  105222. this._ground = null;
  105223. }
  105224. if (this._groundMaterial && !newOptions.createGround) {
  105225. this._groundMaterial.dispose();
  105226. this._groundMaterial = null;
  105227. }
  105228. if (this._groundTexture) {
  105229. if (this._options.groundTexture != newOptions.groundTexture) {
  105230. this._groundTexture.dispose();
  105231. this._groundTexture = null;
  105232. }
  105233. }
  105234. if (this._skybox && !newOptions.createSkybox) {
  105235. this._skybox.dispose();
  105236. this._skybox = null;
  105237. }
  105238. if (this._skyboxMaterial && !newOptions.createSkybox) {
  105239. this._skyboxMaterial.dispose();
  105240. this._skyboxMaterial = null;
  105241. }
  105242. if (this._skyboxTexture) {
  105243. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  105244. this._skyboxTexture.dispose();
  105245. this._skyboxTexture = null;
  105246. }
  105247. }
  105248. if (this._groundMirror && !newOptions.enableGroundMirror) {
  105249. this._groundMirror.dispose();
  105250. this._groundMirror = null;
  105251. }
  105252. if (this._scene.environmentTexture) {
  105253. if (this._options.environmentTexture != newOptions.environmentTexture) {
  105254. this._scene.environmentTexture.dispose();
  105255. }
  105256. }
  105257. this._options = newOptions;
  105258. this._setupBackground();
  105259. this._setupImageProcessing();
  105260. };
  105261. /**
  105262. * Sets the primary color of all the available elements.
  105263. * @param color the main color to affect to the ground and the background
  105264. */
  105265. EnvironmentHelper.prototype.setMainColor = function (color) {
  105266. if (this.groundMaterial) {
  105267. this.groundMaterial.primaryColor = color;
  105268. }
  105269. if (this.skyboxMaterial) {
  105270. this.skyboxMaterial.primaryColor = color;
  105271. }
  105272. if (this.groundMirror) {
  105273. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  105274. }
  105275. };
  105276. /**
  105277. * Setup the image processing according to the specified options.
  105278. */
  105279. EnvironmentHelper.prototype._setupImageProcessing = function () {
  105280. if (this._options.setupImageProcessing) {
  105281. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  105282. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  105283. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  105284. this._setupEnvironmentTexture();
  105285. }
  105286. };
  105287. /**
  105288. * Setup the environment texture according to the specified options.
  105289. */
  105290. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  105291. if (this._scene.environmentTexture) {
  105292. return;
  105293. }
  105294. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  105295. this._scene.environmentTexture = this._options.environmentTexture;
  105296. return;
  105297. }
  105298. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  105299. this._scene.environmentTexture = environmentTexture;
  105300. };
  105301. /**
  105302. * Setup the background according to the specified options.
  105303. */
  105304. EnvironmentHelper.prototype._setupBackground = function () {
  105305. if (!this._rootMesh) {
  105306. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  105307. }
  105308. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  105309. var sceneSize = this._getSceneSize();
  105310. if (this._options.createGround) {
  105311. this._setupGround(sceneSize);
  105312. this._setupGroundMaterial();
  105313. this._setupGroundDiffuseTexture();
  105314. if (this._options.enableGroundMirror) {
  105315. this._setupGroundMirrorTexture(sceneSize);
  105316. }
  105317. this._setupMirrorInGroundMaterial();
  105318. }
  105319. if (this._options.createSkybox) {
  105320. this._setupSkybox(sceneSize);
  105321. this._setupSkyboxMaterial();
  105322. this._setupSkyboxReflectionTexture();
  105323. }
  105324. this._rootMesh.position.x = sceneSize.rootPosition.x;
  105325. this._rootMesh.position.z = sceneSize.rootPosition.z;
  105326. this._rootMesh.position.y = sceneSize.rootPosition.y;
  105327. };
  105328. /**
  105329. * Get the scene sizes according to the setup.
  105330. */
  105331. EnvironmentHelper.prototype._getSceneSize = function () {
  105332. var _this = this;
  105333. var groundSize = this._options.groundSize;
  105334. var skyboxSize = this._options.skyboxSize;
  105335. var rootPosition = this._options.rootPosition;
  105336. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  105337. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  105338. }
  105339. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  105340. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  105341. });
  105342. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  105343. if (this._options.sizeAuto) {
  105344. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  105345. this._scene.activeCamera.upperRadiusLimit) {
  105346. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  105347. skyboxSize = groundSize;
  105348. }
  105349. var sceneDiagonalLenght = sceneDiagonal.length();
  105350. if (sceneDiagonalLenght > groundSize) {
  105351. groundSize = sceneDiagonalLenght * 2;
  105352. skyboxSize = groundSize;
  105353. }
  105354. // 10 % bigger.
  105355. groundSize *= 1.1;
  105356. skyboxSize *= 1.5;
  105357. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  105358. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  105359. }
  105360. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  105361. };
  105362. /**
  105363. * Setup the ground according to the specified options.
  105364. */
  105365. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  105366. var _this = this;
  105367. if (!this._ground || this._ground.isDisposed()) {
  105368. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  105369. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  105370. this._ground.parent = this._rootMesh;
  105371. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  105372. }
  105373. this._ground.receiveShadows = this._options.enableGroundShadow;
  105374. };
  105375. /**
  105376. * Setup the ground material according to the specified options.
  105377. */
  105378. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  105379. if (!this._groundMaterial) {
  105380. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  105381. }
  105382. this._groundMaterial.alpha = this._options.groundOpacity;
  105383. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  105384. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  105385. this._groundMaterial.primaryColor = this._options.groundColor;
  105386. this._groundMaterial.useRGBColor = false;
  105387. this._groundMaterial.enableNoise = true;
  105388. if (this._ground) {
  105389. this._ground.material = this._groundMaterial;
  105390. }
  105391. };
  105392. /**
  105393. * Setup the ground diffuse texture according to the specified options.
  105394. */
  105395. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  105396. if (!this._groundMaterial) {
  105397. return;
  105398. }
  105399. if (this._groundTexture) {
  105400. return;
  105401. }
  105402. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  105403. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  105404. return;
  105405. }
  105406. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  105407. diffuseTexture.gammaSpace = false;
  105408. diffuseTexture.hasAlpha = true;
  105409. this._groundMaterial.diffuseTexture = diffuseTexture;
  105410. };
  105411. /**
  105412. * Setup the ground mirror texture according to the specified options.
  105413. */
  105414. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  105415. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105416. if (!this._groundMirror) {
  105417. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  105418. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  105419. this._groundMirror.anisotropicFilteringLevel = 1;
  105420. this._groundMirror.wrapU = wrapping;
  105421. this._groundMirror.wrapV = wrapping;
  105422. this._groundMirror.gammaSpace = false;
  105423. if (this._groundMirror.renderList) {
  105424. for (var i = 0; i < this._scene.meshes.length; i++) {
  105425. var mesh = this._scene.meshes[i];
  105426. if (mesh !== this._ground &&
  105427. mesh !== this._skybox &&
  105428. mesh !== this._rootMesh) {
  105429. this._groundMirror.renderList.push(mesh);
  105430. }
  105431. }
  105432. }
  105433. }
  105434. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  105435. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  105436. };
  105437. /**
  105438. * Setup the ground to receive the mirror texture.
  105439. */
  105440. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  105441. if (this._groundMaterial) {
  105442. this._groundMaterial.reflectionTexture = this._groundMirror;
  105443. this._groundMaterial.reflectionFresnel = true;
  105444. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  105445. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  105446. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  105447. }
  105448. };
  105449. /**
  105450. * Setup the skybox according to the specified options.
  105451. */
  105452. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  105453. var _this = this;
  105454. if (!this._skybox || this._skybox.isDisposed()) {
  105455. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  105456. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  105457. }
  105458. this._skybox.parent = this._rootMesh;
  105459. };
  105460. /**
  105461. * Setup the skybox material according to the specified options.
  105462. */
  105463. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  105464. if (!this._skybox) {
  105465. return;
  105466. }
  105467. if (!this._skyboxMaterial) {
  105468. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  105469. }
  105470. this._skyboxMaterial.useRGBColor = false;
  105471. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  105472. this._skyboxMaterial.enableNoise = true;
  105473. this._skybox.material = this._skyboxMaterial;
  105474. };
  105475. /**
  105476. * Setup the skybox reflection texture according to the specified options.
  105477. */
  105478. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  105479. if (!this._skyboxMaterial) {
  105480. return;
  105481. }
  105482. if (this._skyboxTexture) {
  105483. return;
  105484. }
  105485. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  105486. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  105487. return;
  105488. }
  105489. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  105490. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  105491. this._skyboxTexture.gammaSpace = false;
  105492. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  105493. };
  105494. /**
  105495. * Dispose all the elements created by the Helper.
  105496. */
  105497. EnvironmentHelper.prototype.dispose = function () {
  105498. if (this._groundMaterial) {
  105499. this._groundMaterial.dispose(true, true);
  105500. }
  105501. if (this._skyboxMaterial) {
  105502. this._skyboxMaterial.dispose(true, true);
  105503. }
  105504. this._rootMesh.dispose(false);
  105505. };
  105506. /**
  105507. * Default ground texture URL.
  105508. */
  105509. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  105510. /**
  105511. * Default skybox texture URL.
  105512. */
  105513. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  105514. /**
  105515. * Default environment texture URL.
  105516. */
  105517. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  105518. return EnvironmentHelper;
  105519. }());
  105520. BABYLON.EnvironmentHelper = EnvironmentHelper;
  105521. })(BABYLON || (BABYLON = {}));
  105522. //# sourceMappingURL=babylon.environmentHelper.js.map
  105523. var BABYLON;
  105524. (function (BABYLON) {
  105525. /** Internal class used to store shapes for emitters */
  105526. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  105527. function ParticleSystemSetEmitterCreationOptions() {
  105528. }
  105529. return ParticleSystemSetEmitterCreationOptions;
  105530. }());
  105531. /**
  105532. * Represents a set of particle systems working together to create a specific effect
  105533. */
  105534. var ParticleSystemSet = /** @class */ (function () {
  105535. function ParticleSystemSet() {
  105536. /**
  105537. * Gets the particle system list
  105538. */
  105539. this.systems = new Array();
  105540. }
  105541. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  105542. /**
  105543. * Gets the emitter node used with this set
  105544. */
  105545. get: function () {
  105546. return this._emitterNode;
  105547. },
  105548. enumerable: true,
  105549. configurable: true
  105550. });
  105551. /**
  105552. * Creates a new emitter mesh as a sphere
  105553. * @param options defines the options used to create the sphere
  105554. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  105555. * @param scene defines the hosting scene
  105556. */
  105557. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  105558. if (this._emitterNode) {
  105559. this._emitterNode.dispose();
  105560. }
  105561. this._emitterCreationOptions = {
  105562. kind: "Sphere",
  105563. options: options,
  105564. renderingGroupId: renderingGroupId
  105565. };
  105566. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  105567. emitterMesh.renderingGroupId = renderingGroupId;
  105568. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  105569. material.emissiveColor = options.color;
  105570. emitterMesh.material = material;
  105571. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  105572. var system = _a[_i];
  105573. system.emitter = emitterMesh;
  105574. }
  105575. this._emitterNode = emitterMesh;
  105576. };
  105577. /**
  105578. * Starts all particle systems of the set
  105579. * @param emitter defines an optional mesh to use as emitter for the particle systems
  105580. */
  105581. ParticleSystemSet.prototype.start = function (emitter) {
  105582. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  105583. var system = _a[_i];
  105584. if (emitter) {
  105585. system.emitter = emitter;
  105586. }
  105587. system.start();
  105588. }
  105589. };
  105590. /**
  105591. * Release all associated resources
  105592. */
  105593. ParticleSystemSet.prototype.dispose = function () {
  105594. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  105595. var system = _a[_i];
  105596. system.dispose();
  105597. }
  105598. this.systems = [];
  105599. if (this._emitterNode) {
  105600. this._emitterNode.dispose();
  105601. this._emitterNode = null;
  105602. }
  105603. };
  105604. /**
  105605. * Serialize the set into a JSON compatible object
  105606. * @returns a JSON compatible representation of the set
  105607. */
  105608. ParticleSystemSet.prototype.serialize = function () {
  105609. var result = {};
  105610. result.systems = [];
  105611. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  105612. var system = _a[_i];
  105613. result.systems.push(system.serialize());
  105614. }
  105615. if (this._emitterNode) {
  105616. result.emitter = this._emitterCreationOptions;
  105617. }
  105618. return result;
  105619. };
  105620. /**
  105621. * Parse a new ParticleSystemSet from a serialized source
  105622. * @param data defines a JSON compatible representation of the set
  105623. * @param scene defines the hosting scene
  105624. * @param gpu defines if we want GPU particles or CPU particles
  105625. * @returns a new ParticleSystemSet
  105626. */
  105627. ParticleSystemSet.Parse = function (data, scene, gpu) {
  105628. if (gpu === void 0) { gpu = false; }
  105629. var result = new ParticleSystemSet();
  105630. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  105631. scene = scene || BABYLON.Engine.LastCreatedScene;
  105632. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  105633. var system = _a[_i];
  105634. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  105635. }
  105636. if (data.emitter) {
  105637. var options = data.emitter.options;
  105638. switch (data.emitter.kind) {
  105639. case "Sphere":
  105640. result.setEmitterAsSphere({
  105641. diameter: options.diameter,
  105642. segments: options.segments,
  105643. color: BABYLON.Color3.FromArray(options.color)
  105644. }, data.emitter.renderingGroupId, scene);
  105645. break;
  105646. }
  105647. }
  105648. return result;
  105649. };
  105650. return ParticleSystemSet;
  105651. }());
  105652. BABYLON.ParticleSystemSet = ParticleSystemSet;
  105653. })(BABYLON || (BABYLON = {}));
  105654. //# sourceMappingURL=babylon.particleSystemSet.js.map
  105655. var BABYLON;
  105656. (function (BABYLON) {
  105657. /**
  105658. * This class is made for on one-liner static method to help creating particle system set.
  105659. */
  105660. var ParticleHelper = /** @class */ (function () {
  105661. function ParticleHelper() {
  105662. }
  105663. /**
  105664. * Create a default particle system that you can tweak
  105665. * @param emitter defines the emitter to use
  105666. * @param capacity defines the system capacity (default is 500 particles)
  105667. * @param scene defines the hosting scene
  105668. * @returns the new Particle system
  105669. */
  105670. ParticleHelper.CreateDefault = function (emitter, capacity, scene) {
  105671. if (capacity === void 0) { capacity = 500; }
  105672. var system = new BABYLON.ParticleSystem("default system", capacity, scene);
  105673. system.emitter = emitter;
  105674. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  105675. system.createConeEmitter(0.1, Math.PI / 4);
  105676. // Particle color
  105677. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  105678. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  105679. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  105680. // Particle Size
  105681. system.minSize = 0.1;
  105682. system.maxSize = 0.1;
  105683. // Emission speed
  105684. system.minEmitPower = 2;
  105685. system.maxEmitPower = 2;
  105686. // Update speed
  105687. system.updateSpeed = 1 / 60;
  105688. system.emitRate = 30;
  105689. return system;
  105690. };
  105691. /**
  105692. * This is the main static method (one-liner) of this helper to create different particle systems
  105693. * @param type This string represents the type to the particle system to create
  105694. * @param scene The scene where the particle system should live
  105695. * @param gpu If the system will use gpu
  105696. * @returns the ParticleSystemSet created
  105697. */
  105698. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  105699. if (gpu === void 0) { gpu = false; }
  105700. if (!scene) {
  105701. scene = BABYLON.Engine.LastCreatedScene;
  105702. ;
  105703. }
  105704. var token = {};
  105705. scene._addPendingData(token);
  105706. return new Promise(function (resolve, reject) {
  105707. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  105708. scene._removePendingData(token);
  105709. return reject("Particle system with GPU is not supported.");
  105710. }
  105711. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  105712. scene._removePendingData(token);
  105713. var newData = JSON.parse(data.toString());
  105714. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  105715. }, undefined, undefined, undefined, function (req, exception) {
  105716. scene._removePendingData(token);
  105717. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  105718. });
  105719. });
  105720. };
  105721. /**
  105722. * Static function used to export a particle system to a ParticleSystemSet variable.
  105723. * Please note that the emitter shape is not exported
  105724. * @param system defines the particle systems to export
  105725. */
  105726. ParticleHelper.ExportSet = function (systems) {
  105727. var set = new BABYLON.ParticleSystemSet();
  105728. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  105729. var system = systems_1[_i];
  105730. set.systems.push(system);
  105731. }
  105732. return set;
  105733. };
  105734. /**
  105735. * Gets or sets base Assets URL
  105736. */
  105737. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  105738. return ParticleHelper;
  105739. }());
  105740. BABYLON.ParticleHelper = ParticleHelper;
  105741. })(BABYLON || (BABYLON = {}));
  105742. //# sourceMappingURL=babylon.particleHelper.js.map
  105743. var BABYLON;
  105744. (function (BABYLON) {
  105745. /**
  105746. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  105747. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  105748. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  105749. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  105750. */
  105751. var VideoDome = /** @class */ (function (_super) {
  105752. __extends(VideoDome, _super);
  105753. /**
  105754. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  105755. * @param name Element's name, child elements will append suffixes for their own names.
  105756. * @param urlsOrVideo defines the url(s) or the video element to use
  105757. * @param options An object containing optional or exposed sub element properties
  105758. */
  105759. function VideoDome(name, urlsOrVideo, options, scene) {
  105760. var _this = _super.call(this, name, scene) || this;
  105761. _this._useDirectMapping = false;
  105762. // set defaults and manage values
  105763. name = name || "videoDome";
  105764. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  105765. options.clickToPlay = Boolean(options.clickToPlay);
  105766. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  105767. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  105768. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  105769. if (options.useDirectMapping === undefined) {
  105770. _this._useDirectMapping = true;
  105771. }
  105772. else {
  105773. _this._useDirectMapping = options.useDirectMapping;
  105774. }
  105775. _this._setReady(false);
  105776. // create
  105777. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  105778. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  105779. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  105780. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  105781. texture.onLoadObservable.addOnce(function () {
  105782. _this._setReady(true);
  105783. });
  105784. // configure material
  105785. material.useEquirectangularFOV = true;
  105786. material.fovMultiplier = 1.0;
  105787. material.opacityFresnel = false;
  105788. if (_this._useDirectMapping) {
  105789. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105790. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105791. material.diffuseTexture = texture;
  105792. }
  105793. else {
  105794. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  105795. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105796. material.reflectionTexture = texture;
  105797. }
  105798. // configure mesh
  105799. _this._mesh.material = material;
  105800. _this._mesh.parent = _this;
  105801. // optional configuration
  105802. if (options.clickToPlay) {
  105803. scene.onPointerUp = function () {
  105804. _this._videoTexture.video.play();
  105805. };
  105806. }
  105807. return _this;
  105808. }
  105809. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  105810. /**
  105811. * Gets the video texture being displayed on the sphere
  105812. */
  105813. get: function () {
  105814. return this._videoTexture;
  105815. },
  105816. enumerable: true,
  105817. configurable: true
  105818. });
  105819. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  105820. /**
  105821. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  105822. * Also see the options.resolution property.
  105823. */
  105824. get: function () {
  105825. return this._material.fovMultiplier;
  105826. },
  105827. set: function (value) {
  105828. this._material.fovMultiplier = value;
  105829. },
  105830. enumerable: true,
  105831. configurable: true
  105832. });
  105833. /**
  105834. * Releases resources associated with this node.
  105835. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  105836. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  105837. */
  105838. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  105839. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  105840. this._videoTexture.dispose();
  105841. this._mesh.dispose();
  105842. this._material.dispose();
  105843. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  105844. };
  105845. return VideoDome;
  105846. }(BABYLON.TransformNode));
  105847. BABYLON.VideoDome = VideoDome;
  105848. })(BABYLON || (BABYLON = {}));
  105849. //# sourceMappingURL=babylon.videoDome.js.map
  105850. var BABYLON;
  105851. (function (BABYLON) {
  105852. /**
  105853. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  105854. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  105855. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  105856. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  105857. */
  105858. var PhotoDome = /** @class */ (function (_super) {
  105859. __extends(PhotoDome, _super);
  105860. /**
  105861. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  105862. * @param name Element's name, child elements will append suffixes for their own names.
  105863. * @param urlsOfPhoto defines the url of the photo to display
  105864. * @param options defines an object containing optional or exposed sub element properties
  105865. * @param onError defines a callback called when an error occured while loading the texture
  105866. */
  105867. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  105868. if (onError === void 0) { onError = null; }
  105869. var _this = _super.call(this, name, scene) || this;
  105870. _this._useDirectMapping = false;
  105871. /**
  105872. * Observable raised when an error occured while loading the 360 image
  105873. */
  105874. _this.onLoadErrorObservable = new BABYLON.Observable();
  105875. // set defaults and manage values
  105876. name = name || "photoDome";
  105877. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  105878. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  105879. if (options.useDirectMapping === undefined) {
  105880. _this._useDirectMapping = true;
  105881. }
  105882. else {
  105883. _this._useDirectMapping = options.useDirectMapping;
  105884. }
  105885. _this._setReady(false);
  105886. // create
  105887. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  105888. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  105889. // configure material
  105890. material.opacityFresnel = false;
  105891. material.useEquirectangularFOV = true;
  105892. material.fovMultiplier = 1.0;
  105893. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  105894. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  105895. if (onError) {
  105896. onError(message, exception);
  105897. }
  105898. });
  105899. _this.photoTexture.onLoadObservable.addOnce(function () {
  105900. _this._setReady(true);
  105901. });
  105902. // configure mesh
  105903. _this._mesh.material = material;
  105904. _this._mesh.parent = _this;
  105905. return _this;
  105906. }
  105907. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  105908. /**
  105909. * Gets or sets the texture being displayed on the sphere
  105910. */
  105911. get: function () {
  105912. return this._photoTexture;
  105913. },
  105914. set: function (value) {
  105915. if (this._photoTexture === value) {
  105916. return;
  105917. }
  105918. this._photoTexture = value;
  105919. if (this._useDirectMapping) {
  105920. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105921. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105922. this._material.diffuseTexture = this._photoTexture;
  105923. }
  105924. else {
  105925. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  105926. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  105927. this._material.reflectionTexture = this._photoTexture;
  105928. }
  105929. },
  105930. enumerable: true,
  105931. configurable: true
  105932. });
  105933. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  105934. /**
  105935. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  105936. * Also see the options.resolution property.
  105937. */
  105938. get: function () {
  105939. return this._material.fovMultiplier;
  105940. },
  105941. set: function (value) {
  105942. this._material.fovMultiplier = value;
  105943. },
  105944. enumerable: true,
  105945. configurable: true
  105946. });
  105947. /**
  105948. * Releases resources associated with this node.
  105949. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  105950. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  105951. */
  105952. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  105953. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  105954. this._photoTexture.dispose();
  105955. this._mesh.dispose();
  105956. this._material.dispose();
  105957. this.onLoadErrorObservable.clear();
  105958. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  105959. };
  105960. return PhotoDome;
  105961. }(BABYLON.TransformNode));
  105962. BABYLON.PhotoDome = PhotoDome;
  105963. })(BABYLON || (BABYLON = {}));
  105964. //# sourceMappingURL=babylon.photoDome.js.map
  105965. var BABYLON;
  105966. (function (BABYLON) {
  105967. BABYLON.Engine.prototype.createQuery = function () {
  105968. return this._gl.createQuery();
  105969. };
  105970. BABYLON.Engine.prototype.deleteQuery = function (query) {
  105971. this._gl.deleteQuery(query);
  105972. return this;
  105973. };
  105974. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  105975. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  105976. };
  105977. BABYLON.Engine.prototype.getQueryResult = function (query) {
  105978. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  105979. };
  105980. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  105981. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  105982. this._gl.beginQuery(glAlgorithm, query);
  105983. return this;
  105984. };
  105985. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  105986. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  105987. this._gl.endQuery(glAlgorithm);
  105988. return this;
  105989. };
  105990. BABYLON.Engine.prototype._createTimeQuery = function () {
  105991. var timerQuery = this.getCaps().timerQuery;
  105992. if (timerQuery.createQueryEXT) {
  105993. return timerQuery.createQueryEXT();
  105994. }
  105995. return this.createQuery();
  105996. };
  105997. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  105998. var timerQuery = this.getCaps().timerQuery;
  105999. if (timerQuery.deleteQueryEXT) {
  106000. timerQuery.deleteQueryEXT(query);
  106001. return;
  106002. }
  106003. this.deleteQuery(query);
  106004. };
  106005. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  106006. var timerQuery = this.getCaps().timerQuery;
  106007. if (timerQuery.getQueryObjectEXT) {
  106008. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  106009. }
  106010. return this.getQueryResult(query);
  106011. };
  106012. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  106013. var timerQuery = this.getCaps().timerQuery;
  106014. if (timerQuery.getQueryObjectEXT) {
  106015. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  106016. }
  106017. return this.isQueryResultAvailable(query);
  106018. };
  106019. BABYLON.Engine.prototype.startTimeQuery = function () {
  106020. var caps = this.getCaps();
  106021. var timerQuery = caps.timerQuery;
  106022. if (!timerQuery) {
  106023. return null;
  106024. }
  106025. var token = new BABYLON._TimeToken();
  106026. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  106027. if (caps.canUseTimestampForTimerQuery) {
  106028. token._startTimeQuery = this._createTimeQuery();
  106029. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  106030. }
  106031. else {
  106032. if (this._currentNonTimestampToken) {
  106033. return this._currentNonTimestampToken;
  106034. }
  106035. token._timeElapsedQuery = this._createTimeQuery();
  106036. if (timerQuery.beginQueryEXT) {
  106037. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  106038. }
  106039. else {
  106040. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  106041. }
  106042. this._currentNonTimestampToken = token;
  106043. }
  106044. return token;
  106045. };
  106046. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  106047. var caps = this.getCaps();
  106048. var timerQuery = caps.timerQuery;
  106049. if (!timerQuery || !token) {
  106050. return -1;
  106051. }
  106052. if (caps.canUseTimestampForTimerQuery) {
  106053. if (!token._startTimeQuery) {
  106054. return -1;
  106055. }
  106056. if (!token._endTimeQuery) {
  106057. token._endTimeQuery = this._createTimeQuery();
  106058. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  106059. }
  106060. }
  106061. else if (!token._timeElapsedQueryEnded) {
  106062. if (!token._timeElapsedQuery) {
  106063. return -1;
  106064. }
  106065. if (timerQuery.endQueryEXT) {
  106066. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  106067. }
  106068. else {
  106069. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  106070. }
  106071. token._timeElapsedQueryEnded = true;
  106072. }
  106073. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  106074. var available = false;
  106075. if (token._endTimeQuery) {
  106076. available = this._getTimeQueryAvailability(token._endTimeQuery);
  106077. }
  106078. else if (token._timeElapsedQuery) {
  106079. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  106080. }
  106081. if (available && !disjoint) {
  106082. var result = 0;
  106083. if (caps.canUseTimestampForTimerQuery) {
  106084. if (!token._startTimeQuery || !token._endTimeQuery) {
  106085. return -1;
  106086. }
  106087. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  106088. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  106089. result = timeEnd - timeStart;
  106090. this._deleteTimeQuery(token._startTimeQuery);
  106091. this._deleteTimeQuery(token._endTimeQuery);
  106092. token._startTimeQuery = null;
  106093. token._endTimeQuery = null;
  106094. }
  106095. else {
  106096. if (!token._timeElapsedQuery) {
  106097. return -1;
  106098. }
  106099. result = this._getTimeQueryResult(token._timeElapsedQuery);
  106100. this._deleteTimeQuery(token._timeElapsedQuery);
  106101. token._timeElapsedQuery = null;
  106102. token._timeElapsedQueryEnded = false;
  106103. this._currentNonTimestampToken = null;
  106104. }
  106105. return result;
  106106. }
  106107. return -1;
  106108. };
  106109. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  106110. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  106111. };
  106112. // We also need to update AbstractMesh as there is a portion of the code there
  106113. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  106114. var engine = this.getEngine();
  106115. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  106116. this._isOccluded = false;
  106117. return;
  106118. }
  106119. if (engine.webGLVersion < 2 || this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  106120. this._isOccluded = false;
  106121. return;
  106122. }
  106123. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  106124. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  106125. if (isOcclusionQueryAvailable) {
  106126. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  106127. this._isOcclusionQueryInProgress = false;
  106128. this._occlusionInternalRetryCounter = 0;
  106129. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  106130. }
  106131. else {
  106132. this._occlusionInternalRetryCounter++;
  106133. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  106134. this._isOcclusionQueryInProgress = false;
  106135. this._occlusionInternalRetryCounter = 0;
  106136. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  106137. // if strict continue the last state of the object.
  106138. this._isOccluded = this.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  106139. }
  106140. else {
  106141. return;
  106142. }
  106143. }
  106144. }
  106145. var scene = this.getScene();
  106146. if (scene.getBoundingBoxRenderer) {
  106147. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  106148. if (!this._occlusionQuery) {
  106149. this._occlusionQuery = engine.createQuery();
  106150. }
  106151. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  106152. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  106153. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  106154. this._isOcclusionQueryInProgress = true;
  106155. }
  106156. };
  106157. })(BABYLON || (BABYLON = {}));
  106158. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  106159. var BABYLON;
  106160. (function (BABYLON) {
  106161. /**
  106162. * Class used to generate noise procedural textures
  106163. */
  106164. var NoiseProceduralTexture = /** @class */ (function (_super) {
  106165. __extends(NoiseProceduralTexture, _super);
  106166. /**
  106167. * Creates a new NoiseProceduralTexture
  106168. * @param name defines the name fo the texture
  106169. * @param size defines the size of the texture (default is 256)
  106170. * @param scene defines the hosting scene
  106171. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  106172. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  106173. */
  106174. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  106175. if (size === void 0) { size = 256; }
  106176. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  106177. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  106178. _this._time = 0;
  106179. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  106180. _this.brightness = 0.2;
  106181. /** Defines the number of octaves to process */
  106182. _this.octaves = 3;
  106183. /** Defines the level of persistence (0.8 by default) */
  106184. _this.persistence = 0.8;
  106185. /** Gets or sets animation speed factor (default is 1) */
  106186. _this.animationSpeedFactor = 1;
  106187. _this._updateShaderUniforms();
  106188. return _this;
  106189. }
  106190. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  106191. var scene = this.getScene();
  106192. if (!scene) {
  106193. return;
  106194. }
  106195. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  106196. this.setFloat("brightness", this.brightness);
  106197. this.setInt("octaves", this.octaves);
  106198. this.setFloat("persistence", this.persistence);
  106199. this.setFloat("timeScale", this._time);
  106200. };
  106201. /** Generate the current state of the procedural texture */
  106202. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  106203. this._updateShaderUniforms();
  106204. _super.prototype.render.call(this, useCameraPostProcess);
  106205. };
  106206. /**
  106207. * Serializes this noise procedural texture
  106208. * @returns a serialized noise procedural texture object
  106209. */
  106210. NoiseProceduralTexture.prototype.serialize = function () {
  106211. var serializationObject = BABYLON.SerializationHelper.Serialize(this, _super.prototype.serialize.call(this));
  106212. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  106213. return serializationObject;
  106214. };
  106215. /**
  106216. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  106217. * @param parsedTexture defines parsed texture data
  106218. * @param scene defines the current scene
  106219. * @param rootUrl defines the root URL containing noise procedural texture information
  106220. * @returns a parsed NoiseProceduralTexture
  106221. */
  106222. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  106223. var texture = BABYLON.SerializationHelper.Parse(function () { return new NoiseProceduralTexture(parsedTexture.name, parsedTexture._size, scene, undefined, parsedTexture._generateMipMaps); }, parsedTexture, scene, rootUrl);
  106224. return texture;
  106225. };
  106226. return NoiseProceduralTexture;
  106227. }(BABYLON.ProceduralTexture));
  106228. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  106229. })(BABYLON || (BABYLON = {}));
  106230. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  106231. var __assign = (this && this.__assign) || function () {
  106232. __assign = Object.assign || function(t) {
  106233. for (var s, i = 1, n = arguments.length; i < n; i++) {
  106234. s = arguments[i];
  106235. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  106236. t[p] = s[p];
  106237. }
  106238. return t;
  106239. };
  106240. return __assign.apply(this, arguments);
  106241. };
  106242. var BABYLON;
  106243. (function (BABYLON) {
  106244. /**
  106245. * This can helps recording videos from BabylonJS.
  106246. * This is based on the available WebRTC functionalities of the browser.
  106247. *
  106248. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  106249. */
  106250. var VideoRecorder = /** @class */ (function () {
  106251. /**
  106252. * Create a new VideoCapture object which can help converting what you see in Babylon to
  106253. * a video file.
  106254. * @param engine Defines the BabylonJS Engine you wish to record
  106255. * @param options Defines options that can be used to customized the capture
  106256. */
  106257. function VideoRecorder(engine, options) {
  106258. if (options === void 0) { options = null; }
  106259. if (!VideoRecorder.IsSupported(engine)) {
  106260. throw "Your browser does not support recording so far.";
  106261. }
  106262. var canvas = engine.getRenderingCanvas();
  106263. if (!canvas) {
  106264. throw "The babylon engine must have a canvas to be recorded";
  106265. }
  106266. this._canvas = canvas;
  106267. this._canvas.isRecording = false;
  106268. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  106269. var stream = this._canvas.captureStream(this._options.fps);
  106270. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  106271. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  106272. this._mediaRecorder.onerror = this._handleError.bind(this);
  106273. this._mediaRecorder.onstop = this._handleStop.bind(this);
  106274. }
  106275. /**
  106276. * Returns wehther or not the VideoRecorder is available in your browser.
  106277. * @param engine Defines the Babylon Engine to check the support for
  106278. * @returns true if supported otherwise false
  106279. */
  106280. VideoRecorder.IsSupported = function (engine) {
  106281. var canvas = engine.getRenderingCanvas();
  106282. return (!!canvas && typeof canvas.captureStream === "function");
  106283. };
  106284. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  106285. /**
  106286. * True wether a recording is already in progress.
  106287. */
  106288. get: function () {
  106289. return !!this._canvas && this._canvas.isRecording;
  106290. },
  106291. enumerable: true,
  106292. configurable: true
  106293. });
  106294. /**
  106295. * Stops the current recording before the default capture timeout passed in the startRecording
  106296. * functions.
  106297. */
  106298. VideoRecorder.prototype.stopRecording = function () {
  106299. if (!this._canvas || !this._mediaRecorder) {
  106300. return;
  106301. }
  106302. if (!this.isRecording) {
  106303. return;
  106304. }
  106305. this._canvas.isRecording = false;
  106306. this._mediaRecorder.stop();
  106307. };
  106308. /**
  106309. * Starts recording the canvas for a max duration specified in parameters.
  106310. * @param fileName Defines the name of the file to be downloaded when the recording stop. If null no automatic download will start and you can rely on the promise to get the data back.
  106311. * @param maxDuration Defines the maximum recording time in seconds.
  106312. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  106313. * @return a promise callback at the end of the recording with the video data in Blob.
  106314. */
  106315. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  106316. var _this = this;
  106317. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  106318. if (maxDuration === void 0) { maxDuration = 7; }
  106319. if (!this._canvas || !this._mediaRecorder) {
  106320. throw "Recorder has already been disposed";
  106321. }
  106322. if (this.isRecording) {
  106323. throw "Recording already in progress";
  106324. }
  106325. if (maxDuration > 0) {
  106326. setTimeout(function () {
  106327. _this.stopRecording();
  106328. }, maxDuration * 1000);
  106329. }
  106330. this._fileName = fileName;
  106331. this._recordedChunks = [];
  106332. this._resolve = null;
  106333. this._reject = null;
  106334. this._canvas.isRecording = true;
  106335. this._mediaRecorder.start(this._options.recordChunckSize);
  106336. return new Promise(function (resolve, reject) {
  106337. _this._resolve = resolve;
  106338. _this._reject = reject;
  106339. });
  106340. };
  106341. /**
  106342. * Releases internal resources used during the recording.
  106343. */
  106344. VideoRecorder.prototype.dispose = function () {
  106345. this._canvas = null;
  106346. this._mediaRecorder = null;
  106347. this._recordedChunks = [];
  106348. this._fileName = null;
  106349. this._resolve = null;
  106350. this._reject = null;
  106351. };
  106352. VideoRecorder.prototype._handleDataAvailable = function (event) {
  106353. if (event.data.size > 0) {
  106354. this._recordedChunks.push(event.data);
  106355. }
  106356. };
  106357. VideoRecorder.prototype._handleError = function (event) {
  106358. this.stopRecording();
  106359. if (this._reject) {
  106360. this._reject(event.error);
  106361. }
  106362. else {
  106363. throw new event.error;
  106364. }
  106365. };
  106366. VideoRecorder.prototype._handleStop = function () {
  106367. this.stopRecording();
  106368. var superBuffer = new Blob(this._recordedChunks);
  106369. if (this._resolve) {
  106370. this._resolve(superBuffer);
  106371. }
  106372. window.URL.createObjectURL(superBuffer);
  106373. if (this._fileName) {
  106374. BABYLON.Tools.Download(superBuffer, this._fileName);
  106375. }
  106376. };
  106377. VideoRecorder._defaultOptions = {
  106378. mimeType: "video/webm",
  106379. fps: 25,
  106380. recordChunckSize: 3000
  106381. };
  106382. return VideoRecorder;
  106383. }());
  106384. BABYLON.VideoRecorder = VideoRecorder;
  106385. })(BABYLON || (BABYLON = {}));
  106386. //# sourceMappingURL=babylon.videoRecorder.js.map
  106387. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  106388. globalObject["BABYLON"] = BABYLON;
  106389. //backwards compatibility
  106390. if(typeof earcut !== 'undefined') {
  106391. globalObject["Earcut"] = {
  106392. earcut: earcut
  106393. };
  106394. }
  106395. return BABYLON;
  106396. });